diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..be96a4f14 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +/.github/ export-ignore +/tests/ export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.php_cs.dist export-ignore +/.php-cs-fixer.dist.php export-ignore +/CHANGELOG.md export-ignore +/phpstan.neon export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..80f6aa6f5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: continuous-integration +on: + push: + branches: + - master + - release/* + pull_request: +jobs: + unit-testing: + name: PHPUnit (PHP ${{ matrix.php-versions }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php-versions: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4'] + coverage: ['pcov'] + code-style: ['no'] + code-analysis: ['no'] + include: + - php-versions: '8.5' + coverage: 'none' + code-style: 'no' + code-analysis: 'yes' + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 #https://github.com/shivammathur/setup-php + with: + php-version: ${{ matrix.php-versions }} + extensions: mbstring, dom, fileinfo, mysql, redis, opcache + coverage: ${{ matrix.coverage }} + tools: composer + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v5 + with: + path: ${{ steps.composer-cache.outputs.dir }} + # Use composer.json for key, if composer.lock is not committed. + # key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install composer dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Code Analysis (PHP CS-Fixer) + if: matrix.code-style == 'yes' + run: php vendor/bin/php-cs-fixer fix --dry-run --diff + + - name: Code Analysis (PHPStan) + if: matrix.code-analysis == 'yes' + run: composer phpstan + + - name: Test with phpunit + run: vendor/bin/phpunit --configuration tests/phpunit.xml --coverage-clover clover.xml + + - name: Code Coverage + uses: codecov/codecov-action@v6 + if: matrix.coverage != 'none' diff --git a/.gitignore b/.gitignore index f08b31359..82b7dad3f 100644 --- a/.gitignore +++ b/.gitignore @@ -3,20 +3,7 @@ vendor/ composer.lock tests/cov/ tests/temp - -#vim -.*.swp - -#binaries -bin/phpunit -bin/phpcs -bin/php-cs-fixer -bin/sabre-cs-fixer -bin/hoa +tests/.phpunit.result.cache # Development stuff -testdata/ .php_cs.cache - -# OS X -.DS_Store diff --git a/.php_cs.dist b/.php_cs.dist index 8d61ee259..c5c78a971 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -6,7 +6,7 @@ $config->getFinder() ->in(__DIR__); $config->setRules([ '@PSR1' => true, - '@Symfony' =>true + '@Symfony' => true ]); return $config; \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 2619562ab..000000000 --- a/.travis.yml +++ /dev/null @@ -1,39 +0,0 @@ -language: php -sudo: required -php: - - 5.5 - - 5.6 - - 7.0 - - 7.1 - - 7.2 - - 7.3 - -env: - global: - - RUN_PHPSTAN="FALSE" - -matrix: - include: - - name: 'PHPStan' - php: 7.2 - env: RUN_PHPSTAN="TRUE" - fast_finish: true - allow_failures: - - php: 5.5 - -install: - - if [ $RUN_PHPSTAN == "TRUE" ]; then wget https://github.com/phpstan/phpstan/releases/download/0.10.3/phpstan.phar; fi - -before_script: - - composer install - -script: - - if [ $RUN_PHPSTAN == "FALSE" ]; then ./bin/phpunit --configuration tests/phpunit.xml --coverage-clover=coverage.xml; fi - - if [ $RUN_PHPSTAN == "TRUE" ]; then php phpstan.phar analyse -c phpstan.neon lib; fi - -after_success: - - bash <(curl -s https://codecov.io/bash) - -cache: - directories: - - $HOME/.composer/cache diff --git a/CHANGELOG.md b/CHANGELOG.md index dfe8955f5..65d9bc239 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,190 @@ ChangeLog ========= -4.2.0-alpha1 (2018-09-26) +4.6.0 (2026-05-31) +------------------ +* #718 feat(VCard): add getByTypes method (@JimKnoxx) +* #756 fix: Update deprecated timezone names (@ralflang) + +4.5.9 (2026-05-31) +------------------ +* #759 fix(itip): handle null old calendar/event (@ChristophWurst) + +4.5.8 (2026-01-12) +------------------ + +* #721: Fix variable scope (@KristofferFM) +* #723: Broker shouldn't add EXDATE property with floating timezone (@KristofferFM) +* #726: Improved check on property name (@KristofferFM) +* #727: Improve error checks in Mimedir parser (@KristofferFM) +* #728: Removing attendee from scheduled recurring event should generate an EXDATE property (@KristofferFM) +* #735: use RDATE in time range check and use all instances (@SebastianKrupinski) +* #743: send participation reply on fresh event (@SebastianKrupinski) + +4.5.7 (2025-04-17) +------------------ + +* #618: Add new exchangetimezone 'Amsterdam, Berlin, Bern, Rom, Stockholm, Wien' (@chr-is) +* #674: Allow unknown value data types for VALUE (@heiglandreas) +* #707: add phpdoc return types for arrayaccess methods (@smhg) + +4.5.6 (2024-10-14) +------------------ + +* #662: add PHP 8.4 to CI (@phil-davis) +* #669: fix: check if event status was changed to cancelled and generate appropriate message (@SebastianKrupinski) +* #673: Fix Implicitly marking parameter $param as nullable is deprecated (@cedric-anne) +* #675: refactor: Replace dirname(__FILE__) with __DIR__ (@ChristophWurst) +* #692: Throw InvalidDataException when RRule is invalid (@mathroc) + +4.5.5 (2024-07-02) +------------------ + +* #632: Add PHP 8.3 to CI (@phil-davis) +* #649: add lineIndex and lineString properties to a Property Node (@JohnRDOrazio) +* #652: ITip\Broker: handle timezones in replies to exception events (@gharlan) +* #654: chore: stop exporting php-cs-fixer config (@phil-davis) +* #656: Yearly rrule compliance by the iterator (@kroky) +* #658: throw ParseException when null input is provided (@phil-davis) +* #653: Handle summer time jumps in event recurrences (@phil-davis) + +4.5.4 (2023-11-09) +------------------ + +* #619: fixed issue: Undefined index: plusminus (@sash04ek) +* #622: Create Issue467Test.php for 619 (@sash04ek) +* #623: docs: fix type definition for oldCalendar (@kesselb) + +4.5.3 (2023-01-22) +------------------ + +* #607: Apply 'Support sabre/xml v4' and needed code changes to 4.5 branch (@phil-davis) + +4.5.2 (2023-01-20) +------------------ + +* #603: Support sabre/xml v4 (@gharlan) + +4.5.1 (2022-10-09) +------------------ + +* #597: Remove utf8_encode to easily support PHP 8.2 (@phil-davis) + +4.5.0 (2022-08-17) +------------------ + +* #579: Update .gitattributes (@cedric-anne) +* #561: PHP 8.1 deprecated support for null values in its APIs (@mstilkerich) +* #571: Fully ignore invalid lines (@heiglandreas) +* #564: Fix infinite loop caused by yearly with bySetPos (@liurxliu) +* #567: Endless loop problem in RRuleIterator::nextDaily (@KristofferFM) +* #466: Add support for MEMBER in a VCard (@sash04ek) +* #559: Handle Vobjects without closing tag (@sash04ek) +* #582: Fix bug in by year day (@KAYLukas) + +4.4.3 (2022-07-15) +------------------ + +* #577: Ignore multiple same parameter-values (@heiglandreas) + +4.4.2 (2022-06-24) +------------------ + +* #565: lowercase mailto:-addresses in getNormalizedValue() (@pk1234) +* #568: Add NICKNAME fallback for VCards without FNs (@Evengard) +* #573: Component/select: Before uppercasing $child->group, make sure it isn't null (@algernon) +* #575: Fix encoding detection on PHP 8.1 (@come-nc) + +4.4.1 (2021-12-07) +------------------ + + #557: Fix Iterator method signatures and avoid passing null as separator for implode (PHP 8.1 support) (@come-nc) + +4.4.0 (2021-11-15) ------------------ + #548: Allow easier extension of the timezone guessing (@heiglandreas) + +4.3.8 (2021-11-14) +------------------ + +* #538: fix EventIterator returns wrong end endTime (@floerke) +* #541: Reordering of the attendees is not a significant change (@floerke) +* #543: Reordering of vevent is not a significant change (@floerke) + +4.3.7 (2021-11-04) +------------------ + +* #551: version bump that was missed in 4.3.6 (@phil-davis) + +4.3.6 (2021-11-04) +------------------ + +* #544: Fix deprecated usages and return types on PHP 8.1 (@cedric-anne) + +4.3.5 (2021-02-12) +------------------ + +* #523: Fix setting properties with group assignment (@mstilkerich) +* #532: Make use of until parameter in nextMonthly function (@jaircuevajunior) + +4.3.4 (2021-02-04) +------------------ + +* #529: Reassign modified date in yearly rrule (@laoneo) +* #525: Add .gitattributes to reduce package size (@fezfez) + +4.3.3 (2020-11-09) +------------------ + +* #519: Remove US/Pacific-New obsolete timezone (@phil-davis) + +4.3.2 (2020-10-03) +------------------ + +* #513: Added Support for PHP 8.0 (@phil-davis) + +4.3.1 (2020-07-13) +------------------ + +* #510: Fix an incomplete phpdoc type annotation (@mstilkerich) +* #505: Refactor unit test code for phpunit9 (@phil-davis) +* #500: Standardize CI (@phil-davis) +* #496: CI tooling changes (@JeroenVanOort) + +4.3.0 (2020-01-31) +------------------ + +* Added support for PHP 7.4, dropped support for PHP 7.0 (@phil-davis) +* #487: Added phpstan coverage, updated testsuite for phpunit8 (@phil-davis, @JeroenVanOort) +* #495: refactored maps to use ::class notation (@JeroenVanOort) + +4.2.2 (2020-01-14) +------------------ + +* #465: Add TZ in iTip REPLY iTip messages +* #486: Add PHONE-NUMBER value type (used for TEL in vCard 3.0) + +4.2.1 (2019-12-18) +------------------ + +* #469, #451: fix compat with php 7.4 +* #443: prevent running in indefinite loop +* #449: Preventing creating a component for a root document +* #450: Fix parse with option Forgiving with trailing equal +* #459: fixed typo in VCalendar which resulting in usage of the wrong TimeZone +* #462: Broker::parseEventForOrganizer copies DTSTAMP from $eventInfo that causes broken scheduling + +4.2.0 (2019-02-19) +------------------ + +* #432: DTSTAMP must be specified in UTC +* #435: ORGANIZER e-mail address are case-insensitive +* #441: Repairing BASE64 encoded vCard version 3 + +4.2.0-alpha1 (2018-09-26) +------------------------- + * #412: Broker: add timezone to CANCEL messages * #424: Support php7.3 @@ -77,7 +258,7 @@ ChangeLog * #306: iTip REPLYs to the first instance of a recurring event was not handled correctly. * Slightly better error message during validation of `N` and `ADR` properties. -* #312: Correctly extracing timezone in the iTip broker, even when we don't +* #312: Correctly extracting timezone in the iTip broker, even when we don't have a master event. (@vkomrakov-sugar). * When validating a component's property that must appear once and which could automatically be repaired, make sure we report the change as 'repaired'. @@ -399,7 +580,7 @@ ChangeLog * #114: VTIMEZONE is retained when generating new REQUEST objects. * #114: Support for 'MAILTO:' style email addresses (in uppercase) in the iTip broker. This improves evolution support. -* #115: Using REQUEST-STATUS from REPLY messages and now propegating that into +* #115: Using REQUEST-STATUS from REPLY messages and now propagating that into SCHEDULE-STATUS. @@ -636,7 +817,7 @@ ChangeLog 3.0.0-alpha2 (2013-05-22) ------------------------- -* Fixed: vCard URL properties were referencing a non-existant class. +* Fixed: vCard URL properties were referencing a non-existent class. 3.0.0-alpha1 (2013-05-21) @@ -794,7 +975,7 @@ ChangeLog properties such as N, ADR, ORG and CATEGORIES. * Added: Splitter classes, that can split up large objects (such as exports) into individual objects (thanks @DominikTo and @armin-hackmann). -* Added: VFREEBUSY component, which allows easily checking wether timeslots are +* Added: VFREEBUSY component, which allows easily checking whether timeslots are available. * Added: The Reader class now has a 'FORGIVING' option, which allows it to parse properties with incorrect characters in the name (at this time, it just allows diff --git a/README.md b/README.md index 5030cf276..659e3fa83 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ sabre/vobject The VObject library allows you to easily parse and manipulate [iCalendar](https://tools.ietf.org/html/rfc5545) and [vCard](https://tools.ietf.org/html/rfc6350) objects using PHP. -The goal of the VObject library is to create a very complete library, with an easy to use API. +The goal of the VObject library is to create a very complete library, with an easy-to-use API. Installation diff --git a/bin/bench_freebusygenerator.php b/bin/bench_freebusygenerator.php index 1299c14fb..963623d18 100644 --- a/bin/bench_freebusygenerator.php +++ b/bin/bench_freebusygenerator.php @@ -11,7 +11,7 @@ echo "The process will be repeated 100 times to get accurate stats\n"; echo "\n"; echo 'Usage: '.$argv[0]." inputfile.ics\n"; - die(); + exit(); } list(, $inputFile) = $argv; diff --git a/bin/bench_manipulatevcard.php b/bin/bench_manipulatevcard.php index f229091db..df6d9f23d 100644 --- a/bin/bench_manipulatevcard.php +++ b/bin/bench_manipulatevcard.php @@ -10,7 +10,7 @@ echo 'system.'; echo "\n"; echo 'Usage: '.$argv[0]." inputfile.vcf\n"; - die(); + exit(); } list(, $inputFile) = $argv; diff --git a/bin/fetch_windows_zones.php b/bin/fetch_windows_zones.php index 9c4e51abd..2361dc309 100755 --- a/bin/fetch_windows_zones.php +++ b/bin/fetch_windows_zones.php @@ -1,13 +1,12 @@ #!/usr/bin/env php =5.5", + "php" : "^7.1 || ^8.0", "ext-mbstring" : "*", - "sabre/xml" : ">=1.5 <3.0" + "sabre/xml" : "^2.1 || ^3.0 || ^4.0" }, "require-dev" : { - "phpunit/phpunit" : "> 4.8.35, <6.0.0" + "friendsofphp/php-cs-fixer": "~2.17.1", + "phpunit/phpunit" : "^7.5 || ^8.5 || ^9.6", + "phpunit/php-invoker" : "^2.0 || ^3.1", + "phpstan/phpstan": "^0.12 || ^1.12 || ^2.0" }, "suggest" : { "hoa/bench" : "If you would like to run the benchmark scripts" @@ -71,6 +74,11 @@ "Sabre\\VObject\\" : "lib/" } }, + "autoload-dev" : { + "psr-4" : { + "Sabre\\VObject\\" : "tests/VObject" + } + }, "bin" : [ "bin/vobject", "bin/generate_vcards" @@ -80,7 +88,20 @@ "dev-master" : "4.0.x-dev" } }, - "config" : { - "bin-dir" : "bin" + "scripts": { + "phpstan": [ + "phpstan analyse lib tests" + ], + "cs-fixer": [ + "php-cs-fixer fix" + ], + "phpunit": [ + "phpunit --configuration tests/phpunit.xml" + ], + "test": [ + "composer phpstan", + "composer cs-fixer", + "composer phpunit" + ] } } diff --git a/lib/Cli.php b/lib/Cli.php index 70b5e8d6e..3bde16f9c 100644 --- a/lib/Cli.php +++ b/lib/Cli.php @@ -2,8 +2,7 @@ namespace Sabre\VObject; -use - InvalidArgumentException; +use InvalidArgumentException; /** * This is the CLI interface for sabre-vobject. @@ -29,7 +28,7 @@ class Cli protected $showHelp = false; /** - * Wether to spit out 'mimedir' or 'json' format. + * Whether to spit out 'mimedir' or 'json' format. * * @var string */ @@ -137,17 +136,14 @@ public function main(array $argv) // jcard/jcal documents case 'jcard': case 'jcal': - // specific document versions case 'vcard21': case 'vcard30': case 'vcard40': case 'icalendar20': - // specific formats case 'json': case 'mimedir': - // icalendar/vcad case 'icalendar': case 'vcard': @@ -183,7 +179,6 @@ public function main(array $argv) case 'vcard30': case 'vcard40': case 'icalendar20': - $this->inputFormat = 'mimedir'; break; @@ -211,7 +206,7 @@ public function main(array $argv) } if (!in_array($positional[0], ['validate', 'repair', 'convert', 'color'])) { - throw new InvalidArgumentException('Uknown command: '.$positional[0]); + throw new InvalidArgumentException('Unknown command: '.$positional[0]); } } catch (InvalidArgumentException $e) { $this->showHelp(); @@ -289,7 +284,7 @@ protected function showHelp() $this->log($this->colorize('green', ' validate').' source_file Validates a file for correctness.'); $this->log($this->colorize('green', ' repair').' source_file [output_file] Repairs a file.'); $this->log($this->colorize('green', ' convert').' source_file [output_file] Converts a file.'); - $this->log($this->colorize('green', ' color').' source_file Colorize a file, useful for debbugging.'); + $this->log($this->colorize('green', ' color').' source_file Colorize a file, useful for debugging.'); $this->log( <<stdout, $this->serializeComponent($vObj)); + $this->serializeComponent($vObj); } /** @@ -516,7 +505,7 @@ protected function serializeComponent(Component $vObj) * * A higher score means the item will be lower in the list. * To avoid score collisions, each "score category" has a reasonable - * space to accomodate elements. The $key is added to the $score to + * space to accommodate elements. The $key is added to the $score to * preserve the original relative order of elements. * * @param int $key @@ -582,8 +571,6 @@ function ($a, $b) use ($sortScore, $tmp) { /** * Colorizes a property. - * - * @param Property $property */ protected function serializeProperty(Property $property) { @@ -642,8 +629,6 @@ protected function serializeProperty(Property $property) /** * Parses the list of arguments. - * - * @param array $argv */ protected function parseArguments(array $argv) { diff --git a/lib/Component.php b/lib/Component.php index a33b7d577..ca82ad49b 100644 --- a/lib/Component.php +++ b/lib/Component.php @@ -28,7 +28,7 @@ class Component extends Node /** * A list of properties and/or sub-components. * - * @var array + * @var array */ protected $children = []; @@ -43,14 +43,12 @@ class Component extends Node * an iCalendar object, this may be something like CALSCALE:GREGORIAN. To * ensure that this does not happen, set $defaults to false. * - * @param Document $root - * @param string $name such as VCALENDAR, VEVENT - * @param array $children - * @param bool $defaults + * @param string|null $name such as VCALENDAR, VEVENT + * @param bool $defaults */ public function __construct(Document $root, $name, array $children = [], $defaults = true) { - $this->name = strtoupper($name); + $this->name = isset($name) ? strtoupper($name) : ''; $this->root = $root; if ($defaults) { @@ -162,9 +160,9 @@ public function remove($item) return; } } - } - throw new \InvalidArgumentException('The item you passed to remove() was not a child of this component'); + throw new \InvalidArgumentException('The item you passed to remove() was not a child of this component'); + } } /** @@ -240,7 +238,7 @@ public function select($name) return array_filter( $result, function ($child) use ($group) { - return $child instanceof Property && strtoupper($child->group) === $group; + return $child instanceof Property && (null !== $child->group ? strtoupper($child->group) : '') === $group; } ); } @@ -251,7 +249,7 @@ function ($child) use ($group) { $result = []; foreach ($this->children as $childGroup) { foreach ($childGroup as $child) { - if ($child instanceof Property && strtoupper($child->group) === $group) { + if ($child instanceof Property && (null !== $child->group ? strtoupper($child->group) : '') === $group) { $result[] = $child; } } @@ -276,7 +274,7 @@ public function serialize() * * A higher score means the item will be lower in the list. * To avoid score collisions, each "score category" has a reasonable - * space to accomodate elements. The $key is added to the $score to + * space to accommodate elements. The $key is added to the $score to * preserve the original relative order of elements. * * @param int $key @@ -341,6 +339,7 @@ function ($a, $b) use ($sortScore, $tmp) { * * @return array */ + #[\ReturnTypeWillChange] public function jsonSerialize() { $components = []; @@ -369,7 +368,7 @@ public function jsonSerialize() * * @param Xml\Writer $writer XML writer */ - public function xmlSerialize(Xml\Writer $writer) + public function xmlSerialize(Xml\Writer $writer): void { $components = []; $properties = []; @@ -433,7 +432,7 @@ protected function getDefaults() * * @param string $name * - * @return Property + * @return Property|null */ public function __get($name) { diff --git a/lib/Component/VAvailability.php b/lib/Component/VAvailability.php index 6f3e7f13c..04ec38dcb 100644 --- a/lib/Component/VAvailability.php +++ b/lib/Component/VAvailability.php @@ -26,9 +26,6 @@ class VAvailability extends VObject\Component * * https://tools.ietf.org/html/draft-daboo-calendar-availability-05#section-3.1 * - * @param DateTimeInterface $start - * @param DateTimeInterface $end - * * @return bool */ public function isInTimeRange(DateTimeInterface $start, DateTimeInterface $end) diff --git a/lib/Component/VCalendar.php b/lib/Component/VCalendar.php index b8eb1aa6f..017aed70c 100644 --- a/lib/Component/VCalendar.php +++ b/lib/Component/VCalendar.php @@ -37,15 +37,15 @@ class VCalendar extends VObject\Document * @var array */ public static $componentMap = [ - 'VCALENDAR' => 'Sabre\\VObject\\Component\\VCalendar', - 'VALARM' => 'Sabre\\VObject\\Component\\VAlarm', - 'VEVENT' => 'Sabre\\VObject\\Component\\VEvent', - 'VFREEBUSY' => 'Sabre\\VObject\\Component\\VFreeBusy', - 'VAVAILABILITY' => 'Sabre\\VObject\\Component\\VAvailability', - 'AVAILABLE' => 'Sabre\\VObject\\Component\\Available', - 'VJOURNAL' => 'Sabre\\VObject\\Component\\VJournal', - 'VTIMEZONE' => 'Sabre\\VObject\\Component\\VTimeZone', - 'VTODO' => 'Sabre\\VObject\\Component\\VTodo', + 'VCALENDAR' => self::class, + 'VALARM' => VAlarm::class, + 'VEVENT' => VEvent::class, + 'VFREEBUSY' => VFreeBusy::class, + 'VAVAILABILITY' => VAvailability::class, + 'AVAILABLE' => Available::class, + 'VJOURNAL' => VJournal::class, + 'VTIMEZONE' => VTimeZone::class, + 'VTODO' => VTodo::class, ]; /** @@ -54,21 +54,21 @@ class VCalendar extends VObject\Document * @var array */ public static $valueMap = [ - 'BINARY' => 'Sabre\\VObject\\Property\\Binary', - 'BOOLEAN' => 'Sabre\\VObject\\Property\\Boolean', - 'CAL-ADDRESS' => 'Sabre\\VObject\\Property\\ICalendar\\CalAddress', - 'DATE' => 'Sabre\\VObject\\Property\\ICalendar\\Date', - 'DATE-TIME' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'DURATION' => 'Sabre\\VObject\\Property\\ICalendar\\Duration', - 'FLOAT' => 'Sabre\\VObject\\Property\\FloatValue', - 'INTEGER' => 'Sabre\\VObject\\Property\\IntegerValue', - 'PERIOD' => 'Sabre\\VObject\\Property\\ICalendar\\Period', - 'RECUR' => 'Sabre\\VObject\\Property\\ICalendar\\Recur', - 'TEXT' => 'Sabre\\VObject\\Property\\Text', - 'TIME' => 'Sabre\\VObject\\Property\\Time', - 'UNKNOWN' => 'Sabre\\VObject\\Property\\Unknown', // jCard / jCal-only. - 'URI' => 'Sabre\\VObject\\Property\\Uri', - 'UTC-OFFSET' => 'Sabre\\VObject\\Property\\UtcOffset', + 'BINARY' => VObject\Property\Binary::class, + 'BOOLEAN' => VObject\Property\Boolean::class, + 'CAL-ADDRESS' => VObject\Property\ICalendar\CalAddress::class, + 'DATE' => VObject\Property\ICalendar\Date::class, + 'DATE-TIME' => VObject\Property\ICalendar\DateTime::class, + 'DURATION' => VObject\Property\ICalendar\Duration::class, + 'FLOAT' => VObject\Property\FloatValue::class, + 'INTEGER' => VObject\Property\IntegerValue::class, + 'PERIOD' => VObject\Property\ICalendar\Period::class, + 'RECUR' => VObject\Property\ICalendar\Recur::class, + 'TEXT' => VObject\Property\Text::class, + 'TIME' => VObject\Property\Time::class, + 'UNKNOWN' => VObject\Property\Unknown::class, // jCard / jCal-only. + 'URI' => VObject\Property\Uri::class, + 'UTC-OFFSET' => VObject\Property\UtcOffset::class, ]; /** @@ -78,78 +78,78 @@ class VCalendar extends VObject\Document */ public static $propertyMap = [ // Calendar properties - 'CALSCALE' => 'Sabre\\VObject\\Property\\FlatText', - 'METHOD' => 'Sabre\\VObject\\Property\\FlatText', - 'PRODID' => 'Sabre\\VObject\\Property\\FlatText', - 'VERSION' => 'Sabre\\VObject\\Property\\FlatText', + 'CALSCALE' => VObject\Property\FlatText::class, + 'METHOD' => VObject\Property\FlatText::class, + 'PRODID' => VObject\Property\FlatText::class, + 'VERSION' => VObject\Property\FlatText::class, // Component properties - 'ATTACH' => 'Sabre\\VObject\\Property\\Uri', - 'CATEGORIES' => 'Sabre\\VObject\\Property\\Text', - 'CLASS' => 'Sabre\\VObject\\Property\\FlatText', - 'COMMENT' => 'Sabre\\VObject\\Property\\FlatText', - 'DESCRIPTION' => 'Sabre\\VObject\\Property\\FlatText', - 'GEO' => 'Sabre\\VObject\\Property\\FloatValue', - 'LOCATION' => 'Sabre\\VObject\\Property\\FlatText', - 'PERCENT-COMPLETE' => 'Sabre\\VObject\\Property\\IntegerValue', - 'PRIORITY' => 'Sabre\\VObject\\Property\\IntegerValue', - 'RESOURCES' => 'Sabre\\VObject\\Property\\Text', - 'STATUS' => 'Sabre\\VObject\\Property\\FlatText', - 'SUMMARY' => 'Sabre\\VObject\\Property\\FlatText', + 'ATTACH' => VObject\Property\Uri::class, + 'CATEGORIES' => VObject\Property\Text::class, + 'CLASS' => VObject\Property\FlatText::class, + 'COMMENT' => VObject\Property\FlatText::class, + 'DESCRIPTION' => VObject\Property\FlatText::class, + 'GEO' => VObject\Property\FloatValue::class, + 'LOCATION' => VObject\Property\FlatText::class, + 'PERCENT-COMPLETE' => VObject\Property\IntegerValue::class, + 'PRIORITY' => VObject\Property\IntegerValue::class, + 'RESOURCES' => VObject\Property\Text::class, + 'STATUS' => VObject\Property\FlatText::class, + 'SUMMARY' => VObject\Property\FlatText::class, // Date and Time Component Properties - 'COMPLETED' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'DTEND' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'DUE' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'DTSTART' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'DURATION' => 'Sabre\\VObject\\Property\\ICalendar\\Duration', - 'FREEBUSY' => 'Sabre\\VObject\\Property\\ICalendar\\Period', - 'TRANSP' => 'Sabre\\VObject\\Property\\FlatText', + 'COMPLETED' => VObject\Property\ICalendar\DateTime::class, + 'DTEND' => VObject\Property\ICalendar\DateTime::class, + 'DUE' => VObject\Property\ICalendar\DateTime::class, + 'DTSTART' => VObject\Property\ICalendar\DateTime::class, + 'DURATION' => VObject\Property\ICalendar\Duration::class, + 'FREEBUSY' => VObject\Property\ICalendar\Period::class, + 'TRANSP' => VObject\Property\FlatText::class, // Time Zone Component Properties - 'TZID' => 'Sabre\\VObject\\Property\\FlatText', - 'TZNAME' => 'Sabre\\VObject\\Property\\FlatText', - 'TZOFFSETFROM' => 'Sabre\\VObject\\Property\\UtcOffset', - 'TZOFFSETTO' => 'Sabre\\VObject\\Property\\UtcOffset', - 'TZURL' => 'Sabre\\VObject\\Property\\Uri', + 'TZID' => VObject\Property\FlatText::class, + 'TZNAME' => VObject\Property\FlatText::class, + 'TZOFFSETFROM' => VObject\Property\UtcOffset::class, + 'TZOFFSETTO' => VObject\Property\UtcOffset::class, + 'TZURL' => VObject\Property\Uri::class, // Relationship Component Properties - 'ATTENDEE' => 'Sabre\\VObject\\Property\\ICalendar\\CalAddress', - 'CONTACT' => 'Sabre\\VObject\\Property\\FlatText', - 'ORGANIZER' => 'Sabre\\VObject\\Property\\ICalendar\\CalAddress', - 'RECURRENCE-ID' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'RELATED-TO' => 'Sabre\\VObject\\Property\\FlatText', - 'URL' => 'Sabre\\VObject\\Property\\Uri', - 'UID' => 'Sabre\\VObject\\Property\\FlatText', + 'ATTENDEE' => VObject\Property\ICalendar\CalAddress::class, + 'CONTACT' => VObject\Property\FlatText::class, + 'ORGANIZER' => VObject\Property\ICalendar\CalAddress::class, + 'RECURRENCE-ID' => VObject\Property\ICalendar\DateTime::class, + 'RELATED-TO' => VObject\Property\FlatText::class, + 'URL' => VObject\Property\Uri::class, + 'UID' => VObject\Property\FlatText::class, // Recurrence Component Properties - 'EXDATE' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'RDATE' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'RRULE' => 'Sabre\\VObject\\Property\\ICalendar\\Recur', - 'EXRULE' => 'Sabre\\VObject\\Property\\ICalendar\\Recur', // Deprecated since rfc5545 + 'EXDATE' => VObject\Property\ICalendar\DateTime::class, + 'RDATE' => VObject\Property\ICalendar\DateTime::class, + 'RRULE' => VObject\Property\ICalendar\Recur::class, + 'EXRULE' => VObject\Property\ICalendar\Recur::class, // Deprecated since rfc5545 // Alarm Component Properties - 'ACTION' => 'Sabre\\VObject\\Property\\FlatText', - 'REPEAT' => 'Sabre\\VObject\\Property\\IntegerValue', - 'TRIGGER' => 'Sabre\\VObject\\Property\\ICalendar\\Duration', + 'ACTION' => VObject\Property\FlatText::class, + 'REPEAT' => VObject\Property\IntegerValue::class, + 'TRIGGER' => VObject\Property\ICalendar\Duration::class, // Change Management Component Properties - 'CREATED' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'DTSTAMP' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'LAST-MODIFIED' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'SEQUENCE' => 'Sabre\\VObject\\Property\\IntegerValue', + 'CREATED' => VObject\Property\ICalendar\DateTime::class, + 'DTSTAMP' => VObject\Property\ICalendar\DateTime::class, + 'LAST-MODIFIED' => VObject\Property\ICalendar\DateTime::class, + 'SEQUENCE' => VObject\Property\IntegerValue::class, // Request Status - 'REQUEST-STATUS' => 'Sabre\\VObject\\Property\\Text', + 'REQUEST-STATUS' => VObject\Property\Text::class, // Additions from draft-daboo-valarm-extensions-04 - 'ALARM-AGENT' => 'Sabre\\VObject\\Property\\Text', - 'ACKNOWLEDGED' => 'Sabre\\VObject\\Property\\ICalendar\\DateTime', - 'PROXIMITY' => 'Sabre\\VObject\\Property\\Text', - 'DEFAULT-ALARM' => 'Sabre\\VObject\\Property\\Boolean', + 'ALARM-AGENT' => VObject\Property\Text::class, + 'ACKNOWLEDGED' => VObject\Property\ICalendar\DateTime::class, + 'PROXIMITY' => VObject\Property\Text::class, + 'DEFAULT-ALARM' => VObject\Property\Boolean::class, // Additions from draft-daboo-calendar-availability-05 - 'BUSYTYPE' => 'Sabre\\VObject\\Property\\Text', + 'BUSYTYPE' => VObject\Property\Text::class, ]; /** @@ -269,21 +269,19 @@ public function getBaseComponent($componentName = null) * If this calendar object, has events with recurrence rules, this method * can be used to expand the event into multiple sub-events. * - * Each event will be stripped from it's recurrence information, and only + * Each event will be stripped from its recurrence information, and only * the instances of the event in the specified timerange will be left * alone. * * In addition, this method will cause timezone information to be stripped, * and normalized to UTC. * - * @param DateTimeInterface $start - * @param DateTimeInterface $end - * @param DateTimeZone $timeZone reference timezone for floating dates and - * times + * @param DateTimeZone $timeZone reference timezone for floating dates and + * times * * @return VCalendar */ - public function expand(DateTimeInterface $start, DateTimeInterface $end, DateTimeZone $timeZone = null) + public function expand(DateTimeInterface $start, DateTimeInterface $end, ?DateTimeZone $timeZone = null) { $newChildren = []; $recurringEvents = []; @@ -311,7 +309,7 @@ public function expand(DateTimeInterface $start, DateTimeInterface $end, DateTim foreach ($this->children() as $child) { if ($child instanceof Property && 'PRODID' !== $child->name) { - // We explictly want to ignore PRODID, because we want to + // We explicitly want to ignore PRODID, because we want to // overwrite it with our own. $newChildren[] = clone $child; } elseif ($child instanceof Component && 'VTIMEZONE' !== $child->name) { @@ -336,7 +334,7 @@ public function expand(DateTimeInterface $start, DateTimeInterface $end, DateTim foreach ($recurringEvents as $events) { try { - $it = new EventIterator($events, $timeZone); + $it = new EventIterator($events, null, $timeZone); } catch (NoInstancesException $e) { // This event is recurring, but it doesn't have a single // instance. We are skipping this event from the output diff --git a/lib/Component/VCard.php b/lib/Component/VCard.php index 860e45ffa..e2b440812 100644 --- a/lib/Component/VCard.php +++ b/lib/Component/VCard.php @@ -39,7 +39,7 @@ class VCard extends VObject\Document * @var array */ public static $componentMap = [ - 'VCARD' => 'Sabre\\VObject\\Component\\VCard', + 'VCARD' => VCard::class, ]; /** @@ -48,22 +48,23 @@ class VCard extends VObject\Document * @var array */ public static $valueMap = [ - 'BINARY' => 'Sabre\\VObject\\Property\\Binary', - 'BOOLEAN' => 'Sabre\\VObject\\Property\\Boolean', - 'CONTENT-ID' => 'Sabre\\VObject\\Property\\FlatText', // vCard 2.1 only - 'DATE' => 'Sabre\\VObject\\Property\\VCard\\Date', - 'DATE-TIME' => 'Sabre\\VObject\\Property\\VCard\\DateTime', - 'DATE-AND-OR-TIME' => 'Sabre\\VObject\\Property\\VCard\\DateAndOrTime', // vCard only - 'FLOAT' => 'Sabre\\VObject\\Property\\FloatValue', - 'INTEGER' => 'Sabre\\VObject\\Property\\IntegerValue', - 'LANGUAGE-TAG' => 'Sabre\\VObject\\Property\\VCard\\LanguageTag', - 'TIMESTAMP' => 'Sabre\\VObject\\Property\\VCard\\TimeStamp', - 'TEXT' => 'Sabre\\VObject\\Property\\Text', - 'TIME' => 'Sabre\\VObject\\Property\\Time', - 'UNKNOWN' => 'Sabre\\VObject\\Property\\Unknown', // jCard / jCal-only. - 'URI' => 'Sabre\\VObject\\Property\\Uri', - 'URL' => 'Sabre\\VObject\\Property\\Uri', // vCard 2.1 only - 'UTC-OFFSET' => 'Sabre\\VObject\\Property\\UtcOffset', + 'BINARY' => VObject\Property\Binary::class, + 'BOOLEAN' => VObject\Property\Boolean::class, + 'CONTENT-ID' => VObject\Property\FlatText::class, // vCard 2.1 only + 'DATE' => VObject\Property\VCard\Date::class, + 'DATE-TIME' => VObject\Property\VCard\DateTime::class, + 'DATE-AND-OR-TIME' => VObject\Property\VCard\DateAndOrTime::class, // vCard only + 'FLOAT' => VObject\Property\FloatValue::class, + 'INTEGER' => VObject\Property\IntegerValue::class, + 'LANGUAGE-TAG' => VObject\Property\VCard\LanguageTag::class, + 'PHONE-NUMBER' => VObject\Property\VCard\PhoneNumber::class, // vCard 3.0 only + 'TIMESTAMP' => VObject\Property\VCard\TimeStamp::class, + 'TEXT' => VObject\Property\Text::class, + 'TIME' => VObject\Property\Time::class, + 'UNKNOWN' => VObject\Property\Unknown::class, // jCard / jCal-only. + 'URI' => VObject\Property\Uri::class, + 'URL' => VObject\Property\Uri::class, // vCard 2.1 only + 'UTC-OFFSET' => VObject\Property\UtcOffset::class, ]; /** @@ -73,68 +74,68 @@ class VCard extends VObject\Document */ public static $propertyMap = [ // vCard 2.1 properties and up - 'N' => 'Sabre\\VObject\\Property\\Text', - 'FN' => 'Sabre\\VObject\\Property\\FlatText', - 'PHOTO' => 'Sabre\\VObject\\Property\\Binary', - 'BDAY' => 'Sabre\\VObject\\Property\\VCard\\DateAndOrTime', - 'ADR' => 'Sabre\\VObject\\Property\\Text', - 'LABEL' => 'Sabre\\VObject\\Property\\FlatText', // Removed in vCard 4.0 - 'TEL' => 'Sabre\\VObject\\Property\\FlatText', - 'EMAIL' => 'Sabre\\VObject\\Property\\FlatText', - 'MAILER' => 'Sabre\\VObject\\Property\\FlatText', // Removed in vCard 4.0 - 'GEO' => 'Sabre\\VObject\\Property\\FlatText', - 'TITLE' => 'Sabre\\VObject\\Property\\FlatText', - 'ROLE' => 'Sabre\\VObject\\Property\\FlatText', - 'LOGO' => 'Sabre\\VObject\\Property\\Binary', + 'N' => VObject\Property\Text::class, + 'FN' => VObject\Property\FlatText::class, + 'PHOTO' => VObject\Property\Binary::class, + 'BDAY' => VObject\Property\VCard\DateAndOrTime::class, + 'ADR' => VObject\Property\Text::class, + 'LABEL' => VObject\Property\FlatText::class, // Removed in vCard 4.0 + 'TEL' => VObject\Property\FlatText::class, + 'EMAIL' => VObject\Property\FlatText::class, + 'MAILER' => VObject\Property\FlatText::class, // Removed in vCard 4.0 + 'GEO' => VObject\Property\FlatText::class, + 'TITLE' => VObject\Property\FlatText::class, + 'ROLE' => VObject\Property\FlatText::class, + 'LOGO' => VObject\Property\Binary::class, // 'AGENT' => 'Sabre\\VObject\\Property\\', // Todo: is an embedded vCard. Probably rare, so // not supported at the moment - 'ORG' => 'Sabre\\VObject\\Property\\Text', - 'NOTE' => 'Sabre\\VObject\\Property\\FlatText', - 'REV' => 'Sabre\\VObject\\Property\\VCard\\TimeStamp', - 'SOUND' => 'Sabre\\VObject\\Property\\FlatText', - 'URL' => 'Sabre\\VObject\\Property\\Uri', - 'UID' => 'Sabre\\VObject\\Property\\FlatText', - 'VERSION' => 'Sabre\\VObject\\Property\\FlatText', - 'KEY' => 'Sabre\\VObject\\Property\\FlatText', - 'TZ' => 'Sabre\\VObject\\Property\\Text', + 'ORG' => VObject\Property\Text::class, + 'NOTE' => VObject\Property\FlatText::class, + 'REV' => VObject\Property\VCard\TimeStamp::class, + 'SOUND' => VObject\Property\FlatText::class, + 'URL' => VObject\Property\Uri::class, + 'UID' => VObject\Property\FlatText::class, + 'VERSION' => VObject\Property\FlatText::class, + 'KEY' => VObject\Property\FlatText::class, + 'TZ' => VObject\Property\Text::class, // vCard 3.0 properties - 'CATEGORIES' => 'Sabre\\VObject\\Property\\Text', - 'SORT-STRING' => 'Sabre\\VObject\\Property\\FlatText', - 'PRODID' => 'Sabre\\VObject\\Property\\FlatText', - 'NICKNAME' => 'Sabre\\VObject\\Property\\Text', - 'CLASS' => 'Sabre\\VObject\\Property\\FlatText', // Removed in vCard 4.0 + 'CATEGORIES' => VObject\Property\Text::class, + 'SORT-STRING' => VObject\Property\FlatText::class, + 'PRODID' => VObject\Property\FlatText::class, + 'NICKNAME' => VObject\Property\Text::class, + 'CLASS' => VObject\Property\FlatText::class, // Removed in vCard 4.0 // rfc2739 properties - 'FBURL' => 'Sabre\\VObject\\Property\\Uri', - 'CAPURI' => 'Sabre\\VObject\\Property\\Uri', - 'CALURI' => 'Sabre\\VObject\\Property\\Uri', - 'CALADRURI' => 'Sabre\\VObject\\Property\\Uri', + 'FBURL' => VObject\Property\Uri::class, + 'CAPURI' => VObject\Property\Uri::class, + 'CALURI' => VObject\Property\Uri::class, + 'CALADRURI' => VObject\Property\Uri::class, // rfc4770 properties - 'IMPP' => 'Sabre\\VObject\\Property\\Uri', + 'IMPP' => VObject\Property\Uri::class, // vCard 4.0 properties - 'SOURCE' => 'Sabre\\VObject\\Property\\Uri', - 'XML' => 'Sabre\\VObject\\Property\\FlatText', - 'ANNIVERSARY' => 'Sabre\\VObject\\Property\\VCard\\DateAndOrTime', - 'CLIENTPIDMAP' => 'Sabre\\VObject\\Property\\Text', - 'LANG' => 'Sabre\\VObject\\Property\\VCard\\LanguageTag', - 'GENDER' => 'Sabre\\VObject\\Property\\Text', - 'KIND' => 'Sabre\\VObject\\Property\\FlatText', - 'MEMBER' => 'Sabre\\VObject\\Property\\Uri', - 'RELATED' => 'Sabre\\VObject\\Property\\Uri', + 'SOURCE' => VObject\Property\Uri::class, + 'XML' => VObject\Property\FlatText::class, + 'ANNIVERSARY' => VObject\Property\VCard\DateAndOrTime::class, + 'CLIENTPIDMAP' => VObject\Property\Text::class, + 'LANG' => VObject\Property\VCard\LanguageTag::class, + 'GENDER' => VObject\Property\Text::class, + 'KIND' => VObject\Property\FlatText::class, + 'MEMBER' => VObject\Property\Uri::class, + 'RELATED' => VObject\Property\Uri::class, // rfc6474 properties - 'BIRTHPLACE' => 'Sabre\\VObject\\Property\\FlatText', - 'DEATHPLACE' => 'Sabre\\VObject\\Property\\FlatText', - 'DEATHDATE' => 'Sabre\\VObject\\Property\\VCard\\DateAndOrTime', + 'BIRTHPLACE' => VObject\Property\FlatText::class, + 'DEATHPLACE' => VObject\Property\FlatText::class, + 'DEATHDATE' => VObject\Property\VCard\DateAndOrTime::class, // rfc6715 properties - 'EXPERTISE' => 'Sabre\\VObject\\Property\\FlatText', - 'HOBBY' => 'Sabre\\VObject\\Property\\FlatText', - 'INTEREST' => 'Sabre\\VObject\\Property\\FlatText', - 'ORG-DIRECTORY' => 'Sabre\\VObject\\Property\\FlatText', + 'EXPERTISE' => VObject\Property\FlatText::class, + 'HOBBY' => VObject\Property\FlatText::class, + 'INTEREST' => VObject\Property\FlatText::class, + 'ORG-DIRECTORY' => VObject\Property\FlatText::class, ]; /** @@ -290,6 +291,11 @@ public function validate($options = 0) $this->FN = (string) $this->ORG; $repaired = true; + // Otherwise, the NICKNAME property may work + } elseif (isset($this->NICKNAME)) { + $this->FN = (string) $this->NICKNAME; + $repaired = true; + // Otherwise, the EMAIL property may work } elseif (isset($this->EMAIL)) { $this->FN = (string) $this->EMAIL; @@ -372,7 +378,7 @@ public function getValidationRules() /** * Returns a preferred field. * - * VCards can indicate wether a field such as ADR, TEL or EMAIL is + * VCards can indicate whether a field such as ADR, TEL or EMAIL is * preferred by specifying TYPE=PREF (vcard 2.1, 3) or PREF=x (vcard 4, x * being a number between 1 and 100). * @@ -424,6 +430,34 @@ public function getByType($propertyName, $type) } } + /** + * Returns a property with a specific TYPE value (ADR, TEL, or EMAIL). + * + * This function will return null if the exact property list does not exist. + * + * For example to get the property of `TEL;TYPE=HOME,CELL` + * you would call `getByTypes('TEL', ['HOME', 'CELL'])` + * + * @param string[] $types + * + * @return \ArrayAccess|array|null + */ + public function getByTypes(string $propertyName, array $types) + { + $types = array_map('strtolower', $types); + foreach ($this->select($propertyName) as $field) { + if (isset($field['TYPE'])) { + $parts = array_map('strtolower', $field['TYPE']->getParts()); + + if (!array_diff($types, $parts) && !array_diff($parts, $types)) { + return $field; + } + } + } + + return null; + } + /** * This method should return a list of default property values. * @@ -444,6 +478,7 @@ protected function getDefaults() * * @return array */ + #[\ReturnTypeWillChange] public function jsonSerialize() { // A vcard does not have sub-components, so we're overriding this @@ -466,7 +501,7 @@ public function jsonSerialize() * * @param Xml\Writer $writer XML writer */ - public function xmlSerialize(Xml\Writer $writer) + public function xmlSerialize(Xml\Writer $writer): void { $propertiesByGroup = []; @@ -525,8 +560,8 @@ public function getClassNameForPropertyName($propertyName) $className = parent::getClassNameForPropertyName($propertyName); // In vCard 4, BINARY no longer exists, and we need URI instead. - if ('Sabre\\VObject\\Property\\Binary' == $className && self::VCARD40 === $this->getDocumentType()) { - return 'Sabre\\VObject\\Property\\Uri'; + if (VObject\Property\Binary::class == $className && self::VCARD40 === $this->getDocumentType()) { + return VObject\Property\Uri::class; } return $className; diff --git a/lib/Component/VEvent.php b/lib/Component/VEvent.php index 09f37033c..a385a09e1 100644 --- a/lib/Component/VEvent.php +++ b/lib/Component/VEvent.php @@ -25,18 +25,15 @@ class VEvent extends VObject\Component * The rules used to determine if an event falls within the specified * time-range is based on the CalDAV specification. * - * @param DateTimeInterface $start - * @param DateTimeInterface $end - * * @return bool */ public function isInTimeRange(DateTimeInterface $start, DateTimeInterface $end) { - if ($this->RRULE) { + if ($this->RRULE || $this->RDATE) { try { $it = new EventIterator($this, null, $start->getTimezone()); } catch (NoInstancesException $e) { - // If we've catched this exception, there are no instances + // If we've caught this exception, there are no instances // for the event that fall into the specified time-range. return false; } diff --git a/lib/Component/VFreeBusy.php b/lib/Component/VFreeBusy.php index 558a85233..fef418b53 100644 --- a/lib/Component/VFreeBusy.php +++ b/lib/Component/VFreeBusy.php @@ -21,9 +21,6 @@ class VFreeBusy extends VObject\Component * Checks based on the contained FREEBUSY information, if a timeslot is * available. * - * @param DateTimeInterface $start - * @param DateTimeInterface $end - * * @return bool */ public function isFree(DateTimeInterface $start, DatetimeInterface $end) diff --git a/lib/Component/VJournal.php b/lib/Component/VJournal.php index 9bd336776..9b7f1b873 100644 --- a/lib/Component/VJournal.php +++ b/lib/Component/VJournal.php @@ -23,9 +23,6 @@ class VJournal extends VObject\Component * The rules used to determine if an event falls within the specified * time-range is based on the CalDAV specification. * - * @param DateTimeInterface $start - * @param DateTimeInterface $end - * * @return bool */ public function isInTimeRange(DateTimeInterface $start, DateTimeInterface $end) diff --git a/lib/Component/VTodo.php b/lib/Component/VTodo.php index 9de77e841..6f022ba6d 100644 --- a/lib/Component/VTodo.php +++ b/lib/Component/VTodo.php @@ -23,9 +23,6 @@ class VTodo extends VObject\Component * The rules used to determine if an event falls within the specified * time-range is based on the CalDAV specification. * - * @param DateTimeInterface $start - * @param DateTimeInterface $end - * * @return bool */ public function isInTimeRange(DateTimeInterface $start, DateTimeInterface $end) diff --git a/lib/DateTimeParser.php b/lib/DateTimeParser.php index 1c253437a..69072ef8c 100644 --- a/lib/DateTimeParser.php +++ b/lib/DateTimeParser.php @@ -31,7 +31,7 @@ class DateTimeParser * * @return DateTimeImmutable */ - public static function parseDateTime($dt, DateTimeZone $tz = null) + public static function parseDateTime($dt, ?DateTimeZone $tz = null) { // Format is YYYYMMDD + "T" + hhmmss $result = preg_match('/^([0-9]{4})([0-1][0-9])([0-3][0-9])T([0-2][0-9])([0-5][0-9])([0-5][0-9])([Z]?)$/', $dt, $matches); @@ -61,7 +61,7 @@ public static function parseDateTime($dt, DateTimeZone $tz = null) * * @return DateTimeImmutable */ - public static function parseDate($date, DateTimeZone $tz = null) + public static function parseDate($date, ?DateTimeZone $tz = null) { // Format is YYYYMMDD $result = preg_match('/^([0-9]{4})([0-1][0-9])([0-3][0-9])$/', $date, $matches); @@ -104,7 +104,7 @@ public static function parseDuration($duration, $asString = false) if (!$asString) { $invert = false; - if ('-' === $matches['plusminus']) { + if (isset($matches['plusminus']) && '-' === $matches['plusminus']) { $invert = true; } diff --git a/lib/Document.php b/lib/Document.php index 0cb2e0978..36f20ddd0 100644 --- a/lib/Document.php +++ b/lib/Document.php @@ -157,10 +157,10 @@ public function create($name) * * @return Component */ - public function createComponent($name, array $children = null, $defaults = true) + public function createComponent($name, ?array $children = null, $defaults = true) { $name = strtoupper($name); - $class = 'Sabre\\VObject\\Component'; + $class = Component::class; if (isset(static::$componentMap[$name])) { $class = static::$componentMap[$name]; @@ -186,10 +186,8 @@ public function createComponent($name, array $children = null, $defaults = true) * @param mixed $value * @param array $parameters * @param string $valueType Force a specific valuetype, such as URI or TEXT - * - * @return Property */ - public function createProperty($name, $value = null, array $parameters = null, $valueType = null) + public function createProperty($name, $value = null, ?array $parameters = null, $valueType = null, ?int $lineIndex = null, ?string $lineString = null): Property { // If there's a . in the name, it means it's prefixed by a groupname. if (false !== ($i = strpos($name, '.'))) { @@ -202,28 +200,35 @@ public function createProperty($name, $value = null, array $parameters = null, $ $class = null; + // If a VALUE parameter is supplied, we have to use that + // According to https://datatracker.ietf.org/doc/html/rfc5545#section-3.2.20 + // If the property's value is the default value type, then this + // parameter need not be specified. However, if the property's + // default value type is overridden by some other allowable value + // type, then this parameter MUST be specified. + if (!$valueType) { + $valueType = $parameters['VALUE'] ?? null; + } + if ($valueType) { // The valueType argument comes first to figure out the correct // class. $class = $this->getClassNameForPropertyValue($valueType); } + // If the value parameter is not set or set to something we do not recognize + // we do not attempt to interpret or parse the datass value as specified in + // https://datatracker.ietf.org/doc/html/rfc5545#section-3.2.20 + // So when we so far did not get a class-name, we use the default for the property if (is_null($class)) { - // If a VALUE parameter is supplied, we should use that. - if (isset($parameters['VALUE'])) { - $class = $this->getClassNameForPropertyValue($parameters['VALUE']); - if (is_null($class)) { - throw new InvalidDataException('Unsupported VALUE parameter for '.$name.' property. You supplied "'.$parameters['VALUE'].'"'); - } - } else { - $class = $this->getClassNameForPropertyName($name); - } + $class = $this->getClassNameForPropertyName($name); } + if (is_null($parameters)) { $parameters = []; } - return new $class($this, $name, $value, $parameters, $group); + return new $class($this, $name, $value, $parameters, $group, $lineIndex, $lineString); } /** @@ -258,7 +263,7 @@ public function getClassNameForPropertyName($propertyName) if (isset(static::$propertyMap[$propertyName])) { return static::$propertyMap[$propertyName]; } else { - return 'Sabre\\VObject\\Property\\Unknown'; + return Property\Unknown::class; } } } diff --git a/lib/ElementList.php b/lib/ElementList.php index 56058cbd5..e419d480c 100644 --- a/lib/ElementList.php +++ b/lib/ElementList.php @@ -24,7 +24,10 @@ class ElementList extends ArrayIterator * * @param int $offset * @param mixed $value + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { throw new LogicException('You can not add new objects to an ElementList'); @@ -36,7 +39,10 @@ public function offsetSet($offset, $value) * This method just forwards the request to the inner iterator * * @param int $offset + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetUnset($offset) { throw new LogicException('You can not remove objects from an ElementList'); diff --git a/lib/FreeBusyData.php b/lib/FreeBusyData.php index d05dfc799..4d9f441ce 100644 --- a/lib/FreeBusyData.php +++ b/lib/FreeBusyData.php @@ -84,7 +84,7 @@ public function add($start, $end, $type) 'type' => $type, ]; - $preceedingItem = $this->data[$insertStartIndex - 1]; + $precedingItem = $this->data[$insertStartIndex - 1]; if ($this->data[$insertStartIndex - 1]['start'] === $start) { // The old item starts at the exact same point as the new item. --$insertStartIndex; @@ -122,11 +122,11 @@ public function add($start, $end, $type) // between. if (-1 === $itemsToDelete) { $itemsToDelete = 0; - if ($newItem['end'] < $preceedingItem['end']) { + if ($newItem['end'] < $precedingItem['end']) { $newItems[] = [ 'start' => $newItem['end'] + 1, - 'end' => $preceedingItem['end'], - 'type' => $preceedingItem['type'], + 'end' => $precedingItem['end'], + 'type' => $precedingItem['type'], ]; } } diff --git a/lib/FreeBusyGenerator.php b/lib/FreeBusyGenerator.php index fc5766d8e..56ae166fa 100644 --- a/lib/FreeBusyGenerator.php +++ b/lib/FreeBusyGenerator.php @@ -71,7 +71,7 @@ class FreeBusyGenerator /** * A VAVAILABILITY document. * - * If this is set, it's information will be included when calculating + * If this is set, its information will be included when calculating * freebusy time. * * @var Document @@ -89,7 +89,7 @@ class FreeBusyGenerator * @param mixed $objects * @param DateTimeZone $timeZone */ - public function __construct(DateTimeInterface $start = null, DateTimeInterface $end = null, $objects = null, DateTimeZone $timeZone = null) + public function __construct(?DateTimeInterface $start = null, ?DateTimeInterface $end = null, $objects = null, ?DateTimeZone $timeZone = null) { $this->setTimeRange($start, $end); @@ -109,8 +109,6 @@ public function __construct(DateTimeInterface $start = null, DateTimeInterface $ * for setting things like the METHOD, CALSCALE, VERSION, etc.. * * The VFREEBUSY object will be automatically added though. - * - * @param Document $vcalendar */ public function setBaseObject(Document $vcalendar) { @@ -119,8 +117,6 @@ public function setBaseObject(Document $vcalendar) /** * Sets a VAVAILABILITY document. - * - * @param Document $vcalendar */ public function setVAvailability(Document $vcalendar) { @@ -130,7 +126,7 @@ public function setVAvailability(Document $vcalendar) /** * Sets the input objects. * - * You must either specify a valendar object as a string, or as the parse + * You must either specify a vcalendar object as a string, or as the parse * Component. * It's also possible to specify multiple objects as an array. * @@ -162,7 +158,7 @@ public function setObjects($objects) * @param DateTimeInterface $start * @param DateTimeInterface $end */ - public function setTimeRange(DateTimeInterface $start = null, DateTimeInterface $end = null) + public function setTimeRange(?DateTimeInterface $start = null, ?DateTimeInterface $end = null) { if (!$start) { $start = new DateTimeImmutable(Settings::$minDate); @@ -176,8 +172,6 @@ public function setTimeRange(DateTimeInterface $start = null, DateTimeInterface /** * Sets the reference timezone for floating times. - * - * @param DateTimeZone $timeZone */ public function setTimeZone(DateTimeZone $timeZone) { @@ -208,9 +202,6 @@ public function getResult() /** * This method takes a VAVAILABILITY component and figures out all the * available times. - * - * @param FreeBusyData $fbData - * @param VCalendar $vavailability */ protected function calculateAvailability(FreeBusyData $fbData, VCalendar $vavailability) { @@ -363,8 +354,7 @@ function ($a, $b) { * This method takes an array of iCalendar objects and applies its busy * times on fbData. * - * @param FreeBusyData $fbData - * @param VCalendar[] $objects + * @param VCalendar[] $objects */ protected function calculateBusy(FreeBusyData $fbData, array $objects) { @@ -372,7 +362,6 @@ protected function calculateBusy(FreeBusyData $fbData, array $objects) foreach ($object->getBaseComponents() as $component) { switch ($component->name) { case 'VEVENT': - $FBTYPE = 'BUSY'; if (isset($component->TRANSP) && ('TRANSPARENT' === strtoupper($component->TRANSP))) { break; diff --git a/lib/ITip/Broker.php b/lib/ITip/Broker.php index b1cfee367..34731e67d 100644 --- a/lib/ITip/Broker.php +++ b/lib/ITip/Broker.php @@ -2,6 +2,7 @@ namespace Sabre\VObject\ITip; +use DateTimeZone; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\DateTimeParser; use Sabre\VObject\Reader; @@ -77,6 +78,12 @@ class Broker 'STATUS', ]; + public $changeProperties = [ + 'LOCATION', + 'SUMMARY', + 'DESCRIPTION' + ]; + /** * This method is used to process an incoming itip message. * @@ -104,12 +111,11 @@ class Broker * * If the iTip message was not supported, we will always return false. * - * @param Message $itipMessage * @param VCalendar $existingObject * * @return VCalendar|null */ - public function processMessage(Message $itipMessage, VCalendar $existingObject = null) + public function processMessage(Message $itipMessage, ?VCalendar $existingObject = null) { // We only support events at the moment. if ('VEVENT' !== $itipMessage->component) { @@ -157,13 +163,13 @@ public function processMessage(Message $itipMessage, VCalendar $existingObject = * people. If the user was an attendee, we need to make sure that the * organizer gets the 'declined' message. * - * @param VCalendar|string $calendar - * @param string|array $userHref - * @param VCalendar|string $oldCalendar + * @param VCalendar|string $calendar + * @param string|array $userHref + * @param VCalendar|string|null $oldCalendar * * @return array */ - public function parseEvent($calendar = null, $userHref, $oldCalendar = null) + public function parseEvent($calendar, $userHref, $oldCalendar = null) { if ($oldCalendar) { if (is_string($oldCalendar)) { @@ -241,16 +247,29 @@ public function parseEvent($calendar = null, $userHref, $oldCalendar = null) $baseCalendar = $oldCalendar; } + // Check if the user is the organizer if (in_array($eventInfo['organizer'], $userHref)) { return $this->parseEventForOrganizer($baseCalendar, $eventInfo, $oldEventInfo); - } elseif ($oldCalendar) { - // We need to figure out if the user is an attendee, but we're only - // doing so if there's an oldCalendar, because we only want to - // process updates, not creation of new events. - foreach ($eventInfo['attendees'] as $attendee) { - if (in_array($attendee['href'], $userHref)) { + } + + // Check if the user is an attendee + foreach ($eventInfo['attendees'] as $attendee) { + if (in_array($attendee['href'], $userHref)) { + // If this is a event update, we always generate a reply + if ($oldCalendar) { return $this->parseEventForAttendee($baseCalendar, $eventInfo, $oldEventInfo, $attendee['href']); } + + // If this is a new event, we only generate a reply if the participation status is set + foreach ($attendee['instances'] as $instance) { + if (isset($instance['partstat']) && 'NEEDS-ACTION' !== $instance['partstat']) { + // Attendee has responded (ACCEPTED/DECLINED/TENTATIVE) - generate REPLY + return $this->parseEventForAttendee($baseCalendar, $eventInfo, $oldEventInfo, $attendee['href']); + } + } + + // User is attendee but no response to process + break; } } @@ -263,13 +282,11 @@ public function parseEvent($calendar = null, $userHref, $oldCalendar = null) * This is message from an organizer, and is either a new event * invite, or an update to an existing one. * - * - * @param Message $itipMessage * @param VCalendar $existingObject * * @return VCalendar|null */ - protected function processMessageRequest(Message $itipMessage, VCalendar $existingObject = null) + protected function processMessageRequest(Message $itipMessage, ?VCalendar $existingObject = null) { if (!$existingObject) { // This is a new invite, and we're just going to copy over @@ -279,14 +296,40 @@ protected function processMessageRequest(Message $itipMessage, VCalendar $existi $existingObject->add(clone $component); } } else { - // We need to update an existing object with all the new - // information. We can just remove all existing components - // and create new ones. + // We need to update an existing object with all the new information. + // We start by removing all non-VEVENT components (VTIMEZONE, etc.) foreach ($existingObject->getComponents() as $component) { - $existingObject->remove($component); + if ($component->name !== 'VEVENT') { + $existingObject->remove($component); + } + } + + // Then we search for a master event in the iTip, if we find it we remove all VEVENT from the original + // calendar object, as we will later add new components from the iTip + foreach ($itipMessage->message->select('VEVENT') as $vEvent) { + if (!isset($vEvent->{'RECURRENCE-ID'})) { + $existingObject->remove('VEVENT'); + } } + + // Then we iterate over the iTip to add new or updated components to the original calendar object foreach ($itipMessage->message->getComponents() as $component) { - $existingObject->add(clone $component); + if ($component->name !== 'VEVENT') { + $existingObject->add(clone $component); + } else { + // It's an exception to a recurring event, we try to find it in the original event to remove it + if (isset($component->{'RECURRENCE-ID'})) { + foreach ($existingObject->select('VEVENT') as $vEvent) { + if (isset($vEvent->{'RECURRENCE-ID'}) && ($vEvent->{'RECURRENCE-ID'}->getDateTime() == $component->{'RECURRENCE-ID'}->getDateTime())) { + $existingObject->remove($vEvent); + + break; + } + } + } + + $existingObject->add(clone $component); + } } } @@ -300,20 +343,87 @@ protected function processMessageRequest(Message $itipMessage, VCalendar $existi * attendee got removed from an event, or an event got cancelled * altogether. * - * @param Message $itipMessage * @param VCalendar $existingObject * * @return VCalendar|null */ - protected function processMessageCancel(Message $itipMessage, VCalendar $existingObject = null) + protected function processMessageCancel(Message $itipMessage, ?VCalendar $existingObject = null) { if (!$existingObject) { // The event didn't exist in the first place, so we're just // ignoring this message. } else { + $instancesToCancel = []; + + $cancelWholeEvent = false; + + // Finding all the instances that are cancelled. + foreach ($itipMessage->message->VEVENT as $vevent) { + if (isset($vevent->{'RECURRENCE-ID'})) { + $recurdate = $vevent->{'RECURRENCE-ID'}->getDateTime(); + $recurIdTimestamp = $recurdate->getTimeStamp(); + + $instancesToCancel[$recurIdTimestamp] = $recurdate; + } else { + // Master is present if it's a non recurring event or if the whole recurring event is cancelled + $cancelWholeEvent = true; + } + } + + $masterObject = null; + foreach ($existingObject->VEVENT as $vevent) { - $vevent->STATUS = 'CANCELLED'; - $vevent->SEQUENCE = $itipMessage->sequence; + $recurIdTimestamp = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimeStamp() : 'master'; + + if ($recurIdTimestamp === 'master') { + $masterObject = $vevent; + } + + if ($cancelWholeEvent) { + $vevent->STATUS = 'CANCELLED'; + $vevent->SEQUENCE = $itipMessage->sequence; + } else if (isset($instancesToCancel[$recurIdTimestamp])) { + $existingObject->remove($vevent); + } + } + + if (!$cancelWholeEvent) { + $exDates = []; + $masterTimeZone = isset($masterObject->EXDATE) ? $masterObject->DTSTART->getDateTime()->getTimeZone() : new DateTimeZone('UTC'); + + if (isset($masterObject->EXDATE)) { + + $exDates = $masterObject->EXDATE->getDateTimes(); + // We only need to update the first timezone, because + // setDateTimes will match all other timezones to the + // first. + + $exDates[0] = $exDates[0]->setTimeZone($masterTimeZone); + + foreach ($exDates as $exDate) { + $exDateTimeStamp = $exDate->getTimeStamp(); + + if (isset($instancesToCancel[$exDateTimeStamp])) { + unset($instancesToCancel[$exDateTimeStamp]); + } + + } + } + + foreach ($instancesToCancel as $instance) { + $instance->setTimezone($masterTimeZone); + $exDates[] = $instance; + } + + $masterObject->remove('EXDATE'); + + $masterObject->add('EXDATE', array_values($exDates)); + + // If TZ has been translated to a standard TZ during conversion, we're putting back the original name + if (isset($masterObject->EXDATE['TZID'])) { + $masterObject->EXDATE['TZID'] = $masterObject->DTSTART['TZID']; + } + } } @@ -326,12 +436,11 @@ protected function processMessageCancel(Message $itipMessage, VCalendar $existin * The message is a reply. This is for example an attendee telling * an organizer he accepted the invite, or declined it. * - * @param Message $itipMessage * @param VCalendar $existingObject * * @return VCalendar|null */ - protected function processMessageReply(Message $itipMessage, VCalendar $existingObject = null) + protected function processMessageReply(Message $itipMessage, ?VCalendar $existingObject = null) { // A reply can only be processed based on an existing object. // If the object is not available, the reply is ignored. @@ -343,9 +452,15 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing // Finding all the instances the attendee replied to. foreach ($itipMessage->message->VEVENT as $vevent) { - $recurId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->getValue() : 'master'; + // Use the Unix timestamp returned by getTimestamp as a unique identifier for the recurrence. + // The Unix timestamp will be the same for an event, even if the reply from the attendee + // used a different format/timezone to express the event date-time. + $recurIdTimestamp = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp() : 'master'; $attendee = $vevent->ATTENDEE; - $instances[$recurId] = $attendee['PARTSTAT']->getValue(); + $instances[$recurIdTimestamp] = [ + 'partstat' => $attendee['PARTSTAT']->getValue(), + 'recurIdDateTime' => isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->getDateTime() : null + ]; if (isset($vevent->{'REQUEST-STATUS'})) { $requestStatus = $vevent->{'REQUEST-STATUS'}->getValue(); list($requestStatus) = explode(';', $requestStatus); @@ -356,17 +471,18 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing // all the instances where we have a reply for. $masterObject = null; foreach ($existingObject->VEVENT as $vevent) { - $recurId = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->getValue() : 'master'; - if ('master' === $recurId) { + // Use the Unix timestamp returned by getTimestamp as a unique identifier for the recurrence. + $recurIdTimestamp = isset($vevent->{'RECURRENCE-ID'}) ? $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimestamp() : 'master'; + if ('master' === $recurIdTimestamp) { $masterObject = $vevent; } - if (isset($instances[$recurId])) { + if (isset($instances[$recurIdTimestamp])) { $attendeeFound = false; if (isset($vevent->ATTENDEE)) { foreach ($vevent->ATTENDEE as $attendee) { if ($attendee->getValue() === $itipMessage->sender) { $attendeeFound = true; - $attendee['PARTSTAT'] = $instances[$recurId]; + $attendee['PARTSTAT'] = $instances[$recurIdTimestamp]['partstat']; $attendee['SCHEDULE-STATUS'] = $requestStatus; // Un-setting the RSVP status, because we now know // that the attendee already replied. @@ -379,13 +495,13 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing // Adding a new attendee. The iTip documentation calls this // a party crasher. $attendee = $vevent->add('ATTENDEE', $itipMessage->sender, [ - 'PARTSTAT' => $instances[$recurId], + 'PARTSTAT' => $instances[$recurIdTimestamp]['partstat'] ]); if ($itipMessage->senderName) { $attendee['CN'] = $itipMessage->senderName; } } - unset($instances[$recurId]); + unset($instances[$recurIdTimestamp]); } } @@ -395,7 +511,7 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing } // If we got replies to instances that did not exist in the // original list, it means that new exceptions must be created. - foreach ($instances as $recurId => $partstat) { + foreach ($instances as $recurIdTimestamp => $instance) { $recurrenceIterator = new EventIterator($existingObject, $itipMessage->uid); $found = false; $iterations = 1000; @@ -403,7 +519,10 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing $newObject = $recurrenceIterator->getEventObject(); $recurrenceIterator->next(); - if (isset($newObject->{'RECURRENCE-ID'}) && $newObject->{'RECURRENCE-ID'}->getValue() === $recurId) { + // Compare the Unix timestamp returned by getTimestamp with the previously calculated timestamp. + // If they are the same, then this is a matching recurrence, even though its date-time may have + // been expressed in a different format/timezone. + if (isset($newObject->{'RECURRENCE-ID'}) && $newObject->{'RECURRENCE-ID'}->getDateTime()->getTimestamp() === $recurIdTimestamp) { $found = true; } --$iterations; @@ -424,7 +543,7 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing foreach ($newObject->ATTENDEE as $attendee) { if ($attendee->getValue() === $itipMessage->sender) { $attendeeFound = true; - $attendee['PARTSTAT'] = $partstat; + $attendee['PARTSTAT'] = $instance['partstat']; break; } } @@ -432,7 +551,7 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing if (!$attendeeFound) { // Adding a new attendee $attendee = $newObject->add('ATTENDEE', $itipMessage->sender, [ - 'PARTSTAT' => $partstat, + 'PARTSTAT' => $instance['partstat'] ]); if ($itipMessage->senderName) { $attendee['CN'] = $itipMessage->senderName; @@ -452,10 +571,6 @@ protected function processMessageReply(Message $itipMessage, VCalendar $existing * We will detect which attendees got added, which got removed and create * specific messages for these situations. * - * @param VCalendar $calendar - * @param array $eventInfo - * @param array $oldEventInfo - * * @return array */ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, array $oldEventInfo) @@ -488,7 +603,6 @@ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, } $messages = []; - foreach ($attendees as $attendee) { // An organizer can also be an attendee. We should not generate any // messages for those. @@ -505,23 +619,26 @@ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, $message->recipient = $attendee['href']; $message->recipientName = $attendee['name']; - if (!$attendee['newInstances']) { - // If there are no instances the attendee is a part of, it - // means the attendee was removed and we need to send him a - // CANCEL. + // Creating the new iCalendar body. + $icalMsg = new VCalendar(); + + foreach ($calendar->select('VTIMEZONE') as $timezone) { + $icalMsg->add(clone $timezone); + } + + if (!$attendee['newInstances'] || 'CANCELLED' === $eventInfo['status']) { + // If there are no instances the attendee is a part of, it means + // the attendee was removed and we need to send them a CANCEL message. + // Also If the meeting STATUS property was changed to CANCELLED + // we need to send the attendee a CANCEL message. $message->method = 'CANCEL'; - // Creating the new iCalendar body. - $icalMsg = new VCalendar(); $icalMsg->METHOD = $message->method; - foreach ($calendar->select('VTIMEZONE') as $timezone) { - $icalMsg->add(clone $timezone); - } - $event = $icalMsg->add('VEVENT', [ 'UID' => $message->uid, 'SEQUENCE' => $message->sequence, + 'DTSTAMP' => gmdate('Ymd\\THis\\Z'), ]); if (isset($calendar->VEVENT->SUMMARY)) { $event->add('SUMMARY', $calendar->VEVENT->SUMMARY->getValue()); @@ -539,34 +656,45 @@ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, $event->add('ATTENDEE', $attendee['href'], [ 'CN' => $attendee['name'], ]); + + if(isset($calendar->VEVENT->VALARM) && $calendar->VEVENT->VALARM->ACTION->getValue() == 'EMAIL') { + $event->add(clone $calendar->VEVENT->VALARM); + $event->VALARM->ATTENDEE->setValue($attendee['href']); + } $message->significantChange = true; } else { // The attendee gets the updated event body $message->method = 'REQUEST'; - // Creating the new iCalendar body. - $icalMsg = new VCalendar(); $icalMsg->METHOD = $message->method; - foreach ($calendar->select('VTIMEZONE') as $timezone) { - $icalMsg->add(clone $timezone); - } - // We need to find out that this change is significant. If it's - // not, systems may opt to not send messages. + // not, we set another variable to find if the change need to send a message. // // We do this based on the 'significantChangeHash' which is // some value that changes if there's a certain set of // properties changed in the event, or simply if there's a // difference in instances that the attendee is invited to. + $oldAttendeeInstances = array_keys($attendee['oldInstances']); + $newAttendeeInstances = array_keys($attendee['newInstances']); + $message->significantChange = 'REQUEST' === $attendee['forceSend'] || - array_keys($attendee['oldInstances']) != array_keys($attendee['newInstances']) || + count($oldAttendeeInstances) != count($newAttendeeInstances) || + count(array_diff($oldAttendeeInstances, $newAttendeeInstances)) > 0 || $oldEventInfo['significantChangeHash'] !== $eventInfo['significantChangeHash']; + $message->hasChange = + $message->significantChange || + $oldEventInfo['changeHash'] !== $eventInfo['changeHash']; + foreach ($attendee['newInstances'] as $instanceId => $instanceInfo) { $currentEvent = clone $eventInfo['instances'][$instanceId]; + if(isset($currentEvent->VALARM) && $currentEvent->VALARM->ACTION->getValue() == 'EMAIL') { + $currentEvent->VALARM->ATTENDEE->setValue($attendee['href']); + } + if ('master' === $instanceId) { // We need to find a list of events that the attendee // is not a part of to add to the list of exceptions. @@ -587,6 +715,9 @@ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, )); } else { $currentEvent->EXDATE = $exceptions; + if ($currentEvent->DTSTART['TZID']) { + $currentEvent->EXDATE['TZID'] = clone $currentEvent->DTSTART['TZID']; + } } } @@ -595,18 +726,19 @@ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, unset($currentEvent->ORGANIZER['SCHEDULE-FORCE-SEND']); unset($currentEvent->ORGANIZER['SCHEDULE-STATUS']); - foreach ($currentEvent->ATTENDEE as $attendee) { - unset($attendee['SCHEDULE-FORCE-SEND']); - unset($attendee['SCHEDULE-STATUS']); + foreach ($currentEvent->ATTENDEE as $currentEventAttendee) { + unset($currentEventAttendee['SCHEDULE-FORCE-SEND']); + unset($currentEventAttendee['SCHEDULE-STATUS']); // We're adding PARTSTAT=NEEDS-ACTION to ensure that // iOS shows an "Inbox Item" - if (!isset($attendee['PARTSTAT'])) { - $attendee['PARTSTAT'] = 'NEEDS-ACTION'; + if (!isset($currentEventAttendee['PARTSTAT'])) { + $currentEventAttendee['PARTSTAT'] = 'NEEDS-ACTION'; } } } + $currentEvent->DTSTAMP = gmdate('Ymd\\THis\\Z'); $icalMsg->add($currentEvent); } } @@ -623,10 +755,7 @@ protected function parseEventForOrganizer(VCalendar $calendar, array $eventInfo, * * This function figures out if we need to send a reply to an organizer. * - * @param VCalendar $calendar - * @param array $eventInfo - * @param array $oldEventInfo - * @param string $attendee + * @param string $attendee * * @return Message[] */ @@ -673,7 +802,7 @@ protected function parseEventForAttendee(VCalendar $calendar, array $eventInfo, // We only need to do that though, if the master event is not declined. if (isset($instances['master']) && 'DECLINED' !== $instances['master']['newstatus']) { foreach ($eventInfo['exdate'] as $exDate) { - if (!in_array($exDate, $oldEventInfo['exdate'])) { + if (!in_array($exDate, $oldEventInfo['exdate'] ?? [])) { if (isset($instances[$exDate])) { $instances[$exDate]['newstatus'] = 'DECLINED'; } else { @@ -696,20 +825,7 @@ protected function parseEventForAttendee(VCalendar $calendar, array $eventInfo, } } - $message = new Message(); - $message->uid = $eventInfo['uid']; - $message->method = 'REPLY'; - $message->component = 'VEVENT'; - $message->sequence = $eventInfo['sequence']; - $message->sender = $attendee; - $message->senderName = $eventInfo['attendees'][$attendee]['name']; - $message->recipient = $eventInfo['organizer']; - $message->recipientName = $eventInfo['organizerName']; - - $icalMsg = new VCalendar(); - $icalMsg->METHOD = 'REPLY'; - - $hasReply = false; + $messages = []; foreach ($instances as $instance) { if ($instance['oldstatus'] == $instance['newstatus'] && 'REPLY' !== $eventInfo['organizerForceSend']) { @@ -717,14 +833,35 @@ protected function parseEventForAttendee(VCalendar $calendar, array $eventInfo, continue; } + $message = new Message(); + $message->uid = $eventInfo['uid']; + $message->method = 'REPLY'; + $message->component = 'VEVENT'; + $message->sender = $attendee; + $message->senderName = $eventInfo['attendees'][$attendee]['name']; + $message->recipient = $eventInfo['organizer']; + $message->recipientName = $eventInfo['organizerName']; + + $icalMsg = new VCalendar(); + $icalMsg->METHOD = 'REPLY'; + + foreach ($calendar->select('VTIMEZONE') as $timezone) { + $icalMsg->add(clone $timezone); + } + $event = $icalMsg->add('VEVENT', [ 'UID' => $message->uid, - 'SEQUENCE' => $message->sequence, ]); + $summary = isset($calendar->VEVENT->SUMMARY) ? $calendar->VEVENT->SUMMARY->getValue() : ''; // Adding properties from the correct source instance if (isset($eventInfo['instances'][$instance['id']])) { $instanceObj = $eventInfo['instances'][$instance['id']]; + if (isset($instanceObj->SEQUENCE)) { + $event->add('SEQUENCE', $instanceObj->SEQUENCE); + + $message->sequence = $eventInfo['sequence']; + } $event->add(clone $instanceObj->DTSTART); if (isset($instanceObj->DTEND)) { $event->add(clone $instanceObj->DTEND); @@ -765,22 +902,17 @@ protected function parseEventForAttendee(VCalendar $calendar, array $eventInfo, if ($message->recipientName) { $organizer['CN'] = $message->recipientName; } - $attendee = $event->add('ATTENDEE', $message->sender, [ - 'PARTSTAT' => $instance['newstatus'], + $msgAttendee = $event->add('ATTENDEE', $message->sender, [ + 'PARTSTAT' => $instance['newstatus'] ]); if ($message->senderName) { - $attendee['CN'] = $message->senderName; + $msgAttendee['CN'] = $message->senderName; } - $hasReply = true; - } - - if ($hasReply) { $message->message = $icalMsg; - - return [$message]; - } else { - return []; + $messages[] = $message; } + + return $messages; } /** @@ -807,7 +939,7 @@ protected function parseEventForAttendee(VCalendar $calendar, array $eventInfo, * * @return array */ - protected function parseEventInfo(VCalendar $calendar = null) + protected function parseEventInfo(?VCalendar $calendar = null) { $uid = null; $organizer = null; @@ -819,6 +951,7 @@ protected function parseEventInfo(VCalendar $calendar = null) $organizerScheduleAgent = 'SERVER'; $significantChangeHash = ''; + $changeHash = ''; // Now we need to collect a list of attendees, and which instances they // are a part of. @@ -827,7 +960,10 @@ protected function parseEventInfo(VCalendar $calendar = null) $instances = []; $exdate = []; + $significantChangeEventProperties = []; + foreach ($calendar->VEVENT as $vevent) { + $eventSignificantChangeHash = ''; $rrule = []; if (is_null($uid)) { @@ -853,12 +989,12 @@ protected function parseEventInfo(VCalendar $calendar = null) } $organizerForceSend = isset($vevent->ORGANIZER['SCHEDULE-FORCE-SEND']) ? - strtoupper($vevent->ORGANIZER['SCHEDULE-FORCE-SEND']) : - null; + strtoupper($vevent->ORGANIZER['SCHEDULE-FORCE-SEND']) : + null; $organizerScheduleAgent = isset($vevent->ORGANIZER['SCHEDULE-AGENT']) ? - strtoupper((string) $vevent->ORGANIZER['SCHEDULE-AGENT']) : - 'SERVER'; + strtoupper((string) $vevent->ORGANIZER['SCHEDULE-AGENT']) : + 'SERVER'; } if (is_null($sequence) && isset($vevent->SEQUENCE)) { $sequence = $vevent->SEQUENCE->getValue(); @@ -896,6 +1032,9 @@ protected function parseEventInfo(VCalendar $calendar = null) $timezone = $vevent->{'RECURRENCE-ID'}->getDateTime()->getTimeZone(); } } + + $instances[$recurId] = $vevent; + if (isset($vevent->ATTENDEE)) { foreach ($vevent->ATTENDEE as $attendee) { if ($this->scheduleAgentServerRules && @@ -906,13 +1045,13 @@ protected function parseEventInfo(VCalendar $calendar = null) } $partStat = isset($attendee['PARTSTAT']) ? - strtoupper($attendee['PARTSTAT']) : - 'NEEDS-ACTION'; + strtoupper($attendee['PARTSTAT']) : + 'NEEDS-ACTION'; $forceSend = isset($attendee['SCHEDULE-FORCE-SEND']) ? - strtoupper($attendee['SCHEDULE-FORCE-SEND']) : - null; + strtoupper($attendee['SCHEDULE-FORCE-SEND']) : + null; if (isset($attendees[$attendee->getNormalizedValue()])) { $attendees[$attendee->getNormalizedValue()]['instances'][$recurId] = [ @@ -934,28 +1073,48 @@ protected function parseEventInfo(VCalendar $calendar = null) ]; } } - $instances[$recurId] = $vevent; } foreach ($this->significantChangeProperties as $prop) { if (isset($vevent->$prop)) { $propertyValues = $vevent->select($prop); - $significantChangeHash .= $prop.':'; + $eventSignificantChangeHash .= $prop.':'; if ('EXDATE' === $prop) { - $significantChangeHash .= implode(',', $exdate).';'; + $eventSignificantChangeHash .= implode(',', $exdate).';'; } elseif ('RRULE' === $prop) { - $significantChangeHash .= implode(',', $rrule).';'; + $eventSignificantChangeHash .= implode(',', $rrule).';'; } else { foreach ($propertyValues as $val) { - $significantChangeHash .= $val->getValue().';'; + $eventSignificantChangeHash .= $val->getValue().';'; } } } } + + foreach ($this->changeProperties as $prop) { + if (isset($vevent->$prop)) { + $propertyValues = $vevent->select($prop); + + $changeHash .= $prop . ':'; + + foreach ($propertyValues as $val) { + $changeHash .= $val->getValue() . ';'; + } + } + } + + $significantChangeEventProperties[] = $eventSignificantChangeHash; + } + + asort($significantChangeEventProperties); + + foreach ($significantChangeEventProperties as $eventSignificantChangeHash) { + $significantChangeHash .= $eventSignificantChangeHash; } $significantChangeHash = md5($significantChangeHash); + $changeHash= md5($changeHash); return compact( 'uid', @@ -969,6 +1128,7 @@ protected function parseEventInfo(VCalendar $calendar = null) 'exdate', 'timezone', 'significantChangeHash', + 'changeHash', 'status' ); } diff --git a/lib/ITip/Message.php b/lib/ITip/Message.php index 43536f172..8af1b1d34 100644 --- a/lib/ITip/Message.php +++ b/lib/ITip/Message.php @@ -115,6 +115,17 @@ class Message */ public $significantChange = true; + /** + * This will be set to true, if the iTip broker considers the change + * not 'significant' but the change need to send a message. + * + * To see the list of properties that are considered not 'significant' but important, check + * out Sabre\VObject\ITip\Broker::$changeProperties. + * + * @var bool + */ + public $hasChange = true; + /** * Returns the schedule status as a string. * diff --git a/lib/Node.php b/lib/Node.php index 154a7fac5..d7cd9caab 100644 --- a/lib/Node.php +++ b/lib/Node.php @@ -73,6 +73,7 @@ abstract public function serialize(); * * @return array */ + #[\ReturnTypeWillChange] abstract public function jsonSerialize(); /** @@ -81,7 +82,7 @@ abstract public function jsonSerialize(); * * @param Xml\Writer $writer XML writer */ - abstract public function xmlSerialize(Xml\Writer $writer); + abstract public function xmlSerialize(Xml\Writer $writer): void; /** * Call this method on a document if you're done using it. @@ -102,6 +103,7 @@ public function destroy() * * @return ElementList */ + #[\ReturnTypeWillChange] public function getIterator() { if (!is_null($this->iterator)) { @@ -115,8 +117,6 @@ public function getIterator() * Sets the overridden iterator. * * Note that this is not actually part of the iterator interface - * - * @param ElementList $iterator */ public function setIterator(ElementList $iterator) { @@ -159,6 +159,7 @@ public function validate($options = 0) * * @return int */ + #[\ReturnTypeWillChange] public function count() { $it = $this->getIterator(); @@ -179,6 +180,7 @@ public function count() * * @return bool */ + #[\ReturnTypeWillChange] public function offsetExists($offset) { $iterator = $this->getIterator(); @@ -195,6 +197,7 @@ public function offsetExists($offset) * * @return mixed */ + #[\ReturnTypeWillChange] public function offsetGet($offset) { $iterator = $this->getIterator(); @@ -209,7 +212,10 @@ public function offsetGet($offset) * * @param int $offset * @param mixed $value + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { $iterator = $this->getIterator(); @@ -229,7 +235,10 @@ public function offsetSet($offset, $value) * This method just forwards the request to the inner iterator * * @param int $offset + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetUnset($offset) { $iterator = $this->getIterator(); diff --git a/lib/PHPUnitAssertions.php b/lib/PHPUnitAssertions.php index d77e4b1ed..45c0a21c6 100644 --- a/lib/PHPUnitAssertions.php +++ b/lib/PHPUnitAssertions.php @@ -15,7 +15,7 @@ trait PHPUnitAssertions { /** - * This method tests wether two vcards or icalendar objects are + * This method tests whether two vcards or icalendar objects are * semantically identical. * * It supports objects being supplied as strings, streams or @@ -34,8 +34,7 @@ trait PHPUnitAssertions */ public function assertVObjectEqualsVObject($expected, $actual, $message = '') { - $self = $this; - $getObj = function ($input) use ($self) { + $getObj = function ($input) { if (is_resource($input)) { $input = stream_get_contents($input); } diff --git a/lib/Parameter.php b/lib/Parameter.php index d370482f0..0f0b5860c 100644 --- a/lib/Parameter.php +++ b/lib/Parameter.php @@ -29,7 +29,7 @@ class Parameter extends Node /** * vCard 2.1 allows parameters to be encoded without a name. * - * We can deduce the parameter name based on it's value. + * We can deduce the parameter name based on its value. * * @var bool */ @@ -52,11 +52,12 @@ class Parameter extends Node */ public function __construct(Document $root, $name, $value = null) { - $this->name = strtoupper($name); $this->root = $root; if (is_null($name)) { $this->noName = true; $this->name = static::guessParameterNameByValue($value); + } else { + $this->name = strtoupper($name); } // If guessParameterNameByValue() returns an empty string @@ -95,13 +96,11 @@ public static function guessParameterNameByValue($value) case 'WORK': case 'HOME': case 'PREF': - // Delivery Label Type case 'DOM': case 'INTL': case 'POSTAL': case 'PARCEL': - // Telephone types case 'VOICE': case 'FAX': @@ -113,7 +112,6 @@ public static function guessParameterNameByValue($value) case 'CAR': case 'ISDN': case 'VIDEO': - // EMAIL types (lol) case 'AOL': case 'APPLELINK': @@ -127,7 +125,6 @@ public static function guessParameterNameByValue($value) case 'PRODIGY': case 'TLX': case 'X400': - // Photo / Logo format types case 'GIF': case 'CGM': @@ -143,12 +140,10 @@ public static function guessParameterNameByValue($value) case 'MPEG2': case 'AVI': case 'QTIME': - // Sound Digital Audio Type case 'WAVE': case 'PCM': case 'AIFF': - // Key types case 'X509': case 'PGP': @@ -201,8 +196,6 @@ public function getValue() /** * Sets multiple values for this parameter. - * - * @param array $value */ public function setParts(array $value) { @@ -301,7 +294,7 @@ function ($out, $item) { // https://tools.ietf.org/html/rfc6868 // // But we've found that iCal (7.0, shipped with OSX 10.9) - // severaly trips on + characters not being quoted, so we + // severely trips on + characters not being quoted, so we // added + as well. if (!preg_match('#(?: [\n":;\^,\+] )#x', $item)) { return $out.$item; @@ -329,6 +322,7 @@ function ($out, $item) { * * @return array */ + #[\ReturnTypeWillChange] public function jsonSerialize() { return $this->value; @@ -340,7 +334,7 @@ public function jsonSerialize() * * @param Xml\Writer $writer XML writer */ - public function xmlSerialize(Xml\Writer $writer) + public function xmlSerialize(Xml\Writer $writer): void { foreach (explode(',', $this->value) as $value) { $writer->writeElement('text', $value); @@ -362,6 +356,7 @@ public function __toString() * * @return ElementList */ + #[\ReturnTypeWillChange] public function getIterator() { if (!is_null($this->iterator)) { diff --git a/lib/Parser/Json.php b/lib/Parser/Json.php index 3fd307e97..f33603207 100644 --- a/lib/Parser/Json.php +++ b/lib/Parser/Json.php @@ -7,6 +7,8 @@ use Sabre\VObject\Document; use Sabre\VObject\EofException; use Sabre\VObject\ParseException; +use Sabre\VObject\Property\FlatText; +use Sabre\VObject\Property\Text; /** * Json Parser. @@ -87,8 +89,6 @@ public function parse($input = null, $options = 0) /** * Parses a component. * - * @param array $jComp - * * @return \Sabre\VObject\Component */ public function parseComponent(array $jComp) @@ -124,8 +124,6 @@ function ($jComp) use ($self) { /** * Parses properties. * - * @param array $jProp - * * @return \Sabre\VObject\Property */ public function parseProperty(array $jProp) @@ -160,8 +158,8 @@ public function parseProperty(array $jProp) // represents TEXT values. We have to normalize these here. In the // future we can get rid of FlatText once we're allowed to break BC // again. - if ('Sabre\VObject\Property\FlatText' === $defaultPropertyClass) { - $defaultPropertyClass = 'Sabre\VObject\Property\Text'; + if (FlatText::class === $defaultPropertyClass) { + $defaultPropertyClass = Text::class; } // If the value type we received (e.g.: TEXT) was not the default value diff --git a/lib/Parser/MimeDir.php b/lib/Parser/MimeDir.php index d98225b59..5520530d0 100644 --- a/lib/Parser/MimeDir.php +++ b/lib/Parser/MimeDir.php @@ -25,6 +25,11 @@ */ class MimeDir extends Parser { + public const TOKEN_PROPNAME = 1; + public const TOKEN_PROPVALUE = 2; + public const TOKEN_PARAMNAME = 3; + public const TOKEN_PARAMVALUE = 4; + /** * The input stream. * @@ -83,6 +88,12 @@ public function parse($input = null, $options = 0) $this->setInput($input); } + if (!\is_resource($this->input)) { + // Null was passed as input, but there was no existing input buffer + // There is nothing to parse. + throw new ParseException('No input provided to parse'); + } + if (0 !== $options) { $this->options = $options; } @@ -124,7 +135,7 @@ public function setInput($input) $this->startLine = 0; if (is_string($input)) { - // Convering to a stream. + // Converting to a stream. $stream = fopen('php://temp', 'r+'); fwrite($stream, $input); rewind($stream); @@ -167,7 +178,11 @@ protected function parseDocument() while (true) { // Reading until we hit END: - $line = $this->readLine(); + try { + $line = $this->readLine(); + } catch (EofException $oEx) { + $line = 'END:'.$this->root->name; + } if ('END:' === strtoupper(substr($line, 0, 4))) { break; } @@ -195,6 +210,9 @@ protected function parseLine($line) { // Start of a new component if ('BEGIN:' === strtoupper(substr($line, 0, 6))) { + if (substr($line, 6) === $this->root->name) { + throw new ParseException('Invalid MimeDir file. Unexpected component: "'.$line.'" in document type '.$this->root->name); + } $component = $this->root->createComponent(substr($line, 6), [], false); while (true) { @@ -233,7 +251,7 @@ protected function parseLine($line) * * If that was not the case, we store it here. * - * @var null|string + * @var string|null */ protected $lineBuffer; @@ -340,7 +358,7 @@ protected function readProperty($line) ) (?=[;:,]) /xi"; - //echo $regex, "\n"; die(); + //echo $regex, "\n"; exit(); preg_match_all($regex, $line, $matches, PREG_SET_ORDER); $property = [ @@ -349,6 +367,12 @@ protected function readProperty($line) 'value' => null, ]; + /* + * Keep track on the last token we parsed in order to do + * better error checking + */ + $lastToken = null; + $lastParam = null; /* @@ -369,18 +393,35 @@ protected function readProperty($line) $value = $this->unescapeParam($value); if (is_null($lastParam)) { + if ($this->options & self::OPTION_IGNORE_INVALID_LINES) { + // When the property can't be matched and the configuration + // option is set to ignore invalid lines, we ignore this line + // This can happen when servers provide faulty data as iCloud + // frequently does with X-APPLE-STRUCTURED-LOCATION + $lastToken = self::TOKEN_PARAMVALUE; + continue; + } throw new ParseException('Invalid Mimedir file. Line starting at '.$this->startLine.' did not follow iCalendar/vCard conventions'); } + + if ('=' == $match[0][0] && self::TOKEN_PARAMNAME != $lastToken) { + throw new ParseException('Invalid Mimedir file. Line starting at '.$this->startLine.': Missing parameter name for parameter value "'.$match['paramValue'].'"'); + } + if (is_null($property['parameters'][$lastParam])) { $property['parameters'][$lastParam] = $value; } elseif (is_array($property['parameters'][$lastParam])) { $property['parameters'][$lastParam][] = $value; + } elseif ($property['parameters'][$lastParam] === $value) { + // When the current value of the parameter is the same as the + // new one, then we can leave the current parameter as it is. } else { $property['parameters'][$lastParam] = [ $property['parameters'][$lastParam], $value, ]; } + $lastToken = self::TOKEN_PARAMVALUE; continue; } if (isset($match['paramName'])) { @@ -388,14 +429,17 @@ protected function readProperty($line) if (!isset($property['parameters'][$lastParam])) { $property['parameters'][$lastParam] = null; } + $lastToken = self::TOKEN_PARAMNAME; continue; } if (isset($match['propValue'])) { $property['value'] = $match['propValue']; + $lastToken = self::TOKEN_PROPVALUE; continue; } - if (isset($match['name']) && $match['name']) { + if (isset($match['name']) && 0 < strlen($match['name'])) { $property['name'] = strtoupper($match['name']); + $lastToken = self::TOKEN_PROPNAME; continue; } @@ -407,7 +451,7 @@ protected function readProperty($line) if (is_null($property['value'])) { $property['value'] = ''; } - if (!$property['name']) { + if (!isset($property['name']) || 0 == strlen($property['name'])) { if ($this->options & self::OPTION_IGNORE_INVALID_LINES) { return false; } @@ -415,7 +459,7 @@ protected function readProperty($line) } // vCard 2.1 states that parameters may appear without a name, and only - // a value. We can deduce the value based on it's name. + // a value. We can deduce the value based on its name. // // Our parser will get those as parameters without a value instead, so // we're filtering these parameters out first. @@ -430,13 +474,13 @@ protected function readProperty($line) } } - $propObj = $this->root->createProperty($property['name'], null, $namedParameters); + $propObj = $this->root->createProperty($property['name'], null, $namedParameters, null, $this->startLine, $line); foreach ($namelessParameters as $namelessParameter) { $propObj->add(null, $namelessParameter); } - if ('QUOTED-PRINTABLE' === strtoupper($propObj['ENCODING'])) { + if (isset($propObj['ENCODING']) && 'QUOTED-PRINTABLE' === strtoupper($propObj['ENCODING'])) { $propObj->setQuotedPrintableValue($this->extractQuotedPrintableValue()); } else { $charset = $this->charset; @@ -447,10 +491,8 @@ protected function readProperty($line) switch (strtolower($charset)) { case 'utf-8': break; - case 'iso-8859-1': - $property['value'] = utf8_encode($property['value']); - break; case 'windows-1252': + case 'iso-8859-1': $property['value'] = mb_convert_encoding($property['value'], 'UTF-8', $charset); break; default: @@ -477,7 +519,7 @@ protected function readProperty($line) * vCard 3.0 says: * * (rfc2425) Backslashes, newlines (\n or \N) and comma's must be * escaped, all time time. - * * Comma's are used for delimeters in multiple values + * * Comma's are used for delimiters in multiple values * * (rfc2426) Adds to to this that the semi-colon MUST also be escaped, * as in some properties semi-colon is used for separators. * * Properties using semi-colons: N, ADR, GEO, ORG @@ -515,7 +557,7 @@ protected function readProperty($line) * * Now for the parameters * - * If delimiter is not set (null) this method will just return a string. + * If delimiter is not set (empty string) this method will just return a string. * If it's a comma or a semi-colon the string will be split on those * characters, and always return an array. * @@ -655,7 +697,7 @@ private function extractQuotedPrintableValue() // missing a whitespace. So if 'forgiving' is turned on, we will take // those as well. if ($this->options & self::OPTION_FORGIVING) { - while ('=' === substr($value, -1)) { + while ('=' === substr($value, -1) && $this->lineBuffer) { // Reading the line $this->readLine(); // Grabbing the raw form diff --git a/lib/Parser/XML.php b/lib/Parser/XML.php index 90f262d9e..78773173d 100644 --- a/lib/Parser/XML.php +++ b/lib/Parser/XML.php @@ -112,8 +112,6 @@ public function parse($input = null, $options = 0) /** * Parse a xCalendar component. - * - * @param Component $parentComponent */ protected function parseVCalendarComponents(Component $parentComponent) { @@ -134,8 +132,6 @@ protected function parseVCalendarComponents(Component $parentComponent) /** * Parse a xCard component. - * - * @param Component $parentComponent */ protected function parseVCardComponents(Component $parentComponent) { @@ -146,8 +142,7 @@ protected function parseVCardComponents(Component $parentComponent) /** * Parse xCalendar and xCard properties. * - * @param Component $parentComponent - * @param string $propertyNamePrefix + * @param string $propertyNamePrefix */ protected function parseProperties(Component $parentComponent, $propertyNamePrefix = '') { @@ -302,8 +297,6 @@ protected function parseProperties(Component $parentComponent, $propertyNamePref /** * Parse a component. - * - * @param Component $parentComponent */ protected function parseComponent(Component $parentComponent) { @@ -327,11 +320,10 @@ protected function parseComponent(Component $parentComponent) /** * Create a property. * - * @param Component $parentComponent - * @param string $name - * @param array $parameters - * @param string $type - * @param mixed $value + * @param string $name + * @param array $parameters + * @param string $type + * @param mixed $value */ protected function createProperty(Component $parentComponent, $name, $parameters, $type, $value) { @@ -359,9 +351,9 @@ public function setInput($input) if (is_string($input)) { $reader = new SabreXml\Reader(); $reader->elementMap['{'.self::XCAL_NAMESPACE.'}period'] - = 'Sabre\VObject\Parser\XML\Element\KeyValue'; + = XML\Element\KeyValue::class; $reader->elementMap['{'.self::XCAL_NAMESPACE.'}recur'] - = 'Sabre\VObject\Parser\XML\Element\KeyValue'; + = XML\Element\KeyValue::class; $reader->xml($input); $input = $reader->parse(); } diff --git a/lib/Parser/XML/Element/KeyValue.php b/lib/Parser/XML/Element/KeyValue.php index e26540036..e01772510 100644 --- a/lib/Parser/XML/Element/KeyValue.php +++ b/lib/Parser/XML/Element/KeyValue.php @@ -18,7 +18,7 @@ class KeyValue extends SabreXml\Element\KeyValue /** * The deserialize method is called during xml parsing. * - * This method is called staticly, this is because in theory this method + * This method is called statically, this is because in theory this method * may be used as a type of constructor, or factory method. * * Often you want to return an instance of the current class, but you are @@ -34,10 +34,8 @@ class KeyValue extends SabreXml\Element\KeyValue * the next element. * * @param XML\Reader $reader - * - * @return mixed */ - public static function xmlDeserialize(SabreXml\Reader $reader) + public static function xmlDeserialize(SabreXml\Reader $reader): array { // If there's no children, we don't do anything. if ($reader->isEmptyElement) { diff --git a/lib/Property.php b/lib/Property.php index 4aa26d517..7cf591486 100644 --- a/lib/Property.php +++ b/lib/Property.php @@ -30,7 +30,7 @@ abstract class Property extends Node * * This is only used in vcards * - * @var string + * @var string|null */ public $group; @@ -52,10 +52,24 @@ abstract class Property extends Node * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ public $delimiter = ';'; + /** + * The line number in the original iCalendar / vCard file + * that corresponds with the current node + * if the node was read from a file. + */ + public $lineIndex; + + /** + * The line string from the original iCalendar / vCard file + * that corresponds with the current node + * if the node was read from a file. + */ + public $lineString; + /** * Creates the generic property. * @@ -67,7 +81,7 @@ abstract class Property extends Node * @param array $parameters List of parameters * @param string $group The vcard property group */ - public function __construct(Component $root, $name, $value = null, array $parameters = [], $group = null) + public function __construct(Component $root, $name, $value = null, array $parameters = [], $group = null, ?int $lineIndex = null, ?string $lineString = null) { $this->name = $name; $this->group = $group; @@ -81,6 +95,14 @@ public function __construct(Component $root, $name, $value = null, array $parame if (!is_null($value)) { $this->setValue($value); } + + if (!is_null($lineIndex)) { + $this->lineIndex = $lineIndex; + } + + if (!is_null($lineString)) { + $this->lineString = $lineString; + } } /** @@ -123,8 +145,6 @@ public function getValue() /** * Sets a multi-valued property. - * - * @param array $parts */ public function setParts(array $parts) { @@ -155,10 +175,10 @@ public function getParts() * * If a parameter with same name already existed, the values will be * combined. - * If nameless parameter is added, we try to guess it's name. + * If nameless parameter is added, we try to guess its name. * * @param string $name - * @param string|null|array $value + * @param string|array|null $value */ public function add($name, $value = null) { @@ -262,8 +282,6 @@ public function getJsonValue() * Sets the JSON value, as it would appear in a jCard or jCal object. * * The value must always be an array. - * - * @param array $value */ public function setJsonValue(array $value) { @@ -280,6 +298,7 @@ public function setJsonValue(array $value) * * @return array */ + #[\ReturnTypeWillChange] public function jsonSerialize() { $parameters = []; @@ -309,8 +328,6 @@ public function jsonSerialize() /** * Hydrate data from a XML subtree, as it would appear in a xCard or xCal * object. - * - * @param array $value */ public function setXmlValue(array $value) { @@ -323,7 +340,7 @@ public function setXmlValue(array $value) * * @param Xml\Writer $writer XML writer */ - public function xmlSerialize(Xml\Writer $writer) + public function xmlSerialize(Xml\Writer $writer): void { $parameters = []; @@ -393,6 +410,7 @@ public function __toString() * * @return bool */ + #[\ReturnTypeWillChange] public function offsetExists($name) { if (is_int($name)) { @@ -419,6 +437,7 @@ public function offsetExists($name) * * @return Node */ + #[\ReturnTypeWillChange] public function offsetGet($name) { if (is_int($name)) { @@ -438,7 +457,10 @@ public function offsetGet($name) * * @param string $name * @param mixed $value + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetSet($name, $value) { if (is_int($name)) { @@ -458,7 +480,10 @@ public function offsetSet($name, $value) * Removes one or more parameters with the specified name. * * @param string $name + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetUnset($name) { if (is_int($name)) { @@ -572,6 +597,18 @@ public function validate($options = 0) break; case Document::VCARD30: $allowedEncoding = ['B']; + //Repair vCard30 that use BASE64 encoding + if ($options & self::REPAIR) { + if ('BASE64' === strtoupper($encoding)) { + $encoding = 'B'; + $this['ENCODING'] = $encoding; + $warnings[] = [ + 'level' => 1, + 'message' => 'ENCODING=BASE64 has been transformed to ENCODING=B.', + 'node' => $this, + ]; + } + } break; } if ($allowedEncoding && !in_array(strtoupper($encoding), $allowedEncoding)) { diff --git a/lib/Property/Binary.php b/lib/Property/Binary.php index 830dd9028..1262dd054 100644 --- a/lib/Property/Binary.php +++ b/lib/Property/Binary.php @@ -24,9 +24,9 @@ class Binary extends Property * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Updates the current value. @@ -100,8 +100,6 @@ public function getJsonValue() * Sets the json value, as it would appear in a jCard or jCal object. * * The value must always be an array. - * - * @param array $value */ public function setJsonValue(array $value) { diff --git a/lib/Property/Boolean.php b/lib/Property/Boolean.php index 1b219bb8c..4bd6ffdfe 100644 --- a/lib/Property/Boolean.php +++ b/lib/Property/Boolean.php @@ -2,13 +2,12 @@ namespace Sabre\VObject\Property; -use - Sabre\VObject\Property; +use Sabre\VObject\Property; /** * Boolean property. * - * This object represents BOOLEAN values. These are always the case-insenstive + * This object represents BOOLEAN values. These are always the case-insensitive * string TRUE or FALSE. * * Automatic conversion to PHP's true and false are done. @@ -59,8 +58,6 @@ public function getValueType() /** * Hydrate data from a XML subtree, as it would appear in a xCard or xCal * object. - * - * @param array $value */ public function setXmlValue(array $value) { diff --git a/lib/Property/FloatValue.php b/lib/Property/FloatValue.php index 208d74516..e780ae6c1 100644 --- a/lib/Property/FloatValue.php +++ b/lib/Property/FloatValue.php @@ -21,7 +21,7 @@ class FloatValue extends Property * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ public $delimiter = ';'; @@ -93,8 +93,6 @@ public function getJsonValue() /** * Hydrate data from a XML subtree, as it would appear in a xCard or xCal * object. - * - * @param array $value */ public function setXmlValue(array $value) { diff --git a/lib/Property/ICalendar/CalAddress.php b/lib/Property/ICalendar/CalAddress.php index e89bb31f9..c90967d79 100644 --- a/lib/Property/ICalendar/CalAddress.php +++ b/lib/Property/ICalendar/CalAddress.php @@ -2,8 +2,7 @@ namespace Sabre\VObject\Property\ICalendar; -use - Sabre\VObject\Property\Text; +use Sabre\VObject\Property\Text; /** * CalAddress property. @@ -20,9 +19,9 @@ class CalAddress extends Text * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Returns the type of value. @@ -54,7 +53,11 @@ public function getNormalizedValue() return $input; } list($schema, $everythingElse) = explode(':', $input, 2); + $schema = strtolower($schema); + if ('mailto' === $schema) { + $everythingElse = strtolower($everythingElse); + } - return strtolower($schema).':'.$everythingElse; + return $schema.':'.$everythingElse; } } diff --git a/lib/Property/ICalendar/DateTime.php b/lib/Property/ICalendar/DateTime.php index 7eb3e0bb7..12f8cd951 100644 --- a/lib/Property/ICalendar/DateTime.php +++ b/lib/Property/ICalendar/DateTime.php @@ -38,8 +38,6 @@ class DateTime extends Property * Sets a multi-valued property. * * You may also specify DateTime objects here. - * - * @param array $parts */ public function setParts(array $parts) { @@ -133,7 +131,7 @@ public function isFloating() * * @return \DateTimeImmutable */ - public function getDateTime(DateTimeZone $timeZone = null) + public function getDateTime(?DateTimeZone $timeZone = null) { $dt = $this->getDateTimes($timeZone); if (!$dt) { @@ -155,7 +153,7 @@ public function getDateTime(DateTimeZone $timeZone = null) * @return \DateTimeImmutable[] * @return \DateTime[] */ - public function getDateTimes(DateTimeZone $timeZone = null) + public function getDateTimes(?DateTimeZone $timeZone = null) { // Does the property have a TZID? $tzid = $this['TZID']; @@ -175,7 +173,6 @@ public function getDateTimes(DateTimeZone $timeZone = null) /** * Sets the property as a DateTime object. * - * @param DateTimeInterface $dt * @param bool isFloating If set to true, timezones will be ignored */ public function setDateTime(DateTimeInterface $dt, $isFloating = false) @@ -187,7 +184,7 @@ public function setDateTime(DateTimeInterface $dt, $isFloating = false) * Sets the property as multiple date-time objects. * * The first value will be used as a reference for the timezones, and all - * the otehr values will be adjusted for that timezone + * the other values will be adjusted for that timezone * * @param DateTimeInterface[] $dt * @param bool isFloating If set to true, timezones will be ignored @@ -279,8 +276,6 @@ function (DateTimeInterface $dt) use ($hasTime, $isUtc) { * Sets the json value, as it would appear in a jCard or jCal object. * * The value must always be an array. - * - * @param array $value */ public function setJsonValue(array $value) { @@ -304,7 +299,10 @@ function ($item) { * * @param string $name * @param mixed $value + * + * @return void */ + #[\ReturnTypeWillChange] public function offsetSet($name, $value) { parent::offsetSet($name, $value); @@ -343,8 +341,8 @@ public function validate($options = 0) $messages = parent::validate($options); $valueType = $this->getValueType(); $values = $this->getParts(); - try { - foreach ($values as $value) { + foreach ($values as $value) { + try { switch ($valueType) { case 'DATE': DateTimeParser::parseDate($value); @@ -353,13 +351,14 @@ public function validate($options = 0) DateTimeParser::parseDateTime($value); break; } + } catch (InvalidDataException $e) { + $messages[] = [ + 'level' => 3, + 'message' => 'The supplied value ('.$value.') is not a correct '.$valueType, + 'node' => $this, + ]; + break; } - } catch (InvalidDataException $e) { - $messages[] = [ - 'level' => 3, - 'message' => 'The supplied value ('.$value.') is not a correct '.$valueType, - 'node' => $this, - ]; } return $messages; diff --git a/lib/Property/ICalendar/Duration.php b/lib/Property/ICalendar/Duration.php index 87f008160..e18fe191e 100644 --- a/lib/Property/ICalendar/Duration.php +++ b/lib/Property/ICalendar/Duration.php @@ -22,7 +22,7 @@ class Duration extends Property * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ public $delimiter = ','; diff --git a/lib/Property/ICalendar/Period.php b/lib/Property/ICalendar/Period.php index 17bfa5c5c..5b93bd01c 100644 --- a/lib/Property/ICalendar/Period.php +++ b/lib/Property/ICalendar/Period.php @@ -23,7 +23,7 @@ class Period extends Property * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ public $delimiter = ','; @@ -67,8 +67,6 @@ public function getValueType() * Sets the json value, as it would appear in a jCard or jCal object. * * The value must always be an array. - * - * @param array $value */ public function setJsonValue(array $value) { @@ -81,6 +79,10 @@ function ($item) { parent::setJsonValue($value); } + function appendUtc($strDate) { + return strpos($strDate, 'Z') === false ? '' : 'Z'; + } + /** * Returns the value, in the format it should be encoded for json. * @@ -94,19 +96,19 @@ public function getJsonValue() foreach ($this->getParts() as $item) { list($start, $end) = explode('/', $item, 2); - $start = DateTimeParser::parseDateTime($start); - // This is a duration value. - if ('P' === $end[0]) { + $startDt = DateTimeParser::parseDateTime($start)->format('Y-m-d\\TH:i:s') . $this->appendUtc($start); + + if ($end[0] === 'P') { $return[] = [ - $start->format('Y-m-d\\TH:i:s'), - $end, + $startDt, + $end ]; } else { - $end = DateTimeParser::parseDateTime($end); + $endDt = DateTimeParser::parseDateTime($end)->format('Y-m-d\\TH:i:s') . $this->appendUtc($end); $return[] = [ - $start->format('Y-m-d\\TH:i:s'), - $end->format('Y-m-d\\TH:i:s'), + $startDt, + $endDt ]; } } diff --git a/lib/Property/ICalendar/Recur.php b/lib/Property/ICalendar/Recur.php index baeda781e..cd3d7a5e4 100644 --- a/lib/Property/ICalendar/Recur.php +++ b/lib/Property/ICalendar/Recur.php @@ -2,6 +2,7 @@ namespace Sabre\VObject\Property\ICalendar; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Property; use Sabre\Xml; @@ -88,8 +89,6 @@ public function getValue() /** * Sets a multi-valued property. - * - * @param array $parts */ public function setParts(array $parts) { @@ -200,7 +199,14 @@ public static function stringToArray($value) if (empty($part)) { continue; } - list($partName, $partValue) = explode('=', $part); + + $parts = explode('=', $part); + + if (2 !== count($parts)) { + throw new InvalidDataException('The supplied iCalendar RRULE part is incorrect: '.$part); + } + + list($partName, $partValue) = $parts; // The value itself had multiple values.. if (false !== strpos($partValue, ',')) { diff --git a/lib/Property/IntegerValue.php b/lib/Property/IntegerValue.php index ddd71d731..3ae775214 100644 --- a/lib/Property/IntegerValue.php +++ b/lib/Property/IntegerValue.php @@ -2,14 +2,13 @@ namespace Sabre\VObject\Property; -use - Sabre\VObject\Property; +use Sabre\VObject\Property; /** * Integer property. * * This object represents INTEGER values. These are always a single integer. - * They may be preceeded by either + or -. + * They may be preceded by either + or -. * * @copyright Copyright (C) fruux GmbH (https://fruux.com/) * @author Evert Pot (http://evertpot.com/) @@ -68,8 +67,6 @@ public function getJsonValue() /** * Hydrate data from a XML subtree, as it would appear in a xCard or xCal * object. - * - * @param array $value */ public function setXmlValue(array $value) { diff --git a/lib/Property/Text.php b/lib/Property/Text.php index 23c945551..16d2c07f4 100644 --- a/lib/Property/Text.php +++ b/lib/Property/Text.php @@ -111,7 +111,7 @@ public function setQuotedPrintableValue($val) // that. // // We also don't have to unescape \\, so all we need to look for is a ; - // that's not preceeded with a \. + // that's not preceded with a \. $regex = '# (?setValue($matches); @@ -136,16 +136,18 @@ public function getRawMimeDirValue() } foreach ($item as &$subItem) { - $subItem = strtr( - $subItem, - [ - '\\' => '\\\\', - ';' => '\;', - ',' => '\,', - "\n" => '\n', - "\r" => '', - ] - ); + if (!is_null($subItem)) { + $subItem = strtr( + $subItem, + [ + '\\' => '\\\\', + ';' => '\;', + ',' => '\,', + "\n" => '\n', + "\r" => '', + ] + ); + } } $item = implode(',', $item); } diff --git a/lib/Property/Time.php b/lib/Property/Time.php index 7aeafc8d0..1b81609aa 100644 --- a/lib/Property/Time.php +++ b/lib/Property/Time.php @@ -19,9 +19,9 @@ class Time extends Text * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Returns the type of value. @@ -40,8 +40,6 @@ public function getValueType() * Sets the JSON value, as it would appear in a jCard or jCal object. * * The value must always be an array. - * - * @param array $value */ public function setJsonValue(array $value) { @@ -119,8 +117,6 @@ public function getJsonValue() /** * Hydrate data from a XML subtree, as it would appear in a xCard or xCal * object. - * - * @param array $value */ public function setXmlValue(array $value) { diff --git a/lib/Property/Uri.php b/lib/Property/Uri.php index 3449ba1f2..1ad1fb199 100644 --- a/lib/Property/Uri.php +++ b/lib/Property/Uri.php @@ -20,9 +20,9 @@ class Uri extends Text * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Returns the type of value. @@ -72,7 +72,7 @@ public function setRawMimeDirValue($val) { // Normally we don't need to do any type of unescaping for these // properties, however.. we've noticed that Google Contacts - // specifically escapes the colon (:) with a blackslash. While I have + // specifically escapes the colon (:) with a backslash. While I have // no clue why they thought that was a good idea, I'm unescaping it // anyway. // diff --git a/lib/Property/UtcOffset.php b/lib/Property/UtcOffset.php index 732239e23..04b88447f 100644 --- a/lib/Property/UtcOffset.php +++ b/lib/Property/UtcOffset.php @@ -17,9 +17,9 @@ class UtcOffset extends Text * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Returns the type of value. @@ -38,8 +38,6 @@ public function getValueType() * Sets the JSON value, as it would appear in a jCard or jCal object. * * The value must always be an array. - * - * @param array $value */ public function setJsonValue(array $value) { diff --git a/lib/Property/VCard/Date.php b/lib/Property/VCard/Date.php index a018ccbb8..fc679d572 100644 --- a/lib/Property/VCard/Date.php +++ b/lib/Property/VCard/Date.php @@ -28,8 +28,6 @@ public function getValueType() /** * Sets the property as a DateTime object. - * - * @param \DateTimeInterface $dt */ public function setDateTime(\DateTimeInterface $dt) { diff --git a/lib/Property/VCard/DateAndOrTime.php b/lib/Property/VCard/DateAndOrTime.php index bf923e49d..7bf79c48c 100644 --- a/lib/Property/VCard/DateAndOrTime.php +++ b/lib/Property/VCard/DateAndOrTime.php @@ -24,9 +24,9 @@ class DateAndOrTime extends Property /** * Field separator. * - * @var null|string + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Returns the type of value. @@ -45,8 +45,6 @@ public function getValueType() * Sets a multi-valued property. * * You may also specify DateTimeInterface objects here. - * - * @param array $parts */ public function setParts(array $parts) { @@ -80,8 +78,6 @@ public function setValue($value) /** * Sets the property as a DateTime object. - * - * @param DateTimeInterface $dt */ public function setDateTime(DateTimeInterface $dt) { diff --git a/lib/Property/VCard/LanguageTag.php b/lib/Property/VCard/LanguageTag.php index 697273989..318ea0231 100644 --- a/lib/Property/VCard/LanguageTag.php +++ b/lib/Property/VCard/LanguageTag.php @@ -2,8 +2,7 @@ namespace Sabre\VObject\Property\VCard; -use - Sabre\VObject\Property; +use Sabre\VObject\Property; /** * LanguageTag property. diff --git a/lib/Property/VCard/PhoneNumber.php b/lib/Property/VCard/PhoneNumber.php new file mode 100644 index 000000000..b714ffd03 --- /dev/null +++ b/lib/Property/VCard/PhoneNumber.php @@ -0,0 +1,30 @@ + + */ +class PhoneNumber extends Property\Text +{ + protected $structuredValues = []; + + /** + * Returns the type of value. + * + * This corresponds to the VALUE= parameter. Every property also has a + * 'default' valueType. + * + * @return string + */ + public function getValueType() + { + return 'PHONE-NUMBER'; + } +} diff --git a/lib/Property/VCard/TimeStamp.php b/lib/Property/VCard/TimeStamp.php index fccf2d600..da6ea3d44 100644 --- a/lib/Property/VCard/TimeStamp.php +++ b/lib/Property/VCard/TimeStamp.php @@ -21,9 +21,9 @@ class TimeStamp extends Text * In case this is a multi-value property. This string will be used as a * delimiter. * - * @var string|null + * @var string */ - public $delimiter = null; + public $delimiter = ''; /** * Returns the type of value. diff --git a/lib/Reader.php b/lib/Reader.php index 3999c66b1..055d546a5 100644 --- a/lib/Reader.php +++ b/lib/Reader.php @@ -55,7 +55,7 @@ public static function read($data, $options = 0, $charset = 'UTF-8') * The options argument is a bitfield. Pass any of the OPTIONS constant to * alter the parsers' behaviour. * - * You can either a string, a readable stream, or an array for it's input. + * You can either a string, a readable stream, or an array for its input. * Specifying the array is useful if json_decode was already called on the * input. * diff --git a/lib/Recur/EventIterator.php b/lib/Recur/EventIterator.php index 2563d4562..212c147d5 100644 --- a/lib/Recur/EventIterator.php +++ b/lib/Recur/EventIterator.php @@ -83,7 +83,7 @@ class EventIterator implements \Iterator * 2. You can pass an array of VEVENTs (all UIDS should match). * 3. You can pass a single VEVENT component. * - * Only the second method is recomended. The other 1 and 3 will be removed + * Only the second method is recommended. The other 1 and 3 will be removed * at some point in the future. * * The $uid parameter is only required for the first method. @@ -93,7 +93,7 @@ class EventIterator implements \Iterator * @param DateTimeZone $timeZone reference timezone for floating dates and * times */ - public function __construct($input, $uid = null, DateTimeZone $timeZone = null) + public function __construct($input, $uid = null, ?DateTimeZone $timeZone = null) { if (is_null($timeZone)) { $timeZone = new DateTimeZone('UTC'); @@ -168,8 +168,12 @@ public function __construct($input, $uid = null, DateTimeZone $timeZone = null) } if (isset($this->masterEvent->RDATE)) { + $rdateValues = []; + foreach ($this->masterEvent->RDATE as $rdate) { + $rdateValues = array_merge($rdateValues, $rdate->getParts()); + } $this->recurIterator = new RDateIterator( - $this->masterEvent->RDATE->getParts(), + $rdateValues, $this->startDate ); } elseif (isset($this->masterEvent->RRULE)) { @@ -198,6 +202,7 @@ public function __construct($input, $uid = null, DateTimeZone $timeZone = null) * * @return DateTimeImmutable */ + #[\ReturnTypeWillChange] public function current() { if ($this->currentDate) { @@ -229,15 +234,19 @@ public function getDtEnd() if (!$this->valid()) { return; } - $end = clone $this->currentDate; + if ($this->currentOverriddenEvent && $this->currentOverriddenEvent->DTEND) { + return $this->currentOverriddenEvent->DTEND->getDateTime($this->timeZone); + } else { + $end = clone $this->currentDate; - return $end->modify('+'.$this->eventDuration.' seconds'); + return $end->modify('+'.$this->eventDuration.' seconds'); + } } /** * Returns a VEVENT for the current iterations of the event. * - * This VEVENT will have a recurrence id, and it's DTSTART and DTEND + * This VEVENT will have a recurrence id, and its DTSTART and DTEND * altered. * * @return VEvent @@ -281,6 +290,7 @@ public function getEventObject() * * @return int */ + #[\ReturnTypeWillChange] public function key() { // The counter is always 1 ahead. @@ -293,6 +303,7 @@ public function key() * * @return bool */ + #[\ReturnTypeWillChange] public function valid() { if ($this->counter > Settings::$maxRecurrences && -1 !== Settings::$maxRecurrences) { @@ -304,7 +315,10 @@ public function valid() /** * Sets the iterator back to the starting point. + * + * @return void */ + #[\ReturnTypeWillChange] public function rewind() { $this->recurIterator->rewind(); @@ -327,7 +341,10 @@ public function rewind() /** * Advances the iterator with one step. + * + * @return void */ + #[\ReturnTypeWillChange] public function next() { $this->currentOverriddenEvent = null; @@ -380,8 +397,6 @@ public function next() /** * Quickly jump to a date in the future. - * - * @param DateTimeInterface $dateTime */ public function fastForward(DateTimeInterface $dateTime) { diff --git a/lib/Recur/NoInstancesException.php b/lib/Recur/NoInstancesException.php index b55af567d..348c02306 100644 --- a/lib/Recur/NoInstancesException.php +++ b/lib/Recur/NoInstancesException.php @@ -7,7 +7,7 @@ /** * This exception gets thrown when a recurrence iterator produces 0 instances. * - * This may happen when every occurence in a rrule is also in EXDATE. + * This may happen when every occurrence in a rrule is also in EXDATE. * * @copyright Copyright (C) fruux GmbH (https://fruux.com/) * @author Evert Pot (http://evertpot.com/) diff --git a/lib/Recur/RDateIterator.php b/lib/Recur/RDateIterator.php index 013694b95..5d56657fa 100644 --- a/lib/Recur/RDateIterator.php +++ b/lib/Recur/RDateIterator.php @@ -24,8 +24,7 @@ class RDateIterator implements Iterator /** * Creates the Iterator. * - * @param string|array $rrule - * @param DateTimeInterface $start + * @param string|array $rrule */ public function __construct($rrule, DateTimeInterface $start) { @@ -36,6 +35,7 @@ public function __construct($rrule, DateTimeInterface $start) /* Implementation of the Iterator interface {{{ */ + #[\ReturnTypeWillChange] public function current() { if (!$this->valid()) { @@ -50,6 +50,7 @@ public function current() * * @return int */ + #[\ReturnTypeWillChange] public function key() { return $this->counter; @@ -61,6 +62,7 @@ public function key() * * @return bool */ + #[\ReturnTypeWillChange] public function valid() { return $this->counter <= count($this->dates); @@ -68,7 +70,10 @@ public function valid() /** * Resets the iterator. + * + * @return void */ + #[\ReturnTypeWillChange] public function rewind() { $this->currentDate = clone $this->startDate; @@ -77,7 +82,10 @@ public function rewind() /** * Goes on to the next iteration. + * + * @return void */ + #[\ReturnTypeWillChange] public function next() { ++$this->counter; @@ -107,8 +115,6 @@ public function isInfinite() /** * This method allows you to quickly go to the next occurrence after the * specified date. - * - * @param DateTimeInterface $dt */ public function fastForward(DateTimeInterface $dt) { diff --git a/lib/Recur/RRuleIterator.php b/lib/Recur/RRuleIterator.php index 554507f19..09729fbb6 100644 --- a/lib/Recur/RRuleIterator.php +++ b/lib/Recur/RRuleIterator.php @@ -24,21 +24,53 @@ */ class RRuleIterator implements Iterator { + /** + * Constant denoting the upper limit on how long into the future + * we want to iterate. The value is a unix timestamp and currently + * corresponds to the datetime 9999-12-31 11:59:59 UTC. + */ + const dateUpperLimit = 253402300799; + /** * Creates the Iterator. * - * @param string|array $rrule - * @param DateTimeInterface $start + * @param string|array $rrule */ public function __construct($rrule, DateTimeInterface $start) { $this->startDate = $start; $this->parseRRule($rrule); $this->currentDate = clone $this->startDate; + $this->skipInvalidStart(); + } + + /** + * For YEARLY frequency with BYMONTH, check if DTSTART matches the rules. + * If not, advance to the first valid occurrence without incrementing the counter. + * See: https://github.com/linagora/esn-sabre/issues/50 + */ + private function skipInvalidStart() + { + if ('yearly' === $this->frequency && $this->byMonth) { + $currentMonth = (int) $this->currentDate->format('n'); + if (!in_array($currentMonth, $this->byMonth)) { + // DTSTART month is not in BYMONTH, advance to first valid occurrence + $this->nextYearly(); + } elseif ($this->byMonthDay || $this->byDay) { + // Month is valid, but check if day is valid + $currentDay = (int) $this->currentDate->format('j'); + $validDays = $this->getMonthlyOccurrences(); + if (!in_array($currentDay, $validDays)) { + // Day is not valid, advance to first valid occurrence + $this->nextYearly(); + } + } + } } /* Implementation of the Iterator interface {{{ */ + #[\ReturnTypeWillChange] public function current() { if (!$this->valid()) { @@ -53,6 +85,7 @@ public function current() * * @return int */ + #[\ReturnTypeWillChange] public function key() { return $this->counter; @@ -65,8 +98,12 @@ public function key() * * @return bool */ + #[\ReturnTypeWillChange] public function valid() { + if (null === $this->currentDate) { + return false; + } if (!is_null($this->count)) { return $this->counter < $this->count; } @@ -76,16 +113,23 @@ public function valid() /** * Resets the iterator. + * + * @return void */ + #[\ReturnTypeWillChange] public function rewind() { $this->currentDate = clone $this->startDate; $this->counter = 0; + $this->skipInvalidStart(); } /** * Goes on to the next iteration. + * + * @return void */ + #[\ReturnTypeWillChange] public function next() { // Otherwise, we find the next event in the normal RRULE @@ -129,8 +173,6 @@ public function isInfinite() /** * This method allows you to quickly go to the next occurrence after the * specified date. - * - * @param DateTimeInterface $dt */ public function fastForward(DateTimeInterface $dt) { @@ -156,6 +198,14 @@ public function fastForward(DateTimeInterface $dt) */ protected $currentDate; + /** + * The number of hours that the next occurrence of an event + * jumped forward, usually because summer time started and + * the requested time-of-day like 0230 did not exist on that + * day. And so the event was scheduled 1 hour later at 0330. + */ + protected $hourJump = 0; + /** * Frequency is one of: secondly, minutely, hourly, daily, weekly, monthly, * yearly. @@ -229,7 +279,7 @@ public function fastForward(DateTimeInterface $dt) * * This is an array of weekdays * - * This may also be preceeded by a positive or negative integer. If present, + * This may also be preceded by a positive or negative integer. If present, * this indicates the nth occurrence of a specific day within the monthly or * yearly rrule. For instance, -2TU indicates the second-last tuesday of * the month, or year. @@ -303,12 +353,65 @@ public function fastForward(DateTimeInterface $dt) /* Functions that advance the iterator {{{ */ + /** + * Gets the original start time of the RRULE. + * + * The value is formatted as a string with 24-hour:minute:second + */ + protected function startTime(): string + { + return $this->startDate->format('H:i:s'); + } + + /** + * Advances currentDate by the interval. + * The time is set from the original startDate. + * If the recurrence is on a day when summer time started, then the + * time on that day may have jumped forward, for example, from 0230 to 0330. + * Using the original time means that the next recurrence will be calculated + * based on the original start time and the day/week/month/year interval. + * So the start time of the next occurrence can correctly revert to 0230. + */ + protected function advanceTheDate(string $interval): void + { + $this->currentDate = $this->currentDate->modify($interval.' '.$this->startTime()); + } + + /** + * Does the processing for adjusting the time of multi-hourly events when summer time starts. + */ + protected function adjustForTimeJumpsOfHourlyEvent(DateTimeInterface $previousEventDateTime): void + { + if (0 === $this->hourJump) { + // Remember if the clock time jumped forward on the next occurrence. + // That happens if the next event time is on a day when summer time starts + // and the event time is in the non-existent hour of the day. + // For example, an event that normally starts at 02:30 will + // have to start at 03:30 on that day. + // If the interval is just 1 hour, then there is no "jumping back" to do. + // The events that day will happen, for example, at 0030 0130 0330 0430 0530... + if ($this->interval > 1) { + $expectedHourOfNextDate = ((int) $previousEventDateTime->format('G') + $this->interval) % 24; + $actualHourOfNextDate = (int) $this->currentDate->format('G'); + $this->hourJump = $actualHourOfNextDate - $expectedHourOfNextDate; + } + } else { + // The hour "jumped" for the previous occurrence, to avoid the non-existent time. + // currentDate got set ahead by (usually) 1 hour on that day. + // Adjust it back for this next occurrence. + $this->currentDate = $this->currentDate->sub(new \DateInterval('PT'.$this->hourJump.'H')); + $this->hourJump = 0; + } + } + /** * Does the processing for advancing the iterator for hourly frequency. */ protected function nextHourly() { + $previousEventDateTime = clone $this->currentDate; $this->currentDate = $this->currentDate->modify('+'.$this->interval.' hours'); + $this->adjustForTimeJumpsOfHourlyEvent($previousEventDateTime); } /** @@ -317,19 +420,22 @@ protected function nextHourly() protected function nextDaily() { if (!$this->byHour && !$this->byDay) { - $this->currentDate = $this->currentDate->modify('+'.$this->interval.' days'); + $this->advanceTheDate('+'.$this->interval.' days'); return; } + $recurrenceHours = []; if (!empty($this->byHour)) { $recurrenceHours = $this->getHours(); } + $recurrenceDays = []; if (!empty($this->byDay)) { $recurrenceDays = $this->getDays(); } + $recurrenceMonths = []; if (!empty($this->byMonth)) { $recurrenceMonths = $this->getMonths(); } @@ -338,7 +444,7 @@ protected function nextDaily() if ($this->byHour) { if ('23' == $this->currentDate->format('G')) { // to obey the interval rule - $this->currentDate = $this->currentDate->modify('+'.$this->interval - 1 .' days'); + $this->currentDate = $this->currentDate->modify('+'.($this->interval - 1).' days'); } $this->currentDate = $this->currentDate->modify('+1 hours'); @@ -354,6 +460,12 @@ protected function nextDaily() // Current hour of the day $currentHour = $this->currentDate->format('G'); + + if ($this->currentDate->getTimestamp() > self::dateUpperLimit) { + $this->currentDate = null; + + return; + } } while ( ($this->byDay && !in_array($currentDay, $recurrenceDays)) || ($this->byHour && !in_array($currentHour, $recurrenceHours)) || @@ -367,15 +479,17 @@ protected function nextDaily() protected function nextWeekly() { if (!$this->byHour && !$this->byDay) { - $this->currentDate = $this->currentDate->modify('+'.$this->interval.' weeks'); + $this->advanceTheDate('+'.$this->interval.' weeks'); return; } + $recurrenceHours = []; if ($this->byHour) { $recurrenceHours = $this->getHours(); } + $recurrenceDays = []; if ($this->byDay) { $recurrenceDays = $this->getDays(); } @@ -387,7 +501,7 @@ protected function nextWeekly() if ($this->byHour) { $this->currentDate = $this->currentDate->modify('+1 hours'); } else { - $this->currentDate = $this->currentDate->modify('+1 days'); + $this->advanceTheDate('+1 days'); } // Current day of the week @@ -398,7 +512,7 @@ protected function nextWeekly() // We need to roll over to the next week if ($currentDay === $firstDay && (!$this->byHour || '0' == $currentHour)) { - $this->currentDate = $this->currentDate->modify('+'.$this->interval - 1 .' weeks'); + $this->currentDate = $this->currentDate->modify('+'.($this->interval - 1).' weeks'); // We need to go to the first day of this week, but only if we // are not already on this first day of this week. @@ -422,13 +536,13 @@ protected function nextMonthly() // occur to the next month. We Must skip these invalid // entries. if ($currentDayOfMonth < 29) { - $this->currentDate = $this->currentDate->modify('+'.$this->interval.' months'); + $this->advanceTheDate('+'.$this->interval.' months'); } else { $increase = 0; do { ++$increase; $tempDate = clone $this->currentDate; - $tempDate = $tempDate->modify('+ '.($this->interval * $increase).' months'); + $tempDate = $tempDate->modify('+ '.($this->interval * $increase).' months '.$this->startTime()); } while ($tempDate->format('j') != $currentDayOfMonth); $this->currentDate = $tempDate; } @@ -436,6 +550,7 @@ protected function nextMonthly() return; } + $occurrence = -1; while (true) { $occurrences = $this->getMonthlyOccurrences(); @@ -461,13 +576,32 @@ protected function nextMonthly() // This goes to 0 because we need to start counting at the // beginning. $currentDayOfMonth = 0; + + // For some reason the "until" parameter was not being used here, + // that's why the workaround of the 10000 year bug was needed at all + // let's stop it before the "until" parameter date + if ($this->until && $this->currentDate->getTimestamp() >= $this->until->getTimestamp()) { + return; + } + + // To prevent running this forever (better: until we hit the max date of DateTimeImmutable) we simply + // stop at 9999-12-31. Looks like the year 10000 problem is not solved in php .... + if ($this->currentDate->getTimestamp() > self::dateUpperLimit) { + $this->currentDate = null; + + return; + } } + // Set the currentDate to the year and month that we are in, and the day of the month that we have selected. + // That day could be a day when summer time starts, and if the time of the event is, for example, 0230, + // then 0230 will not be a valid time on that day. So always apply the start time from the original startDate. + // The "modify" method will set the time forward to 0330, for example, if needed. $this->currentDate = $this->currentDate->setDate( (int) $this->currentDate->format('Y'), (int) $this->currentDate->format('n'), (int) $occurrence - ); + )->modify($this->startTime()); } /** @@ -522,7 +656,7 @@ protected function nextYearly() foreach ($this->byWeekNo as $byWeekNo) { foreach ($dayOffsets as $dayOffset) { $date = clone $this->currentDate; - $date->setISODate($currentYear, $byWeekNo, $dayOffset); + $date = $date->setISODate($currentYear, $byWeekNo, $dayOffset); if ($date > $this->currentDate) { $checkDates[] = $date; @@ -559,11 +693,12 @@ protected function nextYearly() // loop through all YearDay and Days to check all the combinations foreach ($this->byYearDay as $byYearDay) { $date = clone $this->currentDate; - $date = $date->setDate($currentYear, 1, 1); if ($byYearDay > 0) { - $date = $date->add(new \DateInterval('P'.$byYearDay.'D')); + $date = $date->setDate($currentYear, 1, 1); + $date = $date->add(new \DateInterval('P'.($byYearDay - 1).'D')); } else { - $date = $date->sub(new \DateInterval('P'.abs($byYearDay).'D')); + $date = $date->setDate($currentYear, 12, 31); + $date = $date->sub(new \DateInterval('P'.abs($byYearDay + 1).'D')); } if ($date > $this->currentDate && in_array($date->format('N'), $dayOffsets)) { @@ -583,7 +718,7 @@ protected function nextYearly() } // The easiest form - $this->currentDate = $this->currentDate->modify('+'.$this->interval.' years'); + $this->advanceTheDate('+'.$this->interval.' years'); return; } @@ -597,6 +732,7 @@ protected function nextYearly() // If we got a byDay or getMonthDay filter, we must first expand // further. if ($this->byDay || $this->byMonthDay) { + $occurrence = -1; while (true) { $occurrences = $this->getMonthlyOccurrences(); @@ -606,7 +742,11 @@ protected function nextYearly() // If we advanced to the next month or year, the first // occurrence is always correct. if ($occurrence > $currentDayOfMonth || $advancedToNewMonth) { - break 2; + // only consider byMonth matches, + // otherwise, we don't follow RRule correctly + if (in_array($currentMonth, $this->byMonth)) { + break 2; + } } } @@ -627,6 +767,14 @@ protected function nextYearly() (int) $currentMonth, (int) $currentDayOfMonth ); + + // To prevent running this forever (better: until we hit the max date of DateTimeImmutable) we simply + // stop at 9999-12-31. Looks like the year 10000 problem is not solved in php .... + if ($this->currentDate->getTimestamp() > self::dateUpperLimit) { + $this->currentDate = null; + + return; + } } // If we made it here, it means we got a valid occurrence @@ -634,7 +782,7 @@ protected function nextYearly() (int) $currentYear, (int) $currentMonth, (int) $occurrence - ); + )->modify($this->startTime()); return; } else { @@ -651,7 +799,7 @@ protected function nextYearly() (int) $currentYear, (int) $currentMonth, (int) $currentDayOfMonth - ); + )->modify($this->startTime()); return; } @@ -702,7 +850,6 @@ protected function parseRRule($rrule) break; case 'INTERVAL': - case 'COUNT': $val = (int) $value; if ($val < 1) { @@ -760,7 +907,7 @@ protected function parseRRule($rrule) $this->byMonth = (array) $value; foreach ($this->byMonth as $byMonth) { if (!is_numeric($byMonth) || (int) $byMonth < 1 || (int) $byMonth > 12) { - throw new InvalidDataException('BYMONTH in RRULE must have value(s) betweeen 1 and 12!'); + throw new InvalidDataException('BYMONTH in RRULE must have value(s) between 1 and 12!'); } } break; @@ -862,7 +1009,7 @@ protected function getMonthlyOccurrences() foreach ($this->byMonthDay as $monthDay) { // Removing values that are out of range for this month if ($monthDay > $startDate->format('t') || - $monthDay < 0 - $startDate->format('t')) { + $monthDay < 0 - $startDate->format('t')) { continue; } if ($monthDay > 0) { @@ -937,7 +1084,7 @@ protected function getDays() { $recurrenceDays = []; foreach ($this->byDay as $byDay) { - // The day may be preceeded with a positive (+n) or + // The day may be preceded with a positive (+n) or // negative (-n) integer. However, this does not make // sense in 'weekly' so we ignore it here. $recurrenceDays[] = $this->dayMap[substr($byDay, -2)]; diff --git a/lib/Settings.php b/lib/Settings.php index afc586b0c..b0bb80a82 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -46,7 +46,7 @@ class Settings * specific events that recur many, many times, potentially DDOSing the * server. * - * The default (3500) allows creation of a dialy event that goes on for 10 + * The default (3500) allows creation of a daily event that goes on for 10 * years, which is hopefully long enough for most. * * Set this value to -1 to disable this control altogether. diff --git a/lib/Splitter/ICalendar.php b/lib/Splitter/ICalendar.php index 79f7207fd..d42566194 100644 --- a/lib/Splitter/ICalendar.php +++ b/lib/Splitter/ICalendar.php @@ -38,7 +38,7 @@ class ICalendar implements SplitterInterface /** * Constructor. * - * The splitter should receive an readable file stream as it's input. + * The splitter should receive an readable file stream as its input. * * @param resource $input * @param int $options parser options, see the OPTIONS constants diff --git a/lib/Splitter/SplitterInterface.php b/lib/Splitter/SplitterInterface.php index a2c43d662..c845ac5fc 100644 --- a/lib/Splitter/SplitterInterface.php +++ b/lib/Splitter/SplitterInterface.php @@ -20,7 +20,7 @@ interface SplitterInterface /** * Constructor. * - * The splitter should receive an readable file stream as it's input. + * The splitter should receive an readable file stream as its input. * * @param resource $input */ diff --git a/lib/Splitter/VCard.php b/lib/Splitter/VCard.php index 02509c6c3..a20f5c2c1 100644 --- a/lib/Splitter/VCard.php +++ b/lib/Splitter/VCard.php @@ -38,7 +38,7 @@ class VCard implements SplitterInterface /** * Constructor. * - * The splitter should receive an readable file stream as it's input. + * The splitter should receive an readable file stream as its input. * * @param resource $input * @param int $options parser options, see the OPTIONS constants diff --git a/lib/StringUtil.php b/lib/StringUtil.php index 2333d6ab9..b04539e4a 100644 --- a/lib/StringUtil.php +++ b/lib/StringUtil.php @@ -40,23 +40,11 @@ public static function isUTF8($str) */ public static function convertToUTF8($str) { - $encoding = mb_detect_encoding($str, ['UTF-8', 'ISO-8859-1', 'WINDOWS-1252'], true); - - switch ($encoding) { - case 'ISO-8859-1': - $newStr = utf8_encode($str); - break; - /* Unreachable code. Not sure yet how we can improve this - * situation. - case 'WINDOWS-1252' : - $newStr = iconv('cp1252', 'UTF-8', $str); - break; - */ - default: - $newStr = $str; + if (!mb_check_encoding($str, 'UTF-8') && mb_check_encoding($str, 'ISO-8859-1')) { + $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1'); } // Removing any control characters - return preg_replace('%(?:[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F])%', '', $newStr); + return preg_replace('%(?:[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F])%', '', $str); } } diff --git a/lib/TimeZoneUtil.php b/lib/TimeZoneUtil.php index 5b1a775c2..0d77e71ed 100644 --- a/lib/TimeZoneUtil.php +++ b/lib/TimeZoneUtil.php @@ -2,6 +2,16 @@ namespace Sabre\VObject; +use DateTimeZone; +use InvalidArgumentException; +use Sabre\VObject\TimezoneGuesser\FindFromOffset; +use Sabre\VObject\TimezoneGuesser\FindFromTimezoneIdentifier; +use Sabre\VObject\TimezoneGuesser\FindFromTimezoneMap; +use Sabre\VObject\TimezoneGuesser\GuessFromLicEntry; +use Sabre\VObject\TimezoneGuesser\GuessFromMsTzId; +use Sabre\VObject\TimezoneGuesser\TimezoneFinder; +use Sabre\VObject\TimezoneGuesser\TimezoneGuesser; + /** * Time zone name translation. * @@ -14,17 +24,136 @@ */ class TimeZoneUtil { + /** @var self */ + private static $instance = null; + + /** @var TimezoneGuesser[] */ + private $timezoneGuessers = []; + + /** @var TimezoneFinder[] */ + private $timezoneFinders = []; + + private function __construct() + { + $this->addGuesser('lic', new GuessFromLicEntry()); + $this->addGuesser('msTzId', new GuessFromMsTzId()); + $this->addFinder('tzid', new FindFromTimezoneIdentifier()); + $this->addFinder('tzmap', new FindFromTimezoneMap()); + $this->addFinder('offset', new FindFromOffset()); + } + + private static function getInstance(): self + { + if (null === self::$instance) { + self::$instance = new self(); + } + + return self::$instance; + } + + private function addGuesser(string $key, TimezoneGuesser $guesser): void + { + $this->timezoneGuessers[$key] = $guesser; + } + + private function addFinder(string $key, TimezoneFinder $finder): void + { + $this->timezoneFinders[$key] = $finder; + } + + /** + * This method will try to find out the correct timezone for an iCalendar + * date-time value. + * + * You must pass the contents of the TZID parameter, as well as the full + * calendar. + * + * If the lookup fails, this method will return the default PHP timezone + * (as configured using date_default_timezone_set, or the date.timezone ini + * setting). + * + * Alternatively, if $failIfUncertain is set to true, it will throw an + * exception if we cannot accurately determine the timezone. + */ + private function findTimeZone(string $tzid, ?Component $vcalendar = null, bool $failIfUncertain = false): DateTimeZone + { + foreach ($this->timezoneFinders as $timezoneFinder) { + $timezone = $timezoneFinder->find($tzid, $failIfUncertain); + if (!$timezone instanceof DateTimeZone) { + continue; + } + + return $timezone; + } + + if ($vcalendar) { + // If that didn't work, we will scan VTIMEZONE objects + foreach ($vcalendar->select('VTIMEZONE') as $vtimezone) { + if ((string) $vtimezone->TZID === $tzid) { + foreach ($this->timezoneGuessers as $timezoneGuesser) { + $timezone = $timezoneGuesser->guess($vtimezone, $failIfUncertain); + if (!$timezone instanceof DateTimeZone) { + continue; + } + + return $timezone; + } + } + } + } + + if ($failIfUncertain) { + throw new InvalidArgumentException('We were unable to determine the correct PHP timezone for tzid: '.$tzid); + } + + // If we got all the way here, we default to whatever has been set as the PHP default timezone. + return new DateTimeZone(date_default_timezone_get()); + } + + public static function addTimezoneGuesser(string $key, TimezoneGuesser $guesser): void + { + self::getInstance()->addGuesser($key, $guesser); + } + + public static function addTimezoneFinder(string $key, TimezoneFinder $finder): void + { + self::getInstance()->addFinder($key, $finder); + } + + /** + * @param string $tzid + * @param false $failIfUncertain + * + * @return DateTimeZone + */ + public static function getTimeZone($tzid, ?Component $vcalendar = null, $failIfUncertain = false) + { + return self::getInstance()->findTimeZone($tzid, $vcalendar, $failIfUncertain); + } + + public static function clean(): void + { + self::$instance = null; + } + + // Keeping things for backwards compatibility + /** + * @var array|null + * + * @deprecated + */ public static $map = null; /** * List of microsoft exchange timezone ids. * * Source: http://msdn.microsoft.com/en-us/library/aa563018(loband).aspx + * + * @deprecated */ public static $microsoftExchangeMap = [ 0 => 'UTC', 31 => 'Africa/Casablanca', - // Insanely, id #2 is used for both Europe/Lisbon, and Europe/Sarajevo. // I'm not even kidding.. We handle this special case in the // getTimeZone method. @@ -103,135 +232,11 @@ class TimeZoneUtil 39 => 'Pacific/Kwajalein', ]; - /** - * This method will try to find out the correct timezone for an iCalendar - * date-time value. - * - * You must pass the contents of the TZID parameter, as well as the full - * calendar. - * - * If the lookup fails, this method will return the default PHP timezone - * (as configured using date_default_timezone_set, or the date.timezone ini - * setting). - * - * Alternatively, if $failIfUncertain is set to true, it will throw an - * exception if we cannot accurately determine the timezone. - * - * @param string $tzid - * @param Sabre\VObject\Component $vcalendar - * - * @return \DateTimeZone - */ - public static function getTimeZone($tzid, Component $vcalendar = null, $failIfUncertain = false) - { - // First we will just see if the tzid is a support timezone identifier. - // - // The only exception is if the timezone starts with (. This is to - // handle cases where certain microsoft products generate timezone - // identifiers that for instance look like: - // - // (GMT+01.00) Sarajevo/Warsaw/Zagreb - // - // Since PHP 5.5.10, the first bit will be used as the timezone and - // this method will return just GMT+01:00. This is wrong, because it - // doesn't take DST into account. - if ('(' !== $tzid[0]) { - // PHP has a bug that logs PHP warnings even it shouldn't: - // https://bugs.php.net/bug.php?id=67881 - // - // That's why we're checking if we'll be able to successfull instantiate - // \DateTimeZone() before doing so. Otherwise we could simply instantiate - // and catch the exception. - $tzIdentifiers = \DateTimeZone::listIdentifiers(); - - try { - if ( - (in_array($tzid, $tzIdentifiers)) || - (preg_match('/^GMT(\+|-)([0-9]{4})$/', $tzid, $matches)) || - (in_array($tzid, self::getIdentifiersBC())) - ) { - return new \DateTimeZone($tzid); - } - } catch (\Exception $e) { - } - } - - self::loadTzMaps(); - - // Next, we check if the tzid is somewhere in our tzid map. - if (isset(self::$map[$tzid])) { - return new \DateTimeZone(self::$map[$tzid]); - } - - // Some Microsoft products prefix the offset first, so let's strip that off - // and see if it is our tzid map. We don't want to check for this first just - // in case there are overrides in our tzid map. - if (preg_match('/^\((UTC|GMT)(\+|\-)[\d]{2}\:[\d]{2}\) (.*)/', $tzid, $matches)) { - $tzidAlternate = $matches[3]; - if (isset(self::$map[$tzidAlternate])) { - return new \DateTimeZone(self::$map[$tzidAlternate]); - } - } - - // Maybe the author was hyper-lazy and just included an offset. We - // support it, but we aren't happy about it. - if (preg_match('/^GMT(\+|-)([0-9]{4})$/', $tzid, $matches)) { - // Note that the path in the source will never be taken from PHP 5.5.10 - // onwards. PHP 5.5.10 supports the "GMT+0100" style of format, so it - // already gets returned early in this function. Once we drop support - // for versions under PHP 5.5.10, this bit can be taken out of the - // source. - // @codeCoverageIgnoreStart - return new \DateTimeZone('Etc/GMT'.$matches[1].ltrim(substr($matches[2], 0, 2), '0')); - // @codeCoverageIgnoreEnd - } - - if ($vcalendar) { - // If that didn't work, we will scan VTIMEZONE objects - foreach ($vcalendar->select('VTIMEZONE') as $vtimezone) { - if ((string) $vtimezone->TZID === $tzid) { - // Some clients add 'X-LIC-LOCATION' with the olson name. - if (isset($vtimezone->{'X-LIC-LOCATION'})) { - $lic = (string) $vtimezone->{'X-LIC-LOCATION'}; - - // Libical generators may specify strings like - // "SystemV/EST5EDT". For those we must remove the - // SystemV part. - if ('SystemV/' === substr($lic, 0, 8)) { - $lic = substr($lic, 8); - } - - return self::getTimeZone($lic, null, $failIfUncertain); - } - // Microsoft may add a magic number, which we also have an - // answer for. - if (isset($vtimezone->{'X-MICROSOFT-CDO-TZID'})) { - $cdoId = (int) $vtimezone->{'X-MICROSOFT-CDO-TZID'}->getValue(); - - // 2 can mean both Europe/Lisbon and Europe/Sarajevo. - if (2 === $cdoId && false !== strpos((string) $vtimezone->TZID, 'Sarajevo')) { - return new \DateTimeZone('Europe/Sarajevo'); - } - - if (isset(self::$microsoftExchangeMap[$cdoId])) { - return new \DateTimeZone(self::$microsoftExchangeMap[$cdoId]); - } - } - } - } - } - - if ($failIfUncertain) { - throw new \InvalidArgumentException('We were unable to determine the correct PHP timezone for tzid: '.$tzid); - } - - // If we got all the way here, we default to UTC. - return new \DateTimeZone(date_default_timezone_get()); - } - /** * This method will load in all the tz mapping information, if it's not yet * done. + * + * @deprecated */ public static function loadTzMaps() { @@ -257,6 +262,8 @@ public static function loadTzMaps() * (See timezonedata/php-bc.php and timezonedata php-workaround.php) * * @return array + * + * @deprecated */ public static function getIdentifiersBC() { diff --git a/lib/TimezoneGuesser/FindFromOffset.php b/lib/TimezoneGuesser/FindFromOffset.php new file mode 100644 index 000000000..990ac9692 --- /dev/null +++ b/lib/TimezoneGuesser/FindFromOffset.php @@ -0,0 +1,31 @@ +getIdentifiersBC())) + ) { + return new DateTimeZone($tzid); + } + } catch (Exception $e) { + } + + return null; + } + + /** + * This method returns an array of timezone identifiers, that are supported + * by DateTimeZone(), but not returned by DateTimeZone::listIdentifiers(). + * + * We're not using DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC) because: + * - It's not supported by some PHP versions as well as HHVM. + * - It also returns identifiers, that are invalid values for new DateTimeZone() on some PHP versions. + * (See timezonedata/php-bc.php and timezonedata php-workaround.php) + * + * @return array + */ + private function getIdentifiersBC() + { + return include __DIR__.'/../timezonedata/php-bc.php'; + } +} diff --git a/lib/TimezoneGuesser/FindFromTimezoneMap.php b/lib/TimezoneGuesser/FindFromTimezoneMap.php new file mode 100644 index 000000000..799283e01 --- /dev/null +++ b/lib/TimezoneGuesser/FindFromTimezoneMap.php @@ -0,0 +1,89 @@ +hasTzInMap($tzid)) { + try { + return new DateTimeZone($this->getTzFromMap($tzid)); + } catch (\Exception $e) { + return null; + } + } + + // Some Microsoft products prefix the offset first, so let's strip that off + // and see if it is our tzid map. We don't want to check for this first just + // in case there are overrides in our tzid map. + foreach ($this->patterns as $pattern) { + if (!preg_match($pattern, $tzid, $matches)) { + continue; + } + $tzidAlternate = $matches[3]; + if ($this->hasTzInMap($tzidAlternate)) { + try { + return new DateTimeZone($this->getTzFromMap($tzidAlternate)); + } catch (\Exception $e) { + return null; + } + } + } + + return null; + } + + /** + * This method returns an array of timezone identifiers, that are supported + * by DateTimeZone(), but not returned by DateTimeZone::listIdentifiers(). + * + * We're not using DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC) because: + * - It's not supported by some PHP versions as well as HHVM. + * - It also returns identifiers, that are invalid values for new DateTimeZone() on some PHP versions. + * (See timezonedata/php-bc.php and timezonedata php-workaround.php) + * + * @return array + */ + private function getTzMaps() + { + if ([] === $this->map) { + $this->map = array_merge( + include __DIR__.'/../timezonedata/windowszones.php', + include __DIR__.'/../timezonedata/lotuszones.php', + include __DIR__.'/../timezonedata/exchangezones.php', + include __DIR__.'/../timezonedata/php-workaround.php' + ); + } + + return $this->map; + } + + private function getTzFromMap(string $tzid): string + { + return $this->getTzMaps()[$tzid]; + } + + private function hasTzInMap(string $tzid): bool + { + return isset($this->getTzMaps()[$tzid]); + } +} diff --git a/lib/TimezoneGuesser/GuessFromLicEntry.php b/lib/TimezoneGuesser/GuessFromLicEntry.php new file mode 100644 index 000000000..f340a3962 --- /dev/null +++ b/lib/TimezoneGuesser/GuessFromLicEntry.php @@ -0,0 +1,33 @@ +{'X-LIC-LOCATION'})) { + return null; + } + + $lic = (string) $vtimezone->{'X-LIC-LOCATION'}; + + // Libical generators may specify strings like + // "SystemV/EST5EDT". For those we must remove the + // SystemV part. + if ('SystemV/' === substr($lic, 0, 8)) { + $lic = substr($lic, 8); + } + + return TimeZoneUtil::getTimeZone($lic, null, $failIfUncertain); + } +} diff --git a/lib/TimezoneGuesser/GuessFromMsTzId.php b/lib/TimezoneGuesser/GuessFromMsTzId.php new file mode 100644 index 000000000..b11ce1832 --- /dev/null +++ b/lib/TimezoneGuesser/GuessFromMsTzId.php @@ -0,0 +1,119 @@ + 'UTC', + 31 => 'Africa/Casablanca', + + // Insanely, id #2 is used for both Europe/Lisbon, and Europe/Sarajevo. + // I'm not even kidding.. We handle this special case in the + // getTimeZone method. + 2 => 'Europe/Lisbon', + 1 => 'Europe/London', + 4 => 'Europe/Berlin', + 6 => 'Europe/Prague', + 3 => 'Europe/Paris', + 69 => 'Africa/Luanda', // This was a best guess + 7 => 'Europe/Athens', + 5 => 'Europe/Bucharest', + 49 => 'Africa/Cairo', + 50 => 'Africa/Harare', + 59 => 'Europe/Helsinki', + 27 => 'Asia/Jerusalem', + 26 => 'Asia/Baghdad', + 74 => 'Asia/Kuwait', + 51 => 'Europe/Moscow', + 56 => 'Africa/Nairobi', + 25 => 'Asia/Tehran', + 24 => 'Asia/Muscat', // Best guess + 54 => 'Asia/Baku', + 48 => 'Asia/Kabul', + 58 => 'Asia/Yekaterinburg', + 47 => 'Asia/Karachi', + 23 => 'Asia/Calcutta', + 62 => 'Asia/Kathmandu', + 46 => 'Asia/Almaty', + 71 => 'Asia/Dhaka', + 66 => 'Asia/Colombo', + 61 => 'Asia/Rangoon', + 22 => 'Asia/Bangkok', + 64 => 'Asia/Krasnoyarsk', + 45 => 'Asia/Shanghai', + 63 => 'Asia/Irkutsk', + 21 => 'Asia/Singapore', + 73 => 'Australia/Perth', + 75 => 'Asia/Taipei', + 20 => 'Asia/Tokyo', + 72 => 'Asia/Seoul', + 70 => 'Asia/Yakutsk', + 19 => 'Australia/Adelaide', + 44 => 'Australia/Darwin', + 18 => 'Australia/Brisbane', + 76 => 'Australia/Sydney', + 43 => 'Pacific/Guam', + 42 => 'Australia/Hobart', + 68 => 'Asia/Vladivostok', + 41 => 'Asia/Magadan', + 17 => 'Pacific/Auckland', + 40 => 'Pacific/Fiji', + 67 => 'Pacific/Tongatapu', + 29 => 'Atlantic/Azores', + 53 => 'Atlantic/Cape_Verde', + 30 => 'America/Noronha', + 8 => 'America/Sao_Paulo', // Best guess + 32 => 'America/Argentina/Buenos_Aires', + 60 => 'America/Godthab', + 28 => 'America/St_Johns', + 9 => 'America/Halifax', + 33 => 'America/Caracas', + 65 => 'America/Santiago', + 35 => 'America/Bogota', + 10 => 'America/New_York', + 34 => 'America/Indiana/Indianapolis', + 55 => 'America/Guatemala', + 11 => 'America/Chicago', + 37 => 'America/Mexico_City', + 36 => 'America/Edmonton', + 38 => 'America/Phoenix', + 12 => 'America/Denver', // Best guess + 13 => 'America/Los_Angeles', // Best guess + 14 => 'America/Anchorage', + 15 => 'Pacific/Honolulu', + 16 => 'Pacific/Midway', + 39 => 'Pacific/Kwajalein', + ]; + + public function guess(VTimeZone $vtimezone, bool $throwIfUnsure = false): ?DateTimeZone + { + // Microsoft may add a magic number, which we also have an + // answer for. + if (!isset($vtimezone->{'X-MICROSOFT-CDO-TZID'})) { + return null; + } + $cdoId = (int) $vtimezone->{'X-MICROSOFT-CDO-TZID'}->getValue(); + + // 2 can mean both Europe/Lisbon and Europe/Sarajevo. + if (2 === $cdoId && false !== strpos((string) $vtimezone->TZID, 'Sarajevo')) { + return new DateTimeZone('Europe/Sarajevo'); + } + + if (isset(self::$microsoftExchangeMap[$cdoId])) { + return new DateTimeZone(self::$microsoftExchangeMap[$cdoId]); + } + + return null; + } +} diff --git a/lib/TimezoneGuesser/TimezoneFinder.php b/lib/TimezoneGuesser/TimezoneFinder.php new file mode 100644 index 000000000..5aa880a1c --- /dev/null +++ b/lib/TimezoneGuesser/TimezoneFinder.php @@ -0,0 +1,10 @@ +getValueType(); } + if (Document::VCARD30 !== $targetVersion && 'PHONE-NUMBER' === $valueType) { + $valueType = null; + } $newProperty = $output->createProperty( $property->name, $property->getParts(), @@ -141,6 +140,8 @@ protected function convertProperty(Component\VCard $input, Component\VCard $outp $newProperty = $output->createProperty('X-ADDRESSBOOKSERVER-KIND', 'GROUP'); break; } + } elseif ('MEMBER' === $property->name) { + $newProperty = $output->createProperty('X-ADDRESSBOOKSERVER-MEMBER', $property->getValue()); } } elseif (Document::VCARD40 === $targetVersion) { // These properties were removed in vCard 4.0 @@ -174,6 +175,9 @@ protected function convertProperty(Component\VCard $input, Component\VCard $outp $newProperty = $output->createProperty('KIND', 'GROUP'); } break; + case 'X-ADDRESSBOOKSERVER-MEMBER': + $newProperty = $output->createProperty('MEMBER', $property->getValue()); + break; case 'X-ANNIVERSARY': $newProperty->name = 'ANNIVERSARY'; // If we already have an anniversary property with the same @@ -227,7 +231,7 @@ protected function convertProperty(Component\VCard $input, Component\VCard $outp // Lastly, we need to see if there's a need for a VALUE parameter. // - // We can do that by instantating a empty property with that name, and + // We can do that by instantiating a empty property with that name, and // seeing if the default valueType is identical to the current one. $tempProperty = $output->createProperty($newProperty->name); if ($tempProperty->getValueType() !== $newProperty->getValueType()) { @@ -242,8 +246,7 @@ protected function convertProperty(Component\VCard $input, Component\VCard $outp * * vCard 4.0 no longer supports BINARY properties. * - * @param Component\VCard $output - * @param Property\Uri $property the input property + * @param Property\Uri $property the input property * @param $parameters list of parameters that will eventually be added to * the new property * @@ -296,8 +299,7 @@ protected function convertBinaryToUri(Component\VCard $output, Property\Binary $ * be valid in vCard 3.0 as well, we should convert those to BINARY if * possible, to improve compatibility. * - * @param Component\VCard $output - * @param Property\Uri $property the input property + * @param Property\Uri $property the input property * * @return Property\Binary|null */ @@ -344,9 +346,6 @@ protected function convertUriToBinary(Component\VCard $output, Property\Uri $new /** * Adds parameters to a new property for vCard 4.0. - * - * @param Property $newProperty - * @param array $parameters */ protected function convertParameters40(Property $newProperty, array $parameters) { @@ -383,9 +382,6 @@ protected function convertParameters40(Property $newProperty, array $parameters) /** * Adds parameters to a new property for vCard 3.0. - * - * @param Property $newProperty - * @param array $parameters */ protected function convertParameters30(Property $newProperty, array $parameters) { diff --git a/lib/Version.php b/lib/Version.php index 4b23e0690..72391f59a 100644 --- a/lib/Version.php +++ b/lib/Version.php @@ -14,5 +14,5 @@ class Version /** * Full version number. */ - const VERSION = '4.1.7'; + public const VERSION = '4.6.0'; } diff --git a/lib/Writer.php b/lib/Writer.php index c70a6ae4d..cbd22022e 100644 --- a/lib/Writer.php +++ b/lib/Writer.php @@ -19,8 +19,6 @@ class Writer /** * Serializes a vCard or iCalendar object. * - * @param Component $component - * * @return string */ public static function write(Component $component) @@ -31,8 +29,7 @@ public static function write(Component $component) /** * Serializes a jCal or jCard object. * - * @param Component $component - * @param int $options + * @param int $options * * @return string */ @@ -44,8 +41,6 @@ public static function writeJson(Component $component, $options = 0) /** * Serializes a xCal or xCard object. * - * @param Component $component - * * @return string */ public static function writeXml(Component $component) diff --git a/lib/timezonedata/exchangezones.php b/lib/timezonedata/exchangezones.php index 89bddc27c..f42944b3b 100644 --- a/lib/timezonedata/exchangezones.php +++ b/lib/timezonedata/exchangezones.php @@ -17,6 +17,7 @@ 'Greenwich Mean Time: Dublin, Edinburgh, Lisbon, London' => 'Europe/Lisbon', 'Greenwich Mean Time; Dublin, Edinburgh, London' => 'Europe/London', 'Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna' => 'Europe/Berlin', + 'Amsterdam, Berlin, Bern, Rom, Stockholm, Wien' => 'Europe/Berlin', 'Belgrade, Pozsony, Budapest, Ljubljana, Prague' => 'Europe/Prague', 'Brussels, Copenhagen, Madrid, Paris' => 'Europe/Paris', 'Paris, Madrid, Brussels, Copenhagen' => 'Europe/Paris', @@ -39,12 +40,12 @@ 'Kabul' => 'Asia/Kabul', 'Ekaterinburg' => 'Asia/Yekaterinburg', 'Islamabad, Karachi, Tashkent' => 'Asia/Karachi', - 'Kolkata, Chennai, Mumbai, New Delhi, India Standard Time' => 'Asia/Calcutta', + 'Kolkata, Chennai, Mumbai, New Delhi, India Standard Time' => 'Asia/Kolkata', 'Kathmandu, Nepal' => 'Asia/Kathmandu', 'Almaty, Novosibirsk, North Central Asia' => 'Asia/Almaty', 'Astana, Dhaka' => 'Asia/Dhaka', 'Sri Jayawardenepura, Sri Lanka' => 'Asia/Colombo', - 'Rangoon' => 'Asia/Rangoon', + 'Rangoon' => 'Asia/Yangon', 'Bangkok, Hanoi, Jakarta' => 'Asia/Bangkok', 'Krasnoyarsk' => 'Asia/Krasnoyarsk', 'Beijing, Chongqing, Hong Kong SAR, Urumqi' => 'Asia/Shanghai', @@ -71,7 +72,7 @@ 'Mid-Atlantic' => 'America/Noronha', 'Brasilia' => 'America/Sao_Paulo', // Best guess 'Buenos Aires' => 'America/Argentina/Buenos_Aires', - 'Greenland' => 'America/Godthab', + 'Greenland' => 'America/Nuuk', 'Newfoundland' => 'America/St_Johns', 'Atlantic Time (Canada)' => 'America/Halifax', 'Caracas, La Paz' => 'America/Caracas', diff --git a/lib/timezonedata/lotuszones.php b/lib/timezonedata/lotuszones.php index 4b50808f9..08c37afdd 100644 --- a/lib/timezonedata/lotuszones.php +++ b/lib/timezonedata/lotuszones.php @@ -34,7 +34,7 @@ 'Newfoundland' => 'America/St_Johns', 'Argentina' => 'America/Argentina/Buenos_Aires', 'E. South America' => 'America/Belem', - 'Greenland' => 'America/Godthab', + 'Greenland' => 'America/Nuuk', 'Montevideo' => 'America/Montevideo', 'SA Eastern' => 'America/Belem', // 'Mid-Atlantic' => 'Etc/GMT-2', // conflict with windows timezones. @@ -71,12 +71,12 @@ 'Ekaterinburg' => 'Asia/Yekaterinburg', 'Pakistan' => 'Asia/Karachi', 'West Asia' => 'Asia/Tashkent', - 'India' => 'Asia/Calcutta', + 'India' => 'Asia/Kolkata', 'Sri Lanka' => 'Asia/Colombo', 'Nepal' => 'Asia/Kathmandu', 'Central Asia' => 'Asia/Dhaka', 'N. Central Asia' => 'Asia/Almaty', - 'Myanmar' => 'Asia/Rangoon', + 'Myanmar' => 'Asia/Yangon', 'North Asia' => 'Asia/Krasnoyarsk', 'SE Asia' => 'Asia/Bangkok', 'China' => 'Asia/Shanghai', diff --git a/lib/timezonedata/php-bc.php b/lib/timezonedata/php-bc.php index 83f38f507..3116c6868 100644 --- a/lib/timezonedata/php-bc.php +++ b/lib/timezonedata/php-bc.php @@ -147,7 +147,6 @@ 'US/Michigan', 'US/Mountain', 'US/Pacific', - 'US/Pacific-New', 'US/Samoa', 'WET', ]; diff --git a/lib/timezonedata/windowszones.php b/lib/timezonedata/windowszones.php index af3904b12..7ff61b52d 100644 --- a/lib/timezonedata/windowszones.php +++ b/lib/timezonedata/windowszones.php @@ -3,14 +3,14 @@ /** * Automatically generated timezone file. * - * Last update: 2016-08-24T17:35:38-04:00 - * Source: http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml + * Last update: 2020-12-13T17:38:12+05:45 + * Source: https://raw.githubusercontent.com/unicode-org/cldr/master/common/supplemental/windowsZones.xml * - * @copyright Copyright (C) 2011-2015 fruux GmbH (https://fruux.com/). + * @copyright Copyright (C) fruux GmbH (https://fruux.com/). * @license http://sabre.io/license/ Modified BSD License */ -return [ +return [ 'AUS Central Standard Time' => 'Australia/Darwin', 'AUS Eastern Standard Time' => 'Australia/Sydney', 'Afghanistan Standard Time' => 'Asia/Kabul', @@ -20,7 +20,7 @@ 'Arab Standard Time' => 'Asia/Riyadh', 'Arabian Standard Time' => 'Asia/Dubai', 'Arabic Standard Time' => 'Asia/Baghdad', - 'Argentina Standard Time' => 'America/Buenos_Aires', + 'Argentina Standard Time' => 'America/Argentina/Buenos_Aires', 'Astrakhan Standard Time' => 'Europe/Astrakhan', 'Atlantic Standard Time' => 'America/Halifax', 'Aus Central W. Standard Time' => 'Australia/Eucla', @@ -55,16 +55,16 @@ 'Eastern Standard Time (Mexico)' => 'America/Cancun', 'Egypt Standard Time' => 'Africa/Cairo', 'Ekaterinburg Standard Time' => 'Asia/Yekaterinburg', - 'FLE Standard Time' => 'Europe/Kiev', + 'FLE Standard Time' => 'Europe/Kyiv', 'Fiji Standard Time' => 'Pacific/Fiji', 'GMT Standard Time' => 'Europe/London', 'GTB Standard Time' => 'Europe/Bucharest', 'Georgian Standard Time' => 'Asia/Tbilisi', - 'Greenland Standard Time' => 'America/Godthab', + 'Greenland Standard Time' => 'America/Nuuk', 'Greenwich Standard Time' => 'Atlantic/Reykjavik', 'Haiti Standard Time' => 'America/Port-au-Prince', 'Hawaiian Standard Time' => 'Pacific/Honolulu', - 'India Standard Time' => 'Asia/Calcutta', + 'India Standard Time' => 'Asia/Kolkata', 'Iran Standard Time' => 'Asia/Tehran', 'Israel Standard Time' => 'Asia/Jerusalem', 'Jordan Standard Time' => 'Asia/Amman', @@ -74,6 +74,7 @@ 'Line Islands Standard Time' => 'Pacific/Kiritimati', 'Lord Howe Standard Time' => 'Australia/Lord_Howe', 'Magadan Standard Time' => 'Asia/Magadan', + 'Magallanes Standard Time' => 'America/Punta_Arenas', 'Marquesas Standard Time' => 'Pacific/Marquesas', 'Mauritius Standard Time' => 'Indian/Mauritius', 'Middle East Standard Time' => 'Asia/Beirut', @@ -81,21 +82,23 @@ 'Morocco Standard Time' => 'Africa/Casablanca', 'Mountain Standard Time' => 'America/Denver', 'Mountain Standard Time (Mexico)' => 'America/Chihuahua', - 'Myanmar Standard Time' => 'Asia/Rangoon', + 'Myanmar Standard Time' => 'Asia/Yangon', 'N. Central Asia Standard Time' => 'Asia/Novosibirsk', 'Namibia Standard Time' => 'Africa/Windhoek', - 'Nepal Standard Time' => 'Asia/Katmandu', + 'Nepal Standard Time' => 'Asia/Kathmandu', 'New Zealand Standard Time' => 'Pacific/Auckland', 'Newfoundland Standard Time' => 'America/St_Johns', 'Norfolk Standard Time' => 'Pacific/Norfolk', 'North Asia East Standard Time' => 'Asia/Irkutsk', 'North Asia Standard Time' => 'Asia/Krasnoyarsk', 'North Korea Standard Time' => 'Asia/Pyongyang', + 'Omsk Standard Time' => 'Asia/Omsk', 'Pacific SA Standard Time' => 'America/Santiago', 'Pacific Standard Time' => 'America/Los_Angeles', 'Pacific Standard Time (Mexico)' => 'America/Tijuana', 'Pakistan Standard Time' => 'Asia/Karachi', 'Paraguay Standard Time' => 'America/Asuncion', + 'Qyzylorda Standard Time' => 'Asia/Qyzylorda', 'Romance Standard Time' => 'Europe/Paris', 'Russia Time Zone 10' => 'Asia/Srednekolymsk', 'Russia Time Zone 11' => 'Asia/Kamchatka', @@ -108,9 +111,12 @@ 'Saint Pierre Standard Time' => 'America/Miquelon', 'Sakhalin Standard Time' => 'Asia/Sakhalin', 'Samoa Standard Time' => 'Pacific/Apia', + 'Sao Tome Standard Time' => 'Africa/Sao_Tome', + 'Saratov Standard Time' => 'Europe/Saratov', 'Singapore Standard Time' => 'Asia/Singapore', 'South Africa Standard Time' => 'Africa/Johannesburg', 'Sri Lanka Standard Time' => 'Asia/Colombo', + 'Sudan Standard Time' => 'Africa/Khartoum', 'Syria Standard Time' => 'Asia/Damascus', 'Taipei Standard Time' => 'Asia/Taipei', 'Tasmania Standard Time' => 'Australia/Hobart', @@ -121,10 +127,11 @@ 'Transbaikal Standard Time' => 'Asia/Chita', 'Turkey Standard Time' => 'Europe/Istanbul', 'Turks And Caicos Standard Time' => 'America/Grand_Turk', - 'US Eastern Standard Time' => 'America/Indianapolis', + 'US Eastern Standard Time' => 'America/Indiana/Indianapolis', 'US Mountain Standard Time' => 'America/Phoenix', 'UTC' => 'Etc/GMT', 'UTC+12' => 'Etc/GMT-12', + 'UTC+13' => 'Etc/GMT-13', 'UTC-02' => 'Etc/GMT+2', 'UTC-08' => 'Etc/GMT+8', 'UTC-09' => 'Etc/GMT+9', @@ -132,6 +139,7 @@ 'Ulaanbaatar Standard Time' => 'Asia/Ulaanbaatar', 'Venezuela Standard Time' => 'America/Caracas', 'Vladivostok Standard Time' => 'Asia/Vladivostok', + 'Volgograd Standard Time' => 'Europe/Volgograd', 'W. Australia Standard Time' => 'Australia/Perth', 'W. Central Africa Standard Time' => 'Africa/Lagos', 'W. Europe Standard Time' => 'Europe/Berlin', @@ -140,4 +148,5 @@ 'West Bank Standard Time' => 'Asia/Hebron', 'West Pacific Standard Time' => 'Pacific/Port_Moresby', 'Yakutsk Standard Time' => 'Asia/Yakutsk', + 'Yukon Standard Time' => 'America/Whitehorse', ]; diff --git a/phpstan.neon b/phpstan.neon index e50c5be6e..27a856854 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,3 +1,14 @@ parameters: - level: 0 - bootstrap: %currentWorkingDirectory%/vendor/autoload.php + level: 1 + reportUnmatchedIgnoredErrors: false + universalObjectCratesClasses: + - \Sabre\VObject\Component + ignoreErrors: + - + message: "#^Call to an undefined static method#" + count: 2 + path: tests/VObject/Component/VCalendarTest.php + - + message: "#^Cannot unset offset 0 on Sabre\\\\VObject\\\\Property|null.$#" + count: 1 + path: tests/VObject/PropertyTest.php diff --git a/tests/VObject/BirthdayCalendarGeneratorTest.php b/tests/VObject/BirthdayCalendarGeneratorTest.php index 6e4f89a4c..d27362837 100644 --- a/tests/VObject/BirthdayCalendarGeneratorTest.php +++ b/tests/VObject/BirthdayCalendarGeneratorTest.php @@ -458,11 +458,9 @@ public function testVcardStringWithEmptyBirthdayProperty() ); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testParseException() { + $this->expectException(ParseException::class); $generator = new BirthdayCalendarGenerator(); $input = <<setObjects($input); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidArgumentException() { + $this->expectException(\InvalidArgumentException::class); $generator = new BirthdayCalendarGenerator(); $input = <<setObjects($input); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidArgumentExceptionForPartiallyInvalidArray() { + $this->expectException(\InvalidArgumentException::class); $generator = new BirthdayCalendarGenerator(); $input = []; diff --git a/tests/VObject/CliTest.php b/tests/VObject/CliTest.php index 11c969c9d..a4124b76b 100644 --- a/tests/VObject/CliTest.php +++ b/tests/VObject/CliTest.php @@ -11,8 +11,17 @@ */ class CliTest extends TestCase { - public function setUp() + /** @var CliMock */ + private $cli; + + private $sabreTempDir = __DIR__.'/../temp/'; + + public function setUp(): void { + if (!file_exists($this->sabreTempDir)) { + mkdir($this->sabreTempDir); + } + $this->cli = new CliMock(); $this->cli->stderr = fopen('php://memory', 'r+'); $this->cli->stdout = fopen('php://memory', 'r+'); @@ -266,7 +275,7 @@ public function testConvertMimeDir() public function testConvertDefaultFormats() { - $outputFile = SABRE_TEMPDIR.'bar.json'; + $outputFile = $this->sabreTempDir.'bar.json'; $this->assertEquals( 2, @@ -279,7 +288,7 @@ public function testConvertDefaultFormats() public function testConvertDefaultFormats2() { - $outputFile = SABRE_TEMPDIR.'bar.ics'; + $outputFile = $this->sabreTempDir.'bar.ics'; $this->assertEquals( 2, @@ -474,7 +483,15 @@ public function testRepair() ); rewind($this->cli->stdout); - $this->assertRegExp("/^BEGIN:VCARD\r\nVERSION:2.1\r\nUID:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\r\nEND:VCARD\r\n$/", stream_get_contents($this->cli->stdout)); + $regularExpression = "/^BEGIN:VCARD\r\nVERSION:2.1\r\nUID:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\r\nEND:VCARD\r\n$/"; + $data = stream_get_contents($this->cli->stdout); + // ToDo: when we do not need to run phpunit 7 or 8, remove this 'if' block and just use + // the new assertMatchesRegularExpression that exists since phpunit 9. + if (method_exists($this, 'assertMatchesRegularExpression')) { + $this->assertMatchesRegularExpression($regularExpression, $data); + } else { + $this->assertRegExp($regularExpression, $data); + } } public function testRepairNothing() diff --git a/tests/VObject/Component/AvailableTest.php b/tests/VObject/Component/AvailableTest.php index 55292424e..bf0a6716f 100644 --- a/tests/VObject/Component/AvailableTest.php +++ b/tests/VObject/Component/AvailableTest.php @@ -22,7 +22,7 @@ public function testAvailableComponent() END:VCALENDAR VCAL; $document = Reader::read($vcal); - $this->assertInstanceOf(__NAMESPACE__.'\Available', $document->AVAILABLE); + $this->assertInstanceOf(Available::class, $document->AVAILABLE); } public function testGetEffectiveStartEnd() diff --git a/tests/VObject/Component/VAlarmTest.php b/tests/VObject/Component/VAlarmTest.php index 1e7a55ad7..2823d16da 100644 --- a/tests/VObject/Component/VAlarmTest.php +++ b/tests/VObject/Component/VAlarmTest.php @@ -4,6 +4,7 @@ use DateTime; use PHPUnit\Framework\TestCase; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Reader; class VAlarmTest extends TestCase @@ -126,11 +127,9 @@ public function timeRangeTestData() return $tests; } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testInTimeRangeInvalidComponent() { + $this->expectException(InvalidDataException::class); $calendar = new VCalendar(); $valarm = $calendar->createComponent('VALARM'); $valarm->TRIGGER = '-P1D'; diff --git a/tests/VObject/Component/VAvailabilityTest.php b/tests/VObject/Component/VAvailabilityTest.php index b6b9a2b80..edd06b02b 100644 --- a/tests/VObject/Component/VAvailabilityTest.php +++ b/tests/VObject/Component/VAvailabilityTest.php @@ -24,7 +24,7 @@ public function testVAvailabilityComponent() VCAL; $document = Reader::read($vcal); - $this->assertInstanceOf(__NAMESPACE__.'\VAvailability', $document->VAVAILABILITY); + $this->assertInstanceOf(VAvailability::class, $document->VAVAILABILITY); } public function testGetEffectiveStartEnd() @@ -122,7 +122,7 @@ public function testIsInTimeRangeOutside() ); } - public function testRFCxxxSection3_1_availabilityprop_required() + public function testRFCxxxSection3Part1AvailabilitypropRequired() { // UID and DTSTAMP are present. $this->assertIsValid(Reader::read( @@ -177,7 +177,7 @@ public function testRFCxxxSection3_1_availabilityprop_required() )); } - public function testRFCxxxSection3_1_availabilityprop_optional_once() + public function testRFCxxxSection3Part1AvailabilitypropOptionalOnce() { $properties = [ 'BUSYTYPE:BUSY', @@ -205,7 +205,7 @@ public function testRFCxxxSection3_1_availabilityprop_optional_once() } } - public function testRFCxxxSection3_1_availabilityprop_dtend_duration() + public function testRFCxxxSection3Part1AvailabilitypropDtendDuration() { // Only DTEND. $this->assertIsValid(Reader::read($this->template([ @@ -236,10 +236,10 @@ public function testAvailableSubComponent() VCAL; $document = Reader::read($vcal); - $this->assertInstanceOf(__NAMESPACE__, $document->VAVAILABILITY->AVAILABLE); + $this->assertInstanceOf(Available::class, $document->VAVAILABILITY->AVAILABLE); } - public function testRFCxxxSection3_1_availableprop_required() + public function testRFCxxxSection3Part1AvailablepropRequired() { // UID, DTSTAMP and DTSTART are present. $this->assertIsValid(Reader::read( @@ -331,7 +331,7 @@ public function testRFCxxxSection3_1_availableprop_required() )); } - public function testRFCxxxSection3_1_available_dtend_duration() + public function testRFCxxxSection3Part1AvailableDtendDuration() { // Only DTEND. $this->assertIsValid(Reader::read($this->templateAvailable([ @@ -350,7 +350,7 @@ public function testRFCxxxSection3_1_available_dtend_duration() ]))); } - public function testRFCxxxSection3_1_available_optional_once() + public function testRFCxxxSection3Part1AvailableOptionalOnce() { $properties = [ 'CREATED:20111005T135125Z', @@ -373,7 +373,7 @@ public function testRFCxxxSection3_1_available_optional_once() } } - public function testRFCxxxSection3_2() + public function testRFCxxxSection3Part2() { $this->assertEquals( 'BUSY', diff --git a/tests/VObject/Component/VCalendarTest.php b/tests/VObject/Component/VCalendarTest.php index dbf2fef0a..417732ac2 100644 --- a/tests/VObject/Component/VCalendarTest.php +++ b/tests/VObject/Component/VCalendarTest.php @@ -5,6 +5,7 @@ use DateTimeZone; use PHPUnit\Framework\TestCase; use Sabre\VObject; +use Sabre\VObject\InvalidDataException; class VCalendarTest extends TestCase { @@ -330,11 +331,9 @@ public function expandData() return $tests; } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testBrokenEventExpand() { + $this->expectException(InvalidDataException::class); $input = 'BEGIN:VCALENDAR CALSCALE:GREGORIAN VERSION:2.0 @@ -351,6 +350,33 @@ public function testBrokenEventExpand() ); } + /** + * This test used to induce an infinite loop. + * The "medium" annotation means that phpunit will fail the + * test if it takes longer than a default of 10 seconds. + * + * @medium + */ + public function testEventExpandYearly() + { + $input = 'BEGIN:VCALENDAR +BEGIN:VEVENT +UID:1a093f1012086078fdd3d9df5ff4d7d0 +DTSTART;TZID=UTC:20210203T130000 +DTEND;TZID=UTC:20210203T140000 +RRULE:FREQ=YEARLY;COUNT=7;WKST=MO;BYDAY=MO;BYWEEKNO=13,15,50 +END:VEVENT +END:VCALENDAR +'; + $vcal = VObject\Reader::read($input); + $events = $vcal->expand( + new \DateTime('2021-01-01'), + new \DateTime('2023-01-01') + ); + + $this->assertCount(7, $events->VEVENT); + } + public function testGetDocumentType() { $vcard = new VCalendar(); @@ -731,6 +757,55 @@ public function testCalDAVMETHOD() ); } + public function testNodeInValidationErrorHasLineIndexAndLineStringProps(): void + { + $defectiveInput = <<validate(); + $warningMessages = []; + foreach ($result as $error) { + $warningMessages[] = $error['message']; + } + self::assertCount(2, $result, 'We expected exactly 2 validation messages, instead we got '.count($result).' results:'.implode(', ', $warningMessages)); + foreach ($result as $idx => $warning) { + self::assertArrayHasKey('node', $warning); + self::assertInstanceOf(VObject\Property\ICalendar\DateTime::class, $warning['node']); + if (method_exists($this, 'assertObjectHasProperty')) { + self::assertObjectHasProperty('lineIndex', $warning['node']); + self::assertObjectHasProperty('lineString', $warning['node']); + } else { + // Fall back to the older method name known to older versions of phpunit. + self::assertObjectHasAttribute('lineIndex', $warning['node']); + self::assertObjectHasAttribute('lineString', $warning['node']); + } + switch ($idx) { + case 0: + self::assertEquals('10', $warning['node']->lineIndex); + self::assertEquals('CREATED:', $warning['node']->lineString); + break; + case 1: + self::assertEquals('11', $warning['node']->lineIndex); + self::assertEquals('LAST-MODIFIED:', $warning['node']->lineString); + break; + } + } + } + public function assertValidate($ics, $options, $expectedLevel, $expectedMessage = null) { $vcal = VObject\Reader::read($ics); diff --git a/tests/VObject/Component/VCardTest.php b/tests/VObject/Component/VCardTest.php index 1895ce6c5..801eaad79 100644 --- a/tests/VObject/Component/VCardTest.php +++ b/tests/VObject/Component/VCardTest.php @@ -92,6 +92,14 @@ public function validateData() ], "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:foo\r\nORG:Acme Co.\r\nFN:Acme Co.\r\nEND:VCARD\r\n", ]; + // No FN, NICKNAME fallback + $tests[] = [ + "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:foo\r\nNICKNAME:JohnDoe\r\nEND:VCARD\r\n", + [ + 'The FN property must appear in the VCARD component exactly 1 time', + ], + "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:foo\r\nNICKNAME:JohnDoe\r\nFN:JohnDoe\r\nEND:VCARD\r\n", + ]; // No FN, EMAIL fallback $tests[] = [ "BEGIN:VCARD\r\nVERSION:4.0\r\nUID:foo\r\nEMAIL:1@example.org\r\nEND:VCARD\r\n", @@ -135,8 +143,29 @@ public function testGetByType() $vcard = VObject\Reader::read($vcard); $this->assertEquals('1@example.org', $vcard->getByType('EMAIL', 'home')->getValue()); $this->assertEquals('2@example.org', $vcard->getByType('EMAIL', 'work')->getValue()); - $this->assertNull($vcard->getByType('EMAIL', 'non-existant')); - $this->assertNull($vcard->getByType('ADR', 'non-existant')); + $this->assertNull($vcard->getByType('EMAIL', 'non-existent')); + $this->assertNull($vcard->getByType('ADR', 'non-existent')); + } + + public function testGetByTypes() + { + $vcard = <<getByTypes('TEL', ['home', 'cell'])->getValue()); + self::assertEquals('665544332211', $vcard->getByTypes('TEL', ['work', 'cell'])->getValue()); + self::assertEquals('7778889994455', $vcard->getByTypes('TEL', ['work'])->getValue()); + self::assertEquals('555555555', $vcard->getByTypes('TEL', ['external'])->getValue()); + self::assertNull($vcard->getByTypes('TEL', ['non-existent'])); + self::assertNull($vcard->getByTypes('EMAIL', ['non-existent'])); } public function testPreferredNoPref() @@ -204,7 +233,7 @@ public function testNoUIDCardDAV() VCF; $this->assertValidate( $vcard, - VCARD::PROFILE_CARDDAV, + VCard::PROFILE_CARDDAV, 3, 'vCards on CardDAV servers MUST have a UID property.' ); @@ -236,7 +265,7 @@ public function testNoUIDNoCardDAVRepair() VCF; $this->assertValidate( $vcard, - VCARD::REPAIR, + VCard::REPAIR, 1, 'Adding a UID to a vCard property is recommended.' ); @@ -253,7 +282,7 @@ public function testVCard21CardDAV() VCF; $this->assertValidate( $vcard, - VCARD::PROFILE_CARDDAV, + VCard::PROFILE_CARDDAV, 3, 'CardDAV servers are not allowed to accept vCard 2.1.' ); diff --git a/tests/VObject/Component/VEventTest.php b/tests/VObject/Component/VEventTest.php index 635ae5acd..6110af842 100644 --- a/tests/VObject/Component/VEventTest.php +++ b/tests/VObject/Component/VEventTest.php @@ -89,6 +89,41 @@ public function timeRangeTestData() $vevent9->RRULE = 'FREQ=DAILY'; $tests[] = [$vevent9, new \DateTime('2016-10-31'), new \DateTime('2016-12-12'), true]; + // Added this test to check events with RDATE property with multiple dates + $vevent10 = clone $vevent; + $vevent10->DTSTART = '20140901T000000Z'; + $vevent10->DTEND = '20140901T010000Z'; + $vevent10->add('RDATE', ['20141001T000000Z', '20141101T000000Z']); + // DTSTART is the first occurrence + $tests[] = [$vevent10, new \DateTime('2014-09-01'), new \DateTime('2014-09-02'), true]; + // RDATE adds additional occurrences on Oct 1 and Nov 1 + $tests[] = [$vevent10, new \DateTime('2014-10-01'), new \DateTime('2014-10-02'), true]; + $tests[] = [$vevent10, new \DateTime('2014-11-01'), new \DateTime('2014-11-02'), true]; + // No occurrence in December + $tests[] = [$vevent10, new \DateTime('2014-12-01'), new \DateTime('2014-12-31'), false]; + // Range that includes first occurrence + $tests[] = [$vevent10, new \DateTime('2014-08-01'), new \DateTime('2014-09-30'), true]; + // Range that spans all occurrences + $tests[] = [$vevent10, new \DateTime('2014-08-01'), new \DateTime('2014-12-31'), true]; + + // Added this test to check events with RDATE property with multiple instances + $vevent11 = clone $vevent; + $vevent11->DTSTART = '20140901T000000Z'; + $vevent11->DTEND = '20140901T010000Z'; + $vevent11->add('RDATE', '20141001T000000Z'); + $vevent11->add('RDATE', '20141101T000000Z'); + // DTSTART is the first occurrence + $tests[] = [$vevent11, new \DateTime('2014-09-01'), new \DateTime('2014-09-02'), true]; + // RDATE adds additional occurrences on Oct 1 and Nov 1 + $tests[] = [$vevent11, new \DateTime('2014-10-01'), new \DateTime('2014-10-02'), true]; + $tests[] = [$vevent11, new \DateTime('2014-11-01'), new \DateTime('2014-11-02'), true]; + // No occurrence in December + $tests[] = [$vevent11, new \DateTime('2014-12-01'), new \DateTime('2014-12-31'), false]; + // Range that includes first occurrence + $tests[] = [$vevent11, new \DateTime('2014-08-01'), new \DateTime('2014-09-30'), true]; + // Range that spans all occurrences + $tests[] = [$vevent11, new \DateTime('2014-08-01'), new \DateTime('2014-12-31'), true]; + return $tests; } } diff --git a/tests/VObject/ComponentTest.php b/tests/VObject/ComponentTest.php index 8c0a0d7c6..9acedf925 100644 --- a/tests/VObject/ComponentTest.php +++ b/tests/VObject/ComponentTest.php @@ -21,10 +21,13 @@ public function testIterate() $count = 0; foreach ($comp->children() as $key => $subcomponent) { ++$count; - $this->assertInstanceOf('Sabre\\VObject\\Component', $subcomponent); + $this->assertInstanceOf(Component::class, $subcomponent); + + if (2 === $count) { + $this->assertEquals(1, $key); + } } $this->assertEquals(2, $count); - $this->assertEquals(1, $key); } public function testMagicGet() @@ -38,10 +41,10 @@ public function testMagicGet() $comp->add($sub); $event = $comp->vevent; - $this->assertInstanceOf('Sabre\\VObject\\Component', $event); + $this->assertInstanceOf(Component::class, $event); $this->assertEquals('VEVENT', $event->name); - $this->assertInternalType('null', $comp->vjournal); + $this->assertNull($comp->vjournal); } public function testMagicGetGroups() @@ -57,16 +60,48 @@ public function testMagicGetGroups() $sub = $comp->createProperty('EMAIL', '3@3.com'); $comp->add($sub); + $sub = $comp->createProperty('0.EMAIL', '0@0.com'); + $comp->add($sub); + $emails = $comp->email; - $this->assertEquals(3, count($emails)); + $this->assertEquals(4, count($emails)); $email1 = $comp->{'group1.email'}; $this->assertEquals('EMAIL', $email1[0]->name); $this->assertEquals('GROUP1', $email1[0]->group); + $email0 = $comp->{'0.email'}; + $this->assertEquals('EMAIL', $email0[0]->name); + $this->assertEquals('0', $email0[0]->group); + + // this is supposed to return all EMAIL properties that do not have a group $email3 = $comp->{'.email'}; $this->assertEquals('EMAIL', $email3[0]->name); $this->assertEquals(null, $email3[0]->group); + + // this is supposed to return all properties that do not have a group + $nogroupProps = $comp->{'.'}; + $this->assertGreaterThan(0, count($email3)); + foreach ($nogroupProps as $prop) { + $this->assertEquals(null, $prop->group); + } + } + + public function testAddGroupProperties() + { + $comp = new VCard([ + 'VERSION' => '3.0', + 'item2.X-ABLabel' => 'item2-Foo', + ]); + + $comp->{'ITEM1.X-ABLabel'} = 'ITEM1-Foo'; + + foreach (['item2', 'ITEM1'] as $group) { + $prop = $comp->{"$group.X-ABLabel"}; + $this->assertInstanceOf(Property::class, $prop); + $this->assertSame("$group-Foo", (string) $prop); + $this->assertSame($group, $prop->group); + } } public function testMagicIsset() @@ -89,7 +124,7 @@ public function testMagicSetScalar() $comp = new VCalendar(); $comp->myProp = 'myValue'; - $this->assertInstanceOf('Sabre\\VObject\\Property', $comp->MYPROP); + $this->assertInstanceOf(Property::class, $comp->MYPROP); $this->assertEquals('myValue', (string) $comp->MYPROP); } @@ -100,7 +135,7 @@ public function testMagicSetScalarTwice() $comp->myProp = 'myValue'; $this->assertEquals(1, count($comp->children())); - $this->assertInstanceOf('Sabre\\VObject\\Property', $comp->MYPROP); + $this->assertInstanceOf(Property::class, $comp->MYPROP); $this->assertEquals('myValue', (string) $comp->MYPROP); } @@ -109,7 +144,7 @@ public function testMagicSetArray() $comp = new VCalendar(); $comp->ORG = ['Acme Inc', 'Section 9']; - $this->assertInstanceOf('Sabre\\VObject\\Property', $comp->ORG); + $this->assertInstanceOf(Property::class, $comp->ORG); $this->assertEquals(['Acme Inc', 'Section 9'], $comp->ORG->getParts()); } @@ -174,20 +209,16 @@ public function testArrayAccessExists() $this->assertTrue(isset($comp->vevent[1])); } - /** - * @expectedException \LogicException - */ public function testArrayAccessSet() { + $this->expectException(\LogicException::class); $comp = new VCalendar(); $comp['hey'] = 'hi there'; } - /** - * @expectedException \LogicException - */ public function testArrayAccessUnset() { + $this->expectException(\LogicException::class); $comp = new VCalendar(); unset($comp[0]); } @@ -217,7 +248,7 @@ public function testAddScalarParams() $bla = $comp->children()[0]; - $this->assertInstanceOf('Sabre\\VObject\\Property', $bla); + $this->assertInstanceOf(Property::class, $bla); $this->assertEquals('MYPROP', $bla->name); $this->assertEquals('value', (string) $bla); @@ -250,20 +281,16 @@ public function testAddComponentTwice() $this->assertEquals('VEVENT', $comp->VEVENT->name); } - /** - * @expectedException \InvalidArgumentException - */ public function testAddArgFail() { + $this->expectException(\InvalidArgumentException::class); $comp = new VCalendar(); $comp->add($comp->createComponent('VEVENT'), 'hello'); } - /** - * @expectedException \InvalidArgumentException - */ public function testAddArgFail2() { + $this->expectException(\InvalidArgumentException::class); $comp = new VCalendar(); $comp->add([]); } @@ -293,7 +320,7 @@ public function testChildren() $comp->add($comp->createComponent('VTODO')); $r = $comp->children(); - $this->assertInternalType('array', $r); + $this->assertIsArray($r); $this->assertEquals(2, count($r)); } @@ -305,7 +332,7 @@ public function testGetComponents() $comp->add($comp->createComponent('VTODO')); $r = $comp->getComponents(); - $this->assertInternalType('array', $r); + $this->assertIsArray($r); $this->assertEquals(1, count($r)); $this->assertEquals('VTODO', $r[0]->name); } @@ -414,11 +441,9 @@ public function testRemoveByObj() $this->assertTrue(isset($comp->prop1)); } - /** - * @expectedException \InvalidArgumentException - */ public function testRemoveNotFound() { + $this->expectException(\InvalidArgumentException::class); $comp = new VCalendar([], false); $prop = $comp->createProperty('A', 'B'); $comp->remove($prop); diff --git a/tests/VObject/DateTimeParserTest.php b/tests/VObject/DateTimeParserTest.php index 44fba80c5..ab0c1ae6f 100644 --- a/tests/VObject/DateTimeParserTest.php +++ b/tests/VObject/DateTimeParserTest.php @@ -31,11 +31,15 @@ public function testParseICalendarDurationDateInterval() $this->assertEquals($expected, DateTimeParser::parseDuration('-PT3M')); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ + public function testParseDurationZero() + { + $expected = new \DateInterval('PT0S'); + self::assertEquals($expected, DateTimeParser::parseDuration('P')); + } + public function testParseICalendarDurationFail() { + $this->expectException(InvalidDataException::class); DateTimeParser::parseDuration('P1X', true); } @@ -50,19 +54,19 @@ public function testParseICalendarDateTime() /** * @depends testParseICalendarDateTime - * @expectedException \Sabre\VObject\InvalidDataException */ public function testParseICalendarDateTimeBadFormat() { + $this->expectException(InvalidDataException::class); $dateTime = DateTimeParser::parseDateTime('20100316T141405 '); } /** * @depends testParseICalendarDateTime - * @expectedException \Sabre\VObject\InvalidDataException */ public function testParseICalendarDateTimeInvalidTime() { + $this->expectException(InvalidDataException::class); $dateTime = DateTimeParser::parseDateTime('20100316T251405'); } @@ -143,19 +147,19 @@ public function testParseICalendarDateTimeGreaterThan4000() /** * @depends testParseICalendarDate - * @expectedException \Sabre\VObject\InvalidDataException */ public function testParseICalendarDateBadFormat() { + $this->expectException(InvalidDataException::class); $dateTime = DateTimeParser::parseDate('20100316T141405'); } /** * @depends testParseICalendarDate - * @expectedException \Sabre\VObject\InvalidDataException */ public function testParseICalendarDateInvalidDate() { + $this->expectException(InvalidDataException::class); $dateTime = DateTimeParser::parseDate('20101331'); } @@ -170,19 +174,15 @@ public function testVCardDate($input, $output) ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testBadVCardDate() { + $this->expectException(InvalidDataException::class); DateTimeParser::parseVCardDateTime('1985---01'); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testBadVCardTime() { + $this->expectException(InvalidDataException::class); DateTimeParser::parseVCardTime('23:12:166'); } @@ -414,7 +414,7 @@ public function vcardDates() ]; } - public function testDateAndOrTime_DateWithYearMonthDay() + public function testDateAndOrTimeDateWithYearMonthDay() { $this->assertDateAndOrTimeEqualsTo( '20150128', @@ -426,7 +426,7 @@ public function testDateAndOrTime_DateWithYearMonthDay() ); } - public function testDateAndOrTime_DateWithYearMonth() + public function testDateAndOrTimeDateWithYearMonth() { $this->assertDateAndOrTimeEqualsTo( '2015-01', @@ -437,7 +437,7 @@ public function testDateAndOrTime_DateWithYearMonth() ); } - public function testDateAndOrTime_DateWithMonth() + public function testDateAndOrTimeDateWithMonth() { $this->assertDateAndOrTimeEqualsTo( '--01', @@ -447,7 +447,7 @@ public function testDateAndOrTime_DateWithMonth() ); } - public function testDateAndOrTime_DateWithMonthDay() + public function testDateAndOrTimeDateWithMonthDay() { $this->assertDateAndOrTimeEqualsTo( '--0128', @@ -458,7 +458,7 @@ public function testDateAndOrTime_DateWithMonthDay() ); } - public function testDateAndOrTime_DateWithDay() + public function testDateAndOrTimeDateWithDay() { $this->assertDateAndOrTimeEqualsTo( '---28', @@ -468,7 +468,7 @@ public function testDateAndOrTime_DateWithDay() ); } - public function testDateAndOrTime_TimeWithHour() + public function testDateAndOrTimeTimeWithHour() { $this->assertDateAndOrTimeEqualsTo( '13', @@ -478,7 +478,7 @@ public function testDateAndOrTime_TimeWithHour() ); } - public function testDateAndOrTime_TimeWithHourMinute() + public function testDateAndOrTimeTimeWithHourMinute() { $this->assertDateAndOrTimeEqualsTo( '1353', @@ -489,7 +489,7 @@ public function testDateAndOrTime_TimeWithHourMinute() ); } - public function testDateAndOrTime_TimeWithHourSecond() + public function testDateAndOrTimeTimeWithHourSecond() { $this->assertDateAndOrTimeEqualsTo( '135301', @@ -501,7 +501,7 @@ public function testDateAndOrTime_TimeWithHourSecond() ); } - public function testDateAndOrTime_TimeWithMinute() + public function testDateAndOrTimeTimeWithMinute() { $this->assertDateAndOrTimeEqualsTo( '-53', @@ -511,7 +511,7 @@ public function testDateAndOrTime_TimeWithMinute() ); } - public function testDateAndOrTime_TimeWithMinuteSecond() + public function testDateAndOrTimeTimeWithMinuteSecond() { $this->assertDateAndOrTimeEqualsTo( '-5301', @@ -522,7 +522,7 @@ public function testDateAndOrTime_TimeWithMinuteSecond() ); } - public function testDateAndOrTime_TimeWithSecond() + public function testDateAndOrTimeTimeWithSecond() { $this->assertTrue(true); @@ -532,7 +532,7 @@ public function testDateAndOrTime_TimeWithSecond() */ } - public function testDateAndOrTime_TimeWithSecondZ() + public function testDateAndOrTimeTimeWithSecondZ() { $this->assertDateAndOrTimeEqualsTo( '--01Z', @@ -543,7 +543,7 @@ public function testDateAndOrTime_TimeWithSecondZ() ); } - public function testDateAndOrTime_TimeWithSecondTZ() + public function testDateAndOrTimeTimeWithSecondTZ() { $this->assertDateAndOrTimeEqualsTo( '--01+1234', @@ -554,7 +554,7 @@ public function testDateAndOrTime_TimeWithSecondTZ() ); } - public function testDateAndOrTime_DateTimeWithYearMonthDayHour() + public function testDateAndOrTimeDateTimeWithYearMonthDayHour() { $this->assertDateAndOrTimeEqualsTo( '20150128T13', @@ -567,7 +567,7 @@ public function testDateAndOrTime_DateTimeWithYearMonthDayHour() ); } - public function testDateAndOrTime_DateTimeWithMonthDayHour() + public function testDateAndOrTimeDateTimeWithMonthDayHour() { $this->assertDateAndOrTimeEqualsTo( '--0128T13', @@ -579,7 +579,7 @@ public function testDateAndOrTime_DateTimeWithMonthDayHour() ); } - public function testDateAndOrTime_DateTimeWithDayHour() + public function testDateAndOrTimeDateTimeWithDayHour() { $this->assertDateAndOrTimeEqualsTo( '---28T13', @@ -590,7 +590,7 @@ public function testDateAndOrTime_DateTimeWithDayHour() ); } - public function testDateAndOrTime_DateTimeWithDayHourMinute() + public function testDateAndOrTimeDateTimeWithDayHourMinute() { $this->assertDateAndOrTimeEqualsTo( '---28T1353', @@ -602,7 +602,7 @@ public function testDateAndOrTime_DateTimeWithDayHourMinute() ); } - public function testDateAndOrTime_DateTimeWithDayHourMinuteSecond() + public function testDateAndOrTimeDateTimeWithDayHourMinuteSecond() { $this->assertDateAndOrTimeEqualsTo( '---28T135301', @@ -615,7 +615,7 @@ public function testDateAndOrTime_DateTimeWithDayHourMinuteSecond() ); } - public function testDateAndOrTime_DateTimeWithDayHourZ() + public function testDateAndOrTimeDateTimeWithDayHourZ() { $this->assertDateAndOrTimeEqualsTo( '---28T13Z', @@ -627,7 +627,7 @@ public function testDateAndOrTime_DateTimeWithDayHourZ() ); } - public function testDateAndOrTime_DateTimeWithDayHourTZ() + public function testDateAndOrTimeDateTimeWithDayHourTZ() { $this->assertDateAndOrTimeEqualsTo( '---28T13+1234', diff --git a/tests/VObject/DocumentTest.php b/tests/VObject/DocumentTest.php index 2665406f6..f2698f65f 100644 --- a/tests/VObject/DocumentTest.php +++ b/tests/VObject/DocumentTest.php @@ -24,11 +24,11 @@ public function testCreateComponent() $event = $vcal->createComponent('VEVENT'); - $this->assertInstanceOf('Sabre\VObject\Component\VEvent', $event); + $this->assertInstanceOf(Component\VEvent::class, $event); $vcal->add($event); $prop = $vcal->createProperty('X-PROP', '1234256', ['X-PARAM' => '3']); - $this->assertInstanceOf('Sabre\VObject\Property', $prop); + $this->assertInstanceOf(Property::class, $prop); $event->add($prop); @@ -46,16 +46,16 @@ public function testCreate() $vcal = new Component\VCalendar([], false); $event = $vcal->create('VEVENT'); - $this->assertInstanceOf('Sabre\VObject\Component\VEvent', $event); + $this->assertInstanceOf(Component\VEvent::class, $event); $prop = $vcal->create('CALSCALE'); - $this->assertInstanceOf('Sabre\VObject\Property\Text', $prop); + $this->assertInstanceOf(Property\Text::class, $prop); } public function testGetClassNameForPropertyValue() { $vcal = new Component\VCalendar([], false); - $this->assertEquals('Sabre\\VObject\\Property\\Text', $vcal->getClassNameForPropertyValue('TEXT')); + $this->assertEquals(Property\Text::class, $vcal->getClassNameForPropertyValue('TEXT')); $this->assertNull($vcal->getClassNameForPropertyValue('FOO')); } @@ -64,7 +64,7 @@ public function testDestroy() $vcal = new Component\VCalendar([], false); $event = $vcal->createComponent('VEVENT'); - $this->assertInstanceOf('Sabre\VObject\Component\VEvent', $event); + $this->assertInstanceOf(Component\VEvent::class, $event); $vcal->add($event); $prop = $vcal->createProperty('X-PROP', '1234256', ['X-PARAM' => '3']); diff --git a/tests/VObject/ElementListTest.php b/tests/VObject/ElementListTest.php index 1842ca963..f3bb8f2bb 100644 --- a/tests/VObject/ElementListTest.php +++ b/tests/VObject/ElementListTest.php @@ -22,9 +22,12 @@ public function testIterate() $count = 0; foreach ($elemList as $key => $subcomponent) { ++$count; - $this->assertInstanceOf('Sabre\\VObject\\Component', $subcomponent); + $this->assertInstanceOf(Component::class, $subcomponent); + + if (3 === $count) { + $this->assertEquals(2, $key); + } } $this->assertEquals(3, $count); - $this->assertEquals(2, $key); } } diff --git a/tests/VObject/EmptyParameterTest.php b/tests/VObject/EmptyParameterTest.php index 213e69ab8..52fe878e2 100644 --- a/tests/VObject/EmptyParameterTest.php +++ b/tests/VObject/EmptyParameterTest.php @@ -20,7 +20,7 @@ public function testRead() $vcard = Reader::read($input); - $this->assertInstanceOf('Sabre\\VObject\\Component\\VCard', $vcard); + $this->assertInstanceOf(Component\VCard::class, $vcard); $vcard = $vcard->convert(\Sabre\VObject\Document::VCARD30); $vcard = $vcard->serialize(); diff --git a/tests/VObject/EmptyValueIssueTest.php b/tests/VObject/EmptyValueIssueTest.php index 91a4d84f6..0798d9c4a 100644 --- a/tests/VObject/EmptyValueIssueTest.php +++ b/tests/VObject/EmptyValueIssueTest.php @@ -17,7 +17,7 @@ public function testDecodeValue() BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT -DESCRIPTION:This is a descpription\\nwith a linebreak and a \\; \\, and : +DESCRIPTION:This is a description\\nwith a linebreak and a \\; \\, and : END:VEVENT END:VCALENDAR ICS; @@ -25,6 +25,6 @@ public function testDecodeValue() $vobj = Reader::read($input); // Before this bug was fixed, getValue() would return nothing. - $this->assertEquals("This is a descpription\nwith a linebreak and a ; , and :", $vobj->VEVENT->DESCRIPTION->getValue()); + $this->assertEquals("This is a description\nwith a linebreak and a ; , and :", $vobj->VEVENT->DESCRIPTION->getValue()); } } diff --git a/tests/VObject/FreeBusyGeneratorTest.php b/tests/VObject/FreeBusyGeneratorTest.php index 323cf632b..4700a2800 100644 --- a/tests/VObject/FreeBusyGeneratorTest.php +++ b/tests/VObject/FreeBusyGeneratorTest.php @@ -22,15 +22,13 @@ public function testGeneratorBaseObject() $this->assertEquals('PUBLISH', $result->METHOD->getValue()); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidArg() { + $this->expectException(\InvalidArgumentException::class); $gen = new FreeBusyGenerator( new \DateTime('2012-01-01'), new \DateTime('2012-12-31'), - new \StdClass() + new \stdClass() ); } diff --git a/tests/VObject/ICalendar/AttachParseTest.php b/tests/VObject/ICalendar/AttachParseTest.php index a32a2462e..e6e3d8685 100644 --- a/tests/VObject/ICalendar/AttachParseTest.php +++ b/tests/VObject/ICalendar/AttachParseTest.php @@ -3,6 +3,7 @@ namespace Sabre\VObject\ICalendar; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Property\Uri; use Sabre\VObject\Reader; class AttachParseTest extends TestCase @@ -23,7 +24,7 @@ public function testParseAttach() $vcal = Reader::read($vcal); $prop = $vcal->VEVENT->ATTACH; - $this->assertInstanceOf('Sabre\\VObject\\Property\\URI', $prop); + $this->assertInstanceOf(Uri::class, $prop); $this->assertEquals('ftp://example.com/pub/reports/r-960812.ps', $prop->getValue()); } } diff --git a/tests/VObject/ITip/BrokerAttendeeReplyTest.php b/tests/VObject/ITip/BrokerAttendeeReplyTest.php index cd0c7bb66..87d1e9ebf 100644 --- a/tests/VObject/ITip/BrokerAttendeeReplyTest.php +++ b/tests/VObject/ITip/BrokerAttendeeReplyTest.php @@ -68,6 +68,124 @@ public function testAccepted() $this->parse($oldMessage, $newMessage, $expected); } + public function testAcceptedWithTz() + { + $oldMessage = << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => <<parse($oldMessage, $newMessage, $expected); + } + public function testRecurringReply() { $oldMessage = << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => <<parse($oldMessage, $newMessage, $expected); + } + + public function testNewEventWithReply(): void + { + $oldMessage = null; + + $newMessage = << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => 'One', + 'recipient' => 'mailto:strunk@example.org', + 'recipientName' => 'Strunk', + 'message' => <<parse($oldMessage, $newMessage, $expected); } + + /** + * Test that adding EXDATE entries when oldEventInfo doesn't have exdate + * (e.g., when updating a newly created event) doesn't cause a TypeError. + * + * This tests the scenario where an attendee receives a new recurring event + * invitation with EXDATE entries already present. Since there's no old calendar, + * oldEventInfo is initialized with only minimal keys and lacks 'exdate'. + */ + public function testAddExdateWithoutPreviousExdate(): void + { + // No old message - this is a new event invitation + $oldMessage = null; + + // New message: recurring event with EXDATE already present + $newMessage = << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => null, + 'recipient' => 'mailto:organizer@example.org', + 'recipientName' => null, + 'message' => << 'foobar', + 'method' => 'REPLY', + 'component' => 'VEVENT', + 'sender' => 'mailto:one@example.org', + 'senderName' => null, + 'recipient' => 'mailto:organizer@example.org', + 'recipientName' => null, + 'message' => <<parse($oldMessage, $newMessage, $expected); + } } diff --git a/tests/VObject/ITip/BrokerDeleteEventTest.php b/tests/VObject/ITip/BrokerDeleteEventTest.php index 88f30ec18..ec119be4c 100644 --- a/tests/VObject/ITip/BrokerDeleteEventTest.php +++ b/tests/VObject/ITip/BrokerDeleteEventTest.php @@ -305,6 +305,73 @@ public function testAttendeeDeleteCancelledEvent() $this->parse($oldMessage, $newMessage, $expected, 'mailto:one@example.org'); } + public function testOrganizerDeleteEventWithAttendeeAndAlarm() + { + + $oldMessage = << 'foobar', + 'method' => 'CANCEL', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:one@example.org', + 'recipientName' => 'One', + 'message' => <<parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); + + } + public function testNoCalendar() { $this->parse(null, null, [], 'mailto:one@example.org'); diff --git a/tests/VObject/ITip/BrokerNewEventTest.php b/tests/VObject/ITip/BrokerNewEventTest.php index 465f4127b..f2d596a7c 100644 --- a/tests/VObject/ITip/BrokerNewEventTest.php +++ b/tests/VObject/ITip/BrokerNewEventTest.php @@ -60,6 +60,7 @@ public function testSimpleInvite() DTEND:20140811T230000Z ORGANIZER;CN=Strunk:mailto:strunk@example.org ATTENDEE;CN=White;PARTSTAT=NEEDS-ACTION:mailto:white@example.org +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS; @@ -80,11 +81,9 @@ public function testSimpleInvite() $this->parse(null, $message, $expected, 'mailto:strunk@example.org'); } - /** - * @expectedException \Sabre\VObject\ITip\ITipException - */ public function testBrokenEventUIDMisMatch() { + $this->expectException(ITipException::class); $message = <<parse(null, $message, [], 'mailto:strunk@example.org'); } - /** - * @expectedException \Sabre\VObject\ITip\ITipException - */ public function testBrokenEventOrganizerMisMatch() { + $this->expectException(ITipException::class); $message = <<parse(null, $message, [], 'mailto:strunk@example.org'); } - /** - * @expectedException \Sabre\VObject\ITip\ITipException - */ public function testMultipleUID() { + $this->expectException(ITipException::class); $message = <<parse(null, $message, [], 'mailto:strunk@example.org'); } - /** - * @expectedException \Sabre\VObject\ITip\SameOrganizerForAllComponentsException - */ public function testChangingOrganizers() { + $this->expectException(SameOrganizerForAllComponentsException::class); $message = <<parse(null, $message, [], 'mailto:strunk@example.org'); } + + public function testAttendeeRemoval(): void + { + $message = << 'foobar', + 'method' => 'REQUEST', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:white@example.org', + 'recipientName' => 'White', + 'message' => $expectedMessage, + ], + ]; + + $this->parse(null, $message, $expected, 'mailto:strunk@example.org'); + } + + public function testSimpleInviteWithAlarm() + { + $message = << 'foobar', + 'method' => 'REQUEST', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:white@example.org', + 'recipientName' => 'White', + 'message' => $expectedMessage, + ], + ]; + $this->parse(null, $message, $expected, 'mailto:strunk@example.org'); + } + } diff --git a/tests/VObject/ITip/BrokerProcessMessageTest.php b/tests/VObject/ITip/BrokerProcessMessageTest.php index 3327be0d9..aadb32c14 100644 --- a/tests/VObject/ITip/BrokerProcessMessageTest.php +++ b/tests/VObject/ITip/BrokerProcessMessageTest.php @@ -118,6 +118,201 @@ public function testCancelNoExistingEvent() $result = $this->process($itip, $old, $expected); } + public function testCancelInstanceOfRecurring() + { + $itip = <<process($itip, $old, $expected); + } + + public function testCancelExistingInstanceOfRecurring() + { + $itip = <<process($itip, $old, $expected); + } + public function testUnsupportedComponent() { $itip = <<process($itip, $old, $expected); } + public function testReplyWithTz() + { + $itip = <<process($itip, $old, $expected); + } + public function testReplyRequestStatus() { $itip = <<process($itip, $old, $expected); } + public function testReplyExistingExceptionRecurrenceIdInUTC(): void + { + $itip = <<process($itip, $old, $expected); + } + public function testReplyNewException() { // This is a reply to 1 instance of a recurring event. This should @@ -274,7 +440,127 @@ public function testReplyNewExceptionTz() $result = $this->process($itip, $old, $expected); } - public function testReplyPartyCrashCreateExcepton() + public function testReplyNewExceptionRecurrenceIdInDifferentTz(): void + { + // This is a reply to 1 instance of a recurring event. This should + // automatically create an exception. + $itip = <<process($itip, $old, $expected); + } + + public function testReplyNewExceptionRecurrenceIdInUTC(): void + { + // This is a reply to 1 instance of a recurring event. This should + // automatically create an exception. + $itip = <<process($itip, $old, $expected); + } + + public function testReplyPartyCrashCreateException() { // IN this test there's a recurring event that has an exception. The // exception is missing the attendee. diff --git a/tests/VObject/ITip/BrokerSignificantChangesTest.php b/tests/VObject/ITip/BrokerSignificantChangesTest.php index a225cb98c..a20d55025 100644 --- a/tests/VObject/ITip/BrokerSignificantChangesTest.php +++ b/tests/VObject/ITip/BrokerSignificantChangesTest.php @@ -105,4 +105,112 @@ public function testSignificantChangesRRuleOrderNoChange() $this->parse($old, $new, $expected, 'mailto:martin@fruux.com'); } + + /** + * Check significant changes detection (no change). + * Reordering of the attendees should not be a significant change (#540) + * https://github.com/sabre-io/vobject/issues/540. + */ + public function testSignificantChangesAttendeesOrderNoChange() + { + $old = << false]; + $expected[] = ['significantChange' => false]; + + $this->parse($old, $new, $expected, 'mailto:martin@fruux.com'); + } + + /** + * Check significant changes detection (no change). + * Reordering of vevent in a recurring event with exceptions should + * not be a significant change + * https://github.com/sabre-io/vobject/issues/542. + */ + public function testSignificantChangesVeventOrderNoChange() + { + $vevent1 = << false]]; + + $this->parse($old, $new, $expected, 'mailto:martin@fruux.com'); + } } diff --git a/tests/VObject/ITip/BrokerTester.php b/tests/VObject/ITip/BrokerTester.php index fcccd75d8..9e9956e03 100644 --- a/tests/VObject/ITip/BrokerTester.php +++ b/tests/VObject/ITip/BrokerTester.php @@ -45,8 +45,11 @@ public function process($input, $existingObject = null, $expected = false) $vcal = Reader::read($input); + $mainComponent = new \Sabre\VObject\Component\VEvent($vcal, 'VEVENT'); foreach ($vcal->getComponents() as $mainComponent) { - break; + if ('VEVENT' === $mainComponent->name) { + break; + } } $message = new Message(); diff --git a/tests/VObject/ITip/BrokerUpdateEventTest.php b/tests/VObject/ITip/BrokerUpdateEventTest.php index 8706633a8..3343eb7d6 100644 --- a/tests/VObject/ITip/BrokerUpdateEventTest.php +++ b/tests/VObject/ITip/BrokerUpdateEventTest.php @@ -96,6 +96,7 @@ public function testInviteChange() ATTENDEE;CN=Three;PARTSTAT=NEEDS-ACTION:mailto:three@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -125,6 +126,7 @@ public function testInviteChange() ATTENDEE;CN=Three;PARTSTAT=NEEDS-ACTION:mailto:three@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -186,6 +188,7 @@ public function testInviteChangeFromNonSchedulingToSchedulingObject() ATTENDEE;CN=One;PARTSTAT=NEEDS-ACTION:mailto:one@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -279,8 +282,6 @@ public function testNoAttendees() END:VCALENDAR ICS; - $version = \Sabre\VObject\Version::VERSION; - $expected = []; $this->parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); } @@ -344,6 +345,7 @@ public function testRemoveInstance() DTEND;TZID=America/Toronto:20140716T130000 RRULE:FREQ=WEEKLY EXDATE;TZID=America/Toronto:20140724T120000 +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -450,6 +452,7 @@ public function testInviteChangeSignificantChange() ATTENDEE;CN=Three;PARTSTAT=NEEDS-ACTION:mailto:three@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -479,6 +482,7 @@ public function testInviteChangeSignificantChange() ATTENDEE;CN=Three;PARTSTAT=NEEDS-ACTION:mailto:three@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -546,6 +550,7 @@ public function testInviteNoChange() ATTENDEE;CN=One;PARTSTAT=NEEDS-ACTION:mailto:one@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -613,6 +618,7 @@ public function testInviteNoChangeForceSend() ATTENDEE;CN=One;PARTSTAT=NEEDS-ACTION:mailto:one@example.org DTSTART:20140716T120000Z DTEND:20140716T130000Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS @@ -797,6 +803,249 @@ public function testInviteChangeExdateOrder() RRULE:FREQ=WEEKLY EXDATE:20150101T160000Z EXDATE:20150108T160000Z,20141225T160000Z +DTSTAMP:**ANY** +END:VEVENT +END:VCALENDAR +ICS + ], + ]; + + $this->parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); + } + + public function testInviteStatusCancelled(): void + { + $oldMessage = << 'foobar', + 'method' => 'CANCEL', + 'component' => 'VEVENT', + 'message' => <<parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); + } + + /* + * When EXDATE is added by Broker, it needs to be in the correct + * timezone + */ + + public function testExdateTimezone(): void + { + $oldMessage = << 'foobar', + 'method' => 'REQUEST', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:one@example.org', + 'recipientName' => 'One', + 'significantChange' => true, + 'message' => <<parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); + } + + /* + * When EXDATE is added by Broker, it needs to be in the correct + * timezone, also in case UTC is used + */ + + public function testExdateTimezoneUTC(): void + { + $oldMessage = << 'foobar', + 'method' => 'REQUEST', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:one@example.org', + 'recipientName' => 'One', + 'significantChange' => true, + 'message' => <<parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); } + + function testSimpleInviteWithAlarm() { + $oldMessage = << 'foobar', + 'method' => 'REQUEST', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:white@example.org', + 'recipientName' => 'White', + 'message' => $expectedMessage, + ], + ]; + $this->parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); + } + + function testLocationChange() { + + $oldMessage = << 'foobar', + 'method' => 'REQUEST', + 'component' => 'VEVENT', + 'sender' => 'mailto:strunk@example.org', + 'senderName' => 'Strunk', + 'recipient' => 'mailto:two@example.org', + 'recipientName' => 'Two', + 'significantChange' => false, + 'hasChange' => true, + 'message' => <<parse($oldMessage, $newMessage, $expected, 'mailto:strunk@example.org'); + + } } diff --git a/tests/VObject/ITip/EvolutionTest.php b/tests/VObject/ITip/EvolutionTest.php index db4317366..686a94db1 100644 --- a/tests/VObject/ITip/EvolutionTest.php +++ b/tests/VObject/ITip/EvolutionTest.php @@ -844,7 +844,6 @@ public function testNewEvolutionEvent() END:VTIMEZONE BEGIN:VEVENT UID:20140813T153116Z-12176-1000-1065-6@johnny-lubuntu -DTSTAMP:20140813T142829Z DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/America/Toronto:201408 15T110000 DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/America/Toronto:20140815 @@ -1701,7 +1700,6 @@ public function testNewEvolutionEvent() END:VTIMEZONE BEGIN:VEVENT UID:20140813T153116Z-12176-1000-1065-6@johnny-lubuntu -DTSTAMP:20140813T142829Z DTSTART;TZID=/freeassociation.sourceforge.net/Tzfile/America/Toronto:201408 15T110000 DTEND;TZID=/freeassociation.sourceforge.net/Tzfile/America/Toronto:20140815 @@ -1719,6 +1717,7 @@ public function testNewEvolutionEvent() TRUE;LANGUAGE=en:MAILTO:dominik@fruux.com CREATED:20140813T153211Z LAST-MODIFIED:20140813T155353Z +DTSTAMP:**ANY** END:VEVENT END:VCALENDAR ICS; diff --git a/tests/VObject/Issue153Test.php b/tests/VObject/Issue153Test.php index 309025041..7bb37e841 100644 --- a/tests/VObject/Issue153Test.php +++ b/tests/VObject/Issue153Test.php @@ -8,7 +8,7 @@ class Issue153Test extends TestCase { public function testRead() { - $obj = Reader::read(file_get_contents(dirname(__FILE__).'/issue153.vcf')); + $obj = Reader::read(file_get_contents(__DIR__.'/issue153.vcf')); $this->assertEquals('Test Benutzer', (string) $obj->FN); } } diff --git a/tests/VObject/Issue36WorkAroundTest.php b/tests/VObject/Issue36WorkAroundTest.php index 332aace39..1afd3d184 100644 --- a/tests/VObject/Issue36WorkAroundTest.php +++ b/tests/VObject/Issue36WorkAroundTest.php @@ -34,6 +34,6 @@ public function testWorkaround() // If this does not throw an exception, it's all good. $it = new Recur\EventIterator($obj, '1833bd44-188b-405c-9f85-1a12105318aa'); - $this->assertInstanceOf('Sabre\\VObject\\Recur\\EventIterator', $it); + $this->assertInstanceOf(Recur\EventIterator::class, $it); } } diff --git a/tests/VObject/Issue467Test.php b/tests/VObject/Issue467Test.php new file mode 100644 index 000000000..27f1b49bc --- /dev/null +++ b/tests/VObject/Issue467Test.php @@ -0,0 +1,56 @@ +VEVENT->VALARM->TRIGGER->getDateInterval()); + } +} diff --git a/tests/VObject/Issue64Test.php b/tests/VObject/Issue64Test.php index 9dc2bb984..10ec24a0f 100644 --- a/tests/VObject/Issue64Test.php +++ b/tests/VObject/Issue64Test.php @@ -8,12 +8,12 @@ class Issue64Test extends TestCase { public function testRead() { - $vcard = Reader::read(file_get_contents(dirname(__FILE__).'/issue64.vcf')); + $vcard = Reader::read(file_get_contents(__DIR__.'/issue64.vcf')); $vcard = $vcard->convert(\Sabre\VObject\Document::VCARD30); $vcard = $vcard->serialize(); $converted = Reader::read($vcard); - $this->assertInstanceOf('Sabre\\VObject\\Component\\VCard', $converted); + $this->assertInstanceOf(Component\VCard::class, $converted); } } diff --git a/tests/VObject/Issue96Test.php b/tests/VObject/Issue96Test.php index 22d1fed2f..88803a3e0 100644 --- a/tests/VObject/Issue96Test.php +++ b/tests/VObject/Issue96Test.php @@ -18,7 +18,7 @@ public function testRead() VCF; $vcard = Reader::read($input, Reader::OPTION_FORGIVING); - $this->assertInstanceOf('Sabre\\VObject\\Component\\VCard', $vcard); + $this->assertInstanceOf(Component\VCard::class, $vcard); $this->assertEquals('http://www.example.org', $vcard->URL->getValue()); } } diff --git a/tests/VObject/IssueUndefinedIndexTest.php b/tests/VObject/IssueUndefinedIndexTest.php index 5a70b0885..7ed214a19 100644 --- a/tests/VObject/IssueUndefinedIndexTest.php +++ b/tests/VObject/IssueUndefinedIndexTest.php @@ -6,11 +6,9 @@ class IssueUndefinedIndexTest extends TestCase { - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testRead() { + $this->expectException(ParseException::class); $input = << 'WEEKLY', 'byday' => ['MO', 'TU'], ], ], [ - 'x-bool', new \StdClass(), 'boolean', true, + 'x-bool', new \stdClass(), 'boolean', true, ], [ - 'x-time', new \StdClass(), 'time', '08:00:00', + 'x-time', new \stdClass(), 'time', '08:00:00', ], [ - 'attach', new \StdClass(), 'binary', base64_encode('attachment'), + 'attach', new \stdClass(), 'binary', base64_encode('attachment'), ], [ 'request-status', - new \StdClass(), + new \stdClass(), 'text', ['2.0', 'Success'], ], [ 'request-status', - new \StdClass(), + new \stdClass(), 'text', ['3.7', 'Invalid Calendar User', 'ATTENDEE:mailto:jsmith@example.org'], ], [ 'dtend', - new \StdClass(), + new \stdClass(), 'date-time', '2015-01-08T13:30:00', ], diff --git a/tests/VObject/JCardTest.php b/tests/VObject/JCardTest.php index 2100a07a9..1864f666d 100644 --- a/tests/VObject/JCardTest.php +++ b/tests/VObject/JCardTest.php @@ -48,25 +48,25 @@ public function testToJCard() [ [ 'version', - new \StdClass(), + new \stdClass(), 'text', '4.0', ], [ 'prodid', - new \StdClass(), + new \stdClass(), 'text', '-//Sabre//Sabre VObject '.Version::VERSION.'//EN', ], [ 'uid', - new \StdClass(), + new \stdClass(), 'text', 'foo', ], [ 'bday', - new \StdClass(), + new \stdClass(), 'date-and-or-time', '1985-04-07', ], @@ -80,25 +80,25 @@ public function testToJCard() ], [ 'bday', - new \StdClass(), + new \stdClass(), 'date-time', '1979-12-25T02:00:00', ], [ 'rev', - new \StdClass(), + new \stdClass(), 'timestamp', '1995-10-31T22:27:10Z', ], [ 'lang', - new \StdClass(), + new \stdClass(), 'language-tag', 'nl', ], [ 'n', - new \StdClass(), + new \stdClass(), 'text', ['Last', 'First', 'Middle', '', ''], ], @@ -120,7 +120,7 @@ public function testToJCard() ], [ 'adr', - new \StdClass(), + new \stdClass(), 'text', [ '', @@ -134,55 +134,55 @@ public function testToJCard() ], [ 'x-truncated', - new \StdClass(), + new \stdClass(), 'date', '--12-25', ], [ 'x-time-local', - new \StdClass(), + new \stdClass(), 'time', '12:30:00', ], [ 'x-time-utc', - new \StdClass(), + new \stdClass(), 'time', '12:30:00Z', ], [ 'x-time-offset', - new \StdClass(), + new \stdClass(), 'time', '12:30:00-08:00', ], [ 'x-time-reduced', - new \StdClass(), + new \stdClass(), 'time', '23', ], [ 'x-time-truncated', - new \StdClass(), + new \stdClass(), 'time', '--30', ], [ 'x-karma-points', - new \StdClass(), + new \stdClass(), 'integer', 42, ], [ 'x-grade', - new \StdClass(), + new \stdClass(), 'float', 1.3, ], [ 'tz', - new \StdClass(), + new \stdClass(), 'utc-offset', '-05:00', ], diff --git a/tests/VObject/Parser/JsonTest.php b/tests/VObject/Parser/JsonTest.php index 587f55f70..e1c701489 100644 --- a/tests/VObject/Parser/JsonTest.php +++ b/tests/VObject/Parser/JsonTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Sabre\VObject; +use Sabre\VObject\ParseException; class JsonTest extends TestCase { @@ -14,25 +15,25 @@ public function testRoundTripJCard() [ [ 'version', - new \StdClass(), + new \stdClass(), 'text', '4.0', ], [ 'prodid', - new \StdClass(), + new \stdClass(), 'text', '-//Sabre//Sabre VObject '.VObject\Version::VERSION.'//EN', ], [ 'uid', - new \StdClass(), + new \stdClass(), 'text', 'foo', ], [ 'bday', - new \StdClass(), + new \stdClass(), 'date-and-or-time', '1985-04-07', ], @@ -46,25 +47,25 @@ public function testRoundTripJCard() ], [ 'bday', - new \StdClass(), + new \stdClass(), 'date-time', '1979-12-25T02:00:00', ], [ 'rev', - new \StdClass(), + new \stdClass(), 'timestamp', '1995-10-31T22:27:10Z', ], [ 'lang', - new \StdClass(), + new \stdClass(), 'language-tag', 'nl', ], [ 'n', - new \StdClass(), + new \stdClass(), 'text', ['Last', 'First', 'Middle', '', ''], ], @@ -86,7 +87,7 @@ public function testRoundTripJCard() ], [ 'adr', - new \StdClass(), + new \stdClass(), 'text', [ '', @@ -101,55 +102,55 @@ public function testRoundTripJCard() [ 'x-truncated', - new \StdClass(), + new \stdClass(), 'date', '--12-25', ], [ 'x-time-local', - new \StdClass(), + new \stdClass(), 'time', '12:30:00', ], [ 'x-time-utc', - new \StdClass(), + new \stdClass(), 'time', '12:30:00Z', ], [ 'x-time-offset', - new \StdClass(), + new \stdClass(), 'time', '12:30:00-08:00', ], [ 'x-time-reduced', - new \StdClass(), + new \stdClass(), 'time', '23', ], [ 'x-time-truncated', - new \StdClass(), + new \stdClass(), 'time', '--30', ], [ 'x-karma-points', - new \StdClass(), + new \stdClass(), 'integer', 42, ], [ 'x-grade', - new \StdClass(), + new \stdClass(), 'float', 1.3, ], [ 'tz', - new \StdClass(), + new \stdClass(), 'utc-offset', '-05:00', ], @@ -203,19 +204,19 @@ public function testRoundTripJCal() [ [ 'version', - new \StdClass(), + new \stdClass(), 'text', '2.0', ], [ 'prodid', - new \StdClass(), + new \stdClass(), 'text', '-//Sabre//Sabre VObject '.VObject\Version::VERSION.'//EN', ], [ 'calscale', - new \StdClass(), + new \stdClass(), 'text', 'GREGORIAN', ], @@ -224,25 +225,25 @@ public function testRoundTripJCal() ['vevent', [ [ - 'uid', new \StdClass(), 'text', 'foo', + 'uid', new \stdClass(), 'text', 'foo', ], [ - 'dtstart', new \StdClass(), 'date', '2013-05-26', + 'dtstart', new \stdClass(), 'date', '2013-05-26', ], [ - 'duration', new \StdClass(), 'duration', 'P1D', + 'duration', new \stdClass(), 'duration', 'P1D', ], [ - 'categories', new \StdClass(), 'text', 'home', 'testing', + 'categories', new \stdClass(), 'text', 'home', 'testing', ], [ - 'created', new \StdClass(), 'date-time', '2013-05-26T18:10:00Z', + 'created', new \stdClass(), 'date-time', '2013-05-26T18:10:00Z', ], [ - 'attach', new \StdClass(), 'binary', base64_encode('attachment'), + 'attach', new \stdClass(), 'binary', base64_encode('attachment'), ], [ - 'attendee', new \StdClass(), 'cal-address', 'mailto:armin@example.org', + 'attendee', new \stdClass(), 'cal-address', 'mailto:armin@example.org', ], [ 'attendee', @@ -254,41 +255,41 @@ public function testRoundTripJCal() 'mailto:dominik@example.org', ], [ - 'geo', new \StdClass(), 'float', [51.96668, 7.61876], + 'geo', new \stdClass(), 'float', [51.96668, 7.61876], ], [ - 'sequence', new \StdClass(), 'integer', 5, + 'sequence', new \stdClass(), 'integer', 5, ], [ - 'freebusy', new \StdClass(), 'period', ['2013-05-26T21:02:13', 'PT1H'], ['2013-06-26T12:00:00', '2013-06-26T13:00:00'], + 'freebusy', new \stdClass(), 'period', ['2013-05-26T21:02:13', 'PT1H'], ['2013-06-26T12:00:00', '2013-06-26T13:00:00'], ], [ - 'url', new \StdClass(), 'uri', 'http://example.org/', + 'url', new \stdClass(), 'uri', 'http://example.org/', ], [ - 'tzoffsetfrom', new \StdClass(), 'utc-offset', '+05:00', + 'tzoffsetfrom', new \stdClass(), 'utc-offset', '+05:00', ], [ - 'rrule', new \StdClass(), 'recur', [ + 'rrule', new \stdClass(), 'recur', [ 'freq' => 'WEEKLY', 'byday' => ['MO', 'TU'], ], ], [ - 'x-bool', new \StdClass(), 'boolean', true, + 'x-bool', new \stdClass(), 'boolean', true, ], [ - 'x-time', new \StdClass(), 'time', '08:00:00', + 'x-time', new \stdClass(), 'time', '08:00:00', ], [ 'request-status', - new \StdClass(), + new \stdClass(), 'text', ['2.0', 'Success'], ], [ 'request-status', - new \StdClass(), + new \stdClass(), 'text', ['3.7', 'Invalid Calendar User', 'ATTENDEE:mailto:jsmith@example.org'], ], @@ -297,7 +298,7 @@ public function testRoundTripJCal() ['valarm', [ [ - 'action', new \StdClass(), 'text', 'DISPLAY', + 'action', new \stdClass(), 'text', 'DISPLAY', ], ], [], @@ -358,7 +359,7 @@ public function testParseStreamArg() 'vcard', [ [ - 'FN', new \StdClass(), 'text', 'foo', + 'FN', new \stdClass(), 'text', 'foo', ], ], ]; @@ -371,17 +372,15 @@ public function testParseStreamArg() $this->assertEquals('foo', $result->FN->getValue()); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testParseInvalidData() { + $this->expectException(ParseException::class); $json = new Json(); $input = [ 'vlist', [ [ - 'FN', new \StdClass(), 'text', 'foo', + 'FN', new \stdClass(), 'text', 'foo', ], ], ]; diff --git a/tests/VObject/Parser/MimeDirTest.php b/tests/VObject/Parser/MimeDirTest.php index 671c23064..02f30c2c7 100644 --- a/tests/VObject/Parser/MimeDirTest.php +++ b/tests/VObject/Parser/MimeDirTest.php @@ -3,6 +3,8 @@ namespace Sabre\VObject\Parser; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\ParseException; /** * Note that most MimeDir related tests can actually be found in the ReaderTest @@ -10,13 +12,11 @@ */ class MimeDirTest extends TestCase { - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testParseError() { + $this->expectException(ParseException::class); $mimeDir = new MimeDir(); - $mimeDir->parse(fopen(__FILE__, 'a')); + $mimeDir->parse(fopen(__FILE__, 'a+')); } public function testDecodeLatin1() @@ -80,20 +80,16 @@ public function testDontDecodeLatin1() $this->assertEquals("umlaut u - \xFC", $vcard->FN->getValue()); } - /** - * @expectedException \InvalidArgumentException - */ public function testDecodeUnsupportedCharset() { + $this->expectException(\InvalidArgumentException::class); $mimeDir = new MimeDir(); $mimeDir->setCharset('foobar'); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testDecodeUnsupportedInlineCharset() { + $this->expectException(ParseException::class); $vcard = <<parse($vcard); } + public function provideEmptyParserInput(): array + { + return [ + [null, 'No input provided to parse'], + ['', 'End of document reached prematurely'], + ]; + } + + /** + * @dataProvider provideEmptyParserInput + */ + public function testParseEmpty($input, $expectedExceptionMessage): void + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage($expectedExceptionMessage); + $mimeDir = new MimeDir(); + $mimeDir->parse($input); + } + public function testDecodeWindows1252() { $vcard = <<assertEquals('Euro', $vcard->FN->getValue()); $this->assertEquals('Test2', $vcard->N->getValue()); } + + public function testParsingTwiceSameContent() + { + $card = <<parse($card); + // we can do a simple assertion here. As long as we don't get an exception, everything is fine + $this->assertEquals('20220612', $vcard->VEVENT->DTSTART->getValue()); + } + + /** + * @covers \Sabre\VObject\Parser\MimeDir::readProperty + * @dataProvider provideBrokenVCalendar + * + * @param string $vcalendar + * + * @return void + */ + public function testBrokenMultilineContentDoesNotBreakImportWhenSetToIgnoreBrokenLines($vcalendar) + { + $mimeDir = new MimeDir(null, MimeDir::OPTION_IGNORE_INVALID_LINES); + $vcalendar = $mimeDir->parse($vcalendar); + $this->assertInstanceOf(VCalendar::class, $vcalendar); + } + + /** + * @covers \Sabre\VObject\Parser\MimeDir::readProperty + * @dataProvider provideBrokenVCalendar + * + * @param string $vcalendar + * + * @return void + */ + public function testBrokenMultilineContentDoesBreakImport($vcalendar) + { + $mimeDir = new MimeDir(); + $this->expectException(ParseException::class); + $mimeDir->parse($vcalendar); + } + + public function provideBrokenVCalendar() + { + return [[<<parse($iCal); + self::assertEquals('test', $vevent->VEVENT->{0}->getValue()); + } + + public function testInvalidParameter(): void + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Invalid Mimedir file. Line starting at 3: Missing parameter name for parameter value "value2"'); + $vcard = <<parse($vcard); + + echo $vcard->serialize(); + } } diff --git a/tests/VObject/Parser/QuotedPrintableTest.php b/tests/VObject/Parser/QuotedPrintableTest.php index 7ec16a5a5..7cadb46eb 100644 --- a/tests/VObject/Parser/QuotedPrintableTest.php +++ b/tests/VObject/Parser/QuotedPrintableTest.php @@ -3,6 +3,7 @@ namespace Sabre\VObject\Parser; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Component; use Sabre\VObject\Reader; class QuotedPrintableTest extends TestCase @@ -13,7 +14,7 @@ public function testReadQuotedPrintableSimple() $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCARD', $result->name); $this->assertEquals(1, count($result->children())); $this->assertEquals('Aachen', $this->getPropertyValue($result->LABEL)); @@ -24,7 +25,7 @@ public function testReadQuotedPrintableNewlineSoft() $data = "BEGIN:VCARD\r\nLABEL;ENCODING=QUOTED-PRINTABLE:Aa=\r\n ch=\r\n en\r\nEND:VCARD"; $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCARD', $result->name); $this->assertEquals(1, count($result->children())); $this->assertEquals('Aachen', $this->getPropertyValue($result->LABEL)); @@ -35,7 +36,7 @@ public function testReadQuotedPrintableNewlineHard() $data = "BEGIN:VCARD\r\nLABEL;ENCODING=QUOTED-PRINTABLE:Aachen=0D=0A=\r\n Germany\r\nEND:VCARD"; $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCARD', $result->name); $this->assertEquals(1, count($result->children())); $this->assertEquals("Aachen\r\nGermany", $this->getPropertyValue($result->LABEL)); @@ -46,7 +47,7 @@ public function testReadQuotedPrintableCompatibilityMS() $data = "BEGIN:VCARD\r\nLABEL;ENCODING=QUOTED-PRINTABLE:Aachen=0D=0A=\r\nDeutschland:okay\r\nEND:VCARD"; $result = Reader::read($data, Reader::OPTION_FORGIVING); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCARD', $result->name); $this->assertEquals(1, count($result->children())); $this->assertEquals("Aachen\r\nDeutschland:okay", $this->getPropertyValue($result->LABEL)); diff --git a/tests/VObject/Parser/XmlTest.php b/tests/VObject/Parser/XmlTest.php index e520185ba..46ee30ce2 100644 --- a/tests/VObject/Parser/XmlTest.php +++ b/tests/VObject/Parser/XmlTest.php @@ -262,7 +262,7 @@ public function testRFC6321Example2() /** * iCalendar Stream. */ - public function testRFC6321Section3_2() + public function testRFC6321Section3Part2() { $this->assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( @@ -466,7 +466,7 @@ public function testRFC6321Section3_4_1_3() /** * Values, Binary. */ - public function testRFC6321Section3_6_1() + public function testRFC6321Section3Part6Part1() { $this->assertXMLEqualsToMimeDir( <<assertXMLEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( << with a positive and a non-negative numbers. - $this->testRFC6321Section3_4_1_2(); + $this->testRFC6321Section3Part4Part1Part2(); } /** * Values, Integer. */ - public function testRFC6321Section3_6_8() + public function testRFC6321Section3Part6Part8() { $this->assertXMLEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( @@ -1259,7 +1259,7 @@ public function testRFC6351Section5Group() /** * Extensibility. */ - public function testRFC6351Section5_1_NoNamespace() + public function testRFC6351Section5Part1NoNamespace() { $this->assertXMLEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<assertXMLReflexivelyEqualsToMimeDir( <<expectException(\InvalidArgumentException::class); $vcard = new VObject\Component\VCard(['VERSION' => '3.0']); $vcard->add('PHOTO', ['a', 'b']); } diff --git a/tests/VObject/Property/FloatTest.php b/tests/VObject/Property/FloatTest.php index c5237c47b..0ba02470e 100644 --- a/tests/VObject/Property/FloatTest.php +++ b/tests/VObject/Property/FloatTest.php @@ -14,7 +14,7 @@ public function testMimeDir() $result = $mimeDir->parse($input); - $this->assertInstanceOf('Sabre\VObject\Property\FloatValue', $result->{'X-FLOAT'}); + $this->assertInstanceOf(FloatValue::class, $result->{'X-FLOAT'}); $this->assertEquals([ 0.234, diff --git a/tests/VObject/Property/ICalendar/CalAddressTest.php b/tests/VObject/Property/ICalendar/CalAddressTest.php index a907daf5c..e7490869f 100644 --- a/tests/VObject/Property/ICalendar/CalAddressTest.php +++ b/tests/VObject/Property/ICalendar/CalAddressTest.php @@ -25,6 +25,8 @@ public function values() return [ ['mailto:a@b.com', 'mailto:a@b.com'], ['mailto:a@b.com', 'MAILTO:a@b.com'], + ['mailto:a@b.com', 'mailto:A@B.COM'], + ['mailto:a@b.com', 'MAILTO:A@B.COM'], ['/foo/bar', '/foo/bar'], ]; } diff --git a/tests/VObject/Property/ICalendar/DateTimeTest.php b/tests/VObject/Property/ICalendar/DateTimeTest.php index 33525ff33..cedbfa13b 100644 --- a/tests/VObject/Property/ICalendar/DateTimeTest.php +++ b/tests/VObject/Property/ICalendar/DateTimeTest.php @@ -4,12 +4,13 @@ use PHPUnit\Framework\TestCase; use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\InvalidDataException; class DateTimeTest extends TestCase { protected $vcal; - public function setUp() + public function setUp(): void { $this->vcal = new VCalendar(); } @@ -176,7 +177,7 @@ public function testGetDateTimeCached() { $tz = new \DateTimeZone('Europe/Amsterdam'); $dt = new \DateTimeImmutable('1985-07-04 01:30:00', $tz); - $dt->setTimeZone($tz); + $dt = $dt->setTimeZone($tz); $elem = $this->vcal->createProperty('DTSTART'); $elem->setDateTime($dt); @@ -256,11 +257,9 @@ public function testGetDateTimeDateLOCALTZ() $this->assertEquals('Europe/Amsterdam', $dt->getTimeZone()->getName()); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testGetDateTimeDateInvalid() { + $this->expectException(InvalidDataException::class); $elem = $this->vcal->createProperty('DTSTART', 'bla'); $dt = $elem->getDateTime(); } diff --git a/tests/VObject/Property/ICalendar/RecurTest.php b/tests/VObject/Property/ICalendar/RecurTest.php index 818840605..7fe683b55 100644 --- a/tests/VObject/Property/ICalendar/RecurTest.php +++ b/tests/VObject/Property/ICalendar/RecurTest.php @@ -4,6 +4,7 @@ use PHPUnit\Framework\TestCase; use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Node; use Sabre\VObject\Reader; @@ -16,7 +17,7 @@ public function testParts() $vcal = new VCalendar(); $recur = $vcal->add('RRULE', 'FREQ=Daily'); - $this->assertInstanceOf('Sabre\VObject\Property\ICalendar\Recur', $recur); + $this->assertInstanceOf(Recur::class, $recur); $this->assertEquals(['FREQ' => 'DAILY'], $recur->getParts()); $recur->setParts(['freq' => 'MONTHLY']); @@ -24,11 +25,9 @@ public function testParts() $this->assertEquals(['FREQ' => 'MONTHLY'], $recur->getParts()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetValueBadVal() { + $this->expectException(\InvalidArgumentException::class); $vcal = new VCalendar(); $recur = $vcal->add('RRULE', 'FREQ=Daily'); $recur->setValue(new \Exception()); @@ -196,6 +195,14 @@ public function testValidateStripNoFreq() ); } + public function testUnrepairableRRule() + { + $this->expectException(InvalidDataException::class); + $calendar = new VCalendar(); + $property = $calendar->createProperty('RRULE', 'IAmNotARRule'); + $property->validate(Node::REPAIR); + } + public function testValidateInvalidByMonthRruleWithRepair() { $calendar = new VCalendar(); diff --git a/tests/VObject/Property/UriTest.php b/tests/VObject/Property/UriTest.php index 4ab32a736..d3d0e0f9c 100644 --- a/tests/VObject/Property/UriTest.php +++ b/tests/VObject/Property/UriTest.php @@ -21,6 +21,6 @@ public function testAlwaysEncodeUriVCalendar() END:VCALENDAR ICS; $output = Reader::read($input)->serialize(); - $this->assertContains('URL;VALUE=URI:http://example.org/', $output); + $this->assertStringContainsString('URL;VALUE=URI:http://example.org/', $output); } } diff --git a/tests/VObject/Property/VCard/DateAndOrTimeTest.php b/tests/VObject/Property/VCard/DateAndOrTimeTest.php index a59411e01..f21b408a1 100644 --- a/tests/VObject/Property/VCard/DateAndOrTimeTest.php +++ b/tests/VObject/Property/VCard/DateAndOrTimeTest.php @@ -105,11 +105,9 @@ public function testSetPartsDateTimeImmutable() $this->assertEquals('20140402T183700Z', $prop->getValue()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetPartsTooMany() { + $this->expectException(\InvalidArgumentException::class); $vcard = new VObject\Component\VCard(); $prop = $vcard->createProperty('BDAY'); diff --git a/tests/VObject/Property/VCard/LanguageTagTest.php b/tests/VObject/Property/VCard/LanguageTagTest.php index ffb65f434..54106ffe8 100644 --- a/tests/VObject/Property/VCard/LanguageTagTest.php +++ b/tests/VObject/Property/VCard/LanguageTagTest.php @@ -14,7 +14,7 @@ public function testMimeDir() $result = $mimeDir->parse($input); - $this->assertInstanceOf('Sabre\VObject\Property\VCard\LanguageTag', $result->LANG); + $this->assertInstanceOf(LanguageTag::class, $result->LANG); $this->assertEquals('nl', $result->LANG->getValue()); @@ -31,7 +31,7 @@ public function testChangeAndSerialize() $result = $mimeDir->parse($input); - $this->assertInstanceOf('Sabre\VObject\Property\VCard\LanguageTag', $result->LANG); + $this->assertInstanceOf(LanguageTag::class, $result->LANG); // This replicates what the vcard converter does and triggered a bug in // the past. $result->LANG->setValue(['de']); diff --git a/tests/VObject/Property/VCard/PhoneNumberTest.php b/tests/VObject/Property/VCard/PhoneNumberTest.php new file mode 100644 index 000000000..668bc7e4c --- /dev/null +++ b/tests/VObject/Property/VCard/PhoneNumberTest.php @@ -0,0 +1,19 @@ +assertInstanceOf(PhoneNumber::class, $vCard->TEL); + $this->assertEquals('PHONE-NUMBER', $vCard->TEL->getValueType()); + $this->assertEquals($input, $vCard->serialize()); + } +} diff --git a/tests/VObject/PropertyTest.php b/tests/VObject/PropertyTest.php index 0bc8afc90..08238379c 100644 --- a/tests/VObject/PropertyTest.php +++ b/tests/VObject/PropertyTest.php @@ -5,6 +5,7 @@ use PHPUnit\Framework\TestCase; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\Component\VCard; +use Sabre\VObject\Property\ICalendar\DateTime; class PropertyTest extends TestCase { @@ -62,7 +63,7 @@ public function testParameterGet() $property = $cal->createProperty('propname', 'propvalue'); $property['paramname'] = 'paramvalue'; - $this->assertInstanceOf('Sabre\\VObject\\Parameter', $property['paramname']); + $this->assertInstanceOf(Parameter::class, $property['paramname']); } public function testParameterNotExists() @@ -71,7 +72,7 @@ public function testParameterNotExists() $property = $cal->createProperty('propname', 'propvalue'); $property['paramname'] = 'paramvalue'; - $this->assertInternalType('null', $property['foo']); + $this->assertNull($property['foo']); } public function testParameterMultiple() @@ -81,7 +82,7 @@ public function testParameterMultiple() $property['paramname'] = 'paramvalue'; $property->add('paramname', 'paramvalue'); - $this->assertInstanceOf('Sabre\\VObject\\Parameter', $property['paramname']); + $this->assertInstanceOf(Parameter::class, $property['paramname']); $this->assertEquals(2, count($property['paramname']->getParts())); } @@ -92,7 +93,7 @@ public function testSetParameterAsString() $property['paramname'] = 'paramvalue'; $this->assertEquals(1, count($property->parameters())); - $this->assertInstanceOf('Sabre\\VObject\\Parameter', $property->parameters['PARAMNAME']); + $this->assertInstanceOf(Parameter::class, $property->parameters['PARAMNAME']); $this->assertEquals('PARAMNAME', $property->parameters['PARAMNAME']->name); $this->assertEquals('paramvalue', $property->parameters['PARAMNAME']->getValue()); } @@ -308,11 +309,10 @@ public function testGetValue() /** * ElementList should reject this. - * - * @expectedException \LogicException */ public function testArrayAccessSetInt() { + $this->expectException(\LogicException::class); $calendar = new VCalendar(); $property = $calendar->createProperty('X-PROP', null); @@ -322,11 +322,10 @@ public function testArrayAccessSetInt() /** * ElementList should reject this. - * - * @expectedException \LogicException */ public function testArrayAccessUnsetInt() { + $this->expectException(\LogicException::class); $calendar = new VCalendar(); $property = $calendar->createProperty('X-PROP', null); @@ -368,6 +367,12 @@ public function testValidateBadEncodingVCard3() $this->assertEquals('ENCODING=BASE64 is not valid for this document type.', $result[0]['message']); $this->assertEquals(3, $result[0]['level']); + + //Validate the reparation of BASE64 formatted vCard v3 + $result = $property->validate(Property::REPAIR); + + $this->assertEquals('ENCODING=BASE64 has been transformed to ENCODING=B.', $result[0]['message']); + $this->assertEquals(1, $result[0]['level']); } public function testValidateBadEncodingVCard21() @@ -381,4 +386,18 @@ public function testValidateBadEncodingVCard21() $this->assertEquals('ENCODING=B is not valid for this document type.', $result[0]['message']); $this->assertEquals(3, $result[0]['level']); } + + public function testUnknownValuesWillBeIgnored(): void + { + $cal = new VCalendar(); + $property = $cal->createProperty('DTSTAMP', '20240101T000000Z', ['VALUE' => 'DATETIME']); + + self::assertEquals("DTSTAMP;VALUE=DATETIME:20240101T000000Z\r\n", $property->serialize()); + + self::assertInstanceOf(DateTime::class, $property); + self::assertCount(1, $property->parameters()); + self::assertInstanceOf(Parameter::class, $property->parameters['VALUE']); + self::assertEquals('VALUE', $property->parameters['VALUE']->name); + self::assertEquals('DATETIME', $property->parameters['VALUE']->getValue()); + } } diff --git a/tests/VObject/ReaderTest.php b/tests/VObject/ReaderTest.php index 06310e80a..cc2838a1a 100644 --- a/tests/VObject/ReaderTest.php +++ b/tests/VObject/ReaderTest.php @@ -12,7 +12,7 @@ public function testReadComponent() $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } @@ -27,7 +27,7 @@ public function testReadStream() $result = Reader::read($stream); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } @@ -38,7 +38,7 @@ public function testReadComponentUnixNewLine() $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } @@ -49,26 +49,22 @@ public function testReadComponentLineFold() $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testReadCorruptComponent() { + $this->expectException(ParseException::class); $data = "BEGIN:VCALENDAR\r\nEND:FOO"; $result = Reader::read($data); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testReadCorruptSubComponent() { + $this->expectException(ParseException::class); $data = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nEND:FOO\r\nEND:VCALENDAR"; $result = Reader::read($data); @@ -80,7 +76,7 @@ public function testReadProperty() $result = Reader::read($data); $result = $result->SUMMARY; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('SUMMARY', $result->name); $this->assertEquals('propValue', $result->getValue()); } @@ -91,7 +87,7 @@ public function testReadPropertyWithNewLine() $result = Reader::read($data); $result = $result->SUMMARY; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('SUMMARY', $result->name); $this->assertEquals("Line1\nLine2\nLine3\\Not the 4th line!", $result->getValue()); } @@ -102,7 +98,7 @@ public function testReadMappedProperty() $result = Reader::read($data); $result = $result->DTSTART; - $this->assertInstanceOf('Sabre\\VObject\\Property\\ICalendar\\DateTime', $result); + $this->assertInstanceOf(Property\ICalendar\DateTime::class, $result); $this->assertEquals('DTSTART', $result->name); $this->assertEquals('20110529', $result->getValue()); } @@ -113,18 +109,21 @@ public function testReadMappedPropertyGrouped() $result = Reader::read($data); $result = $result->DTSTART; - $this->assertInstanceOf('Sabre\\VObject\\Property\\ICalendar\\DateTime', $result); + $this->assertInstanceOf(Property\ICalendar\DateTime::class, $result); $this->assertEquals('DTSTART', $result->name); $this->assertEquals('20110529', $result->getValue()); } - /** - * @expectedException \Sabre\VObject\ParseException - */ - public function testReadBrokenLine() + public function testReadMissingEnd() { - $data = "BEGIN:VCALENDAR\r\nPROPNAME;propValue"; + $data = "BEGIN:VCALENDAR\r\nPROPNAME:propValue"; $result = Reader::read($data); + $this->assertInstanceOf(Component::class, $result); + $this->assertEquals('VCALENDAR', $result->name); + $this->assertEquals(1, count($result->children())); + $this->assertInstanceOf(Property::class, $result->children()[0]); + $this->assertEquals('PROPNAME', $result->children()[0]->name); + $this->assertEquals('propValue', $result->children()[0]->getValue()); } public function testReadPropertyInComponent() @@ -137,10 +136,10 @@ public function testReadPropertyInComponent() $result = Reader::read(implode("\r\n", $data)); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(1, count($result->children())); - $this->assertInstanceOf('Sabre\\VObject\\Property', $result->children()[0]); + $this->assertInstanceOf(Property::class, $result->children()[0]); $this->assertEquals('PROPNAME', $result->children()[0]->name); $this->assertEquals('propValue', $result->children()[0]->getValue()); } @@ -158,13 +157,13 @@ public function testReadNestedComponent() $result = Reader::read(implode("\r\n", $data)); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(1, count($result->children())); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result->children()[0]); + $this->assertInstanceOf(Component::class, $result->children()[0]); $this->assertEquals('VTIMEZONE', $result->children()[0]->name); $this->assertEquals(1, count($result->children()[0]->children())); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result->children()[0]->children()[0]); + $this->assertInstanceOf(Component::class, $result->children()[0]->children()[0]); $this->assertEquals('DAYLIGHT', $result->children()[0]->children()[0]->name); } @@ -175,7 +174,7 @@ public function testReadPropertyParameter() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -190,7 +189,7 @@ public function testReadPropertyRepeatingParameter() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -206,7 +205,7 @@ public function testReadPropertyRepeatingNamelessGuessedParameter() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -222,7 +221,7 @@ public function testReadPropertyNoName() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -238,7 +237,7 @@ public function testReadPropertyParameterExtraColon() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue:anotherrandomstring', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -253,7 +252,7 @@ public function testReadProperty2Parameters() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(2, count($result->parameters())); @@ -270,7 +269,7 @@ public function testReadPropertyParameterQuoted() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -285,7 +284,7 @@ public function testReadPropertyParameterNewLines() $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); @@ -300,7 +299,7 @@ public function testReadPropertyParameterQuotedColon() $result = Reader::read($data); $result = $result->PROPNAME; - $this->assertInstanceOf('Sabre\\VObject\\Property', $result); + $this->assertInstanceOf(Property::class, $result); $this->assertEquals('PROPNAME', $result->name); $this->assertEquals('propValue', $result->getValue()); $this->assertEquals(1, count($result->parameters())); @@ -342,7 +341,7 @@ public function testReadWithInvalidLine() $data = [ 'BEGIN:VCALENDAR', 'DESCRIPTION:propValue', - "Yes, we've actually seen a file with non-idented property values on multiple lines", + "Yes, we've actually seen a file with non-indented property values on multiple lines", 'END:VCALENDAR', ]; @@ -369,11 +368,10 @@ public function testReadWithInvalidLine() /** * Reported as Issue 32. - * - * @expectedException \Sabre\VObject\ParseException */ public function testReadIncompleteFile() { + $this->expectException(ParseException::class); $input = <<expectException(\InvalidArgumentException::class); Reader::read(false); } @@ -417,7 +413,7 @@ public function testReadBOM() $data = chr(0xef).chr(0xbb).chr(0xbf)."BEGIN:VCALENDAR\r\nEND:VCALENDAR"; $result = Reader::read($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } @@ -434,7 +430,7 @@ public function testReadXMLComponent() $result = Reader::readXML($data); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } @@ -455,7 +451,7 @@ public function testReadXMLStream() $result = Reader::readXML($stream); - $this->assertInstanceOf('Sabre\\VObject\\Component', $result); + $this->assertInstanceOf(Component::class, $result); $this->assertEquals('VCALENDAR', $result->name); $this->assertEquals(0, count($result->children())); } diff --git a/tests/VObject/Recur/EventIterator/ByMonthInDailyTest.php b/tests/VObject/Recur/EventIterator/ByMonthInDailyTest.php index 40f09364f..bd1eeb9b6 100644 --- a/tests/VObject/Recur/EventIterator/ByMonthInDailyTest.php +++ b/tests/VObject/Recur/EventIterator/ByMonthInDailyTest.php @@ -1,9 +1,10 @@ assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand(new DateTime('2013-09-28'), new DateTime('2014-09-11')); + $dates = []; foreach ($vcal->VEVENT as $event) { $dates[] = $event->DTSTART->getValue(); } diff --git a/tests/VObject/Recur/EventIterator/BySetPosHangTest.php b/tests/VObject/Recur/EventIterator/BySetPosHangTest.php index 82bd353e0..555f2ffd4 100644 --- a/tests/VObject/Recur/EventIterator/BySetPosHangTest.php +++ b/tests/VObject/Recur/EventIterator/BySetPosHangTest.php @@ -1,9 +1,10 @@ assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand(new DateTime('2015-01-01'), new DateTime('2016-01-01')); + $dates = []; foreach ($vcal->VEVENT as $event) { $dates[] = $event->DTSTART->getValue(); } diff --git a/tests/VObject/Recur/EventIterator/ExpandFloatingTimesTest.php b/tests/VObject/Recur/EventIterator/ExpandFloatingTimesTest.php index 635b0a8c5..605e10dde 100644 --- a/tests/VObject/Recur/EventIterator/ExpandFloatingTimesTest.php +++ b/tests/VObject/Recur/EventIterator/ExpandFloatingTimesTest.php @@ -5,6 +5,7 @@ use DateTime; use DateTimeZone; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Component\VCalendar; use Sabre\VObject\Reader; class ExpandFloatingTimesTest extends TestCase @@ -26,7 +27,7 @@ public function testExpand() ICS; $vcal = Reader::read($input); - $this->assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand(new DateTime('2015-01-01'), new DateTime('2015-01-31')); $output = <<assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand( new DateTime('2015-01-01'), diff --git a/tests/VObject/Recur/EventIterator/HandleRDateExpandTest.php b/tests/VObject/Recur/EventIterator/HandleRDateExpandTest.php index 698c5fe59..548820191 100644 --- a/tests/VObject/Recur/EventIterator/HandleRDateExpandTest.php +++ b/tests/VObject/Recur/EventIterator/HandleRDateExpandTest.php @@ -6,6 +6,7 @@ use DateTimeImmutable; use DateTimeZone; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Component\VCalendar; use Sabre\VObject\Reader; /** @@ -36,7 +37,7 @@ public function testExpand() ICS; $vcal = Reader::read($input); - $this->assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand(new DateTime('2015-01-01'), new DateTime('2015-12-01')); diff --git a/tests/VObject/Recur/EventIterator/IncorrectExpandTest.php b/tests/VObject/Recur/EventIterator/IncorrectExpandTest.php index afc509972..f9fcda442 100644 --- a/tests/VObject/Recur/EventIterator/IncorrectExpandTest.php +++ b/tests/VObject/Recur/EventIterator/IncorrectExpandTest.php @@ -4,6 +4,7 @@ use DateTime; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Component\VCalendar; use Sabre\VObject\Reader; /** @@ -34,7 +35,7 @@ public function testExpand() ICS; $vcal = Reader::read($input); - $this->assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand(new DateTime('2011-01-01'), new DateTime('2014-01-01')); diff --git a/tests/VObject/Recur/EventIterator/InfiniteLoopProblemTest.php b/tests/VObject/Recur/EventIterator/InfiniteLoopProblemTest.php index 2f73d8e37..5546c508d 100644 --- a/tests/VObject/Recur/EventIterator/InfiniteLoopProblemTest.php +++ b/tests/VObject/Recur/EventIterator/InfiniteLoopProblemTest.php @@ -6,11 +6,15 @@ use DateTimeZone; use PHPUnit\Framework\TestCase; use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Recur; class InfiniteLoopProblemTest extends TestCase { - public function setUp() + /** @var VCalendar */ + private $vcal; + + public function setUp(): void { $this->vcal = new VCalendar(); } @@ -73,11 +77,10 @@ public function testYearlyByMonthLoop() * Something, somewhere produced an ics with an interval set to 0. Because * this means we increase the current day (or week, month) by 0, this also * results in an infinite loop. - * - * @expectedException \Sabre\VObject\InvalidDataException */ public function testZeroInterval() { + $this->expectException(InvalidDataException::class); $ev = $this->vcal->createComponent('VEVENT'); $ev->UID = 'uuid'; $ev->DTSTART = '20120824T145700Z'; diff --git a/tests/VObject/Recur/EventIterator/Issue26Test.php b/tests/VObject/Recur/EventIterator/Issue26Test.php index bb4df64df..3313c3ec6 100644 --- a/tests/VObject/Recur/EventIterator/Issue26Test.php +++ b/tests/VObject/Recur/EventIterator/Issue26Test.php @@ -3,16 +3,16 @@ namespace Sabre\VObject\Recur\EventIterator; use PHPUnit\Framework\TestCase; +use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Reader; use Sabre\VObject\Recur\EventIterator; class Issue26Test extends TestCase { - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testExpand() { + $this->expectException(InvalidDataException::class); $input = <<assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $it = new EventIterator($vcal, 'bae5d57a98'); } diff --git a/tests/VObject/Recur/EventIterator/Issue48Test.php b/tests/VObject/Recur/EventIterator/Issue48Test.php index fe4b06755..aef592590 100644 --- a/tests/VObject/Recur/EventIterator/Issue48Test.php +++ b/tests/VObject/Recur/EventIterator/Issue48Test.php @@ -1,10 +1,13 @@ assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); - $it = new Recur\EventIterator($vcal, 'foo'); + $it = new EventIterator($vcal, 'foo'); $result = iterator_to_array($it); diff --git a/tests/VObject/Recur/EventIterator/Issue50Test.php b/tests/VObject/Recur/EventIterator/Issue50Test.php index df9c15519..5c476e6f2 100644 --- a/tests/VObject/Recur/EventIterator/Issue50Test.php +++ b/tests/VObject/Recur/EventIterator/Issue50Test.php @@ -1,10 +1,13 @@ assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); - $it = new Recur\EventIterator($vcal, '1aef0b27-3d92-4581-829a-11999dd36724'); + $it = new EventIterator($vcal, '1aef0b27-3d92-4581-829a-11999dd36724'); $result = []; foreach ($it as $instance) { diff --git a/tests/VObject/Recur/EventIterator/MainTest.php b/tests/VObject/Recur/EventIterator/MainTest.php index 10782a53a..cf317f3ea 100644 --- a/tests/VObject/Recur/EventIterator/MainTest.php +++ b/tests/VObject/Recur/EventIterator/MainTest.php @@ -6,6 +6,7 @@ use DateTimeZone; use PHPUnit\Framework\TestCase; use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Recur\EventIterator; class MainTest extends TestCase @@ -29,11 +30,11 @@ public function testValues() } /** - * @expectedException \Sabre\VObject\InvalidDataException * @depends testValues */ public function testInvalidFreq() { + $this->expectException(InvalidDataException::class); $vcal = new VCalendar(); $ev = $vcal->createComponent('VEVENT'); $ev->RRULE = 'FREQ=SMONTHLY;INTERVAL=3;UNTIL=20111025T000000Z'; @@ -47,20 +48,16 @@ public function testInvalidFreq() $it = new EventIterator($vcal, (string) $ev->UID); } - /** - * @expectedException \InvalidArgumentException - */ public function testVCalendarNoUID() { + $this->expectException(\InvalidArgumentException::class); $vcal = new VCalendar(); $it = new EventIterator($vcal); } - /** - * @expectedException \InvalidArgumentException - */ public function testVCalendarInvalidUID() { + $this->expectException(\InvalidArgumentException::class); $vcal = new VCalendar(); $it = new EventIterator($vcal, 'foo'); } @@ -1175,7 +1172,7 @@ public function testComplexExclusions() /** * @depends testValues */ - public function testOverridenEvent() + public function testOverriddenEvent() { $vcal = new VCalendar(); @@ -1246,7 +1243,7 @@ public function testOverridenEvent() /** * @depends testValues */ - public function testOverridenEvent2() + public function testOverriddenEvent2() { $vcal = new VCalendar(); @@ -1294,7 +1291,7 @@ public function testOverridenEvent2() /** * @depends testValues */ - public function testOverridenEventNoValuesExpected() + public function testOverriddenEventNoValuesExpected() { $vcal = new VCalendar(); $ev1 = $vcal->createComponent('VEVENT'); @@ -1321,12 +1318,12 @@ public function testOverridenEventNoValuesExpected() $summaries = []; // The reported problem was specifically related to the VCALENDAR - // expansion. In this parcitular case, we had to forward to the 28th of + // expansion. In this particular case, we had to forward to the 28th of // january. $it->fastForward(new DateTimeImmutable('2012-01-28 23:00:00')); - // We stop the loop when it hits the 6th of februari. Normally this - // iterator would hit 24, 25 (overriden from 31) and 7 feb but because + // We stop the loop when it hits the 6th of February. Normally this + // iterator would hit 24, 25 (overridden from 31) and 7 feb but because // we 'filter' from the 28th till the 6th, we should get 0 results. while ($it->valid() && $it->getDTStart() < new DateTimeImmutable('2012-02-06 23:00:00')) { $dates[] = $it->getDTStart(); @@ -1386,10 +1383,10 @@ public function testRDATE() /** * @depends testValues - * @expectedException \InvalidArgumentException */ public function testNoMasterBadUID() { + $this->expectException(\InvalidArgumentException::class); $vcal = new VCalendar(); // ev2 overrides an event, and puts it on 2pm instead. $ev2 = $vcal->createComponent('VEVENT'); diff --git a/tests/VObject/Recur/EventIterator/MaxInstancesTest.php b/tests/VObject/Recur/EventIterator/MaxInstancesTest.php index d0571ee82..6314b3b5a 100644 --- a/tests/VObject/Recur/EventIterator/MaxInstancesTest.php +++ b/tests/VObject/Recur/EventIterator/MaxInstancesTest.php @@ -5,15 +5,14 @@ use DateTime; use PHPUnit\Framework\TestCase; use Sabre\VObject\Reader; +use Sabre\VObject\Recur\MaxInstancesExceededException; use Sabre\VObject\Settings; class MaxInstancesTest extends TestCase { - /** - * @expectedException \Sabre\VObject\Recur\MaxInstancesExceededException - */ public function testExceedMaxRecurrences() { + $this->expectException(MaxInstancesExceededException::class); $input = <<assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $vcal = $vcal->expand(new DateTime('2011-01-01'), new DateTime('2015-01-01')); diff --git a/tests/VObject/Recur/EventIterator/NoInstancesTest.php b/tests/VObject/Recur/EventIterator/NoInstancesTest.php index b3e5a11fa..d89afd197 100644 --- a/tests/VObject/Recur/EventIterator/NoInstancesTest.php +++ b/tests/VObject/Recur/EventIterator/NoInstancesTest.php @@ -1,17 +1,18 @@ expectException(NoInstancesException::class); $input = <<assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); + $this->assertInstanceOf(VCalendar::class, $vcal); $it = new EventIterator($vcal, 'foo'); } diff --git a/tests/VObject/Recur/EventIterator/OverrideDurationTest.php b/tests/VObject/Recur/EventIterator/OverrideDurationTest.php new file mode 100644 index 000000000..f25ef13d9 --- /dev/null +++ b/tests/VObject/Recur/EventIterator/OverrideDurationTest.php @@ -0,0 +1,52 @@ +getComponents()); + + $this->assertEquals($eventIterator->current()->format('Y-m-d H:i:s'), '2021-05-17 09:00:00', 'recur event start time'); + $this->assertEquals($eventIterator->getDtEnd()->format('Y-m-d H:i:s'), '2021-05-17 10:00:00', 'recur event end time'); + + $eventIterator->next(); + $this->assertEquals($eventIterator->current()->format('Y-m-d H:i:s'), '2021-05-18 09:00:00', 'recur event start time'); + $this->assertEquals($eventIterator->getDtEnd()->format('Y-m-d H:i:s'), '2021-05-18 10:00:00', 'recur event end time'); + + $eventIterator->next(); + $this->assertEquals($eventIterator->current()->format('Y-m-d H:i:s'), '2021-05-19 09:00:00', 'overridden event start time'); + $this->assertEquals($eventIterator->getDtEnd()->format('Y-m-d H:i:s'), '2021-05-19 12:00:00', 'overridden event end time'); + + $eventIterator->next(); + $this->assertEquals($eventIterator->current()->format('Y-m-d H:i:s'), '2021-05-20 09:00:00', 'recur event start time'); + $this->assertEquals($eventIterator->getDtEnd()->format('Y-m-d H:i:s'), '2021-05-20 10:00:00', 'recur event end time'); + } +} diff --git a/tests/VObject/Recur/EventIterator/OverrideFirstEventTest.php b/tests/VObject/Recur/EventIterator/OverrideFirstEventTest.php index 8773c168c..150a13980 100644 --- a/tests/VObject/Recur/EventIterator/OverrideFirstEventTest.php +++ b/tests/VObject/Recur/EventIterator/OverrideFirstEventTest.php @@ -1,6 +1,6 @@ parse( + 'FREQ=HOURLY;INTERVAL=2;COUNT=5', + $start, + $expected, + null, + 'Europe/Zurich' + ); + } + + public function dst2HourlyTransitionProvider(): iterable + { + yield 'On transition start' => [ + 'Start' => '2023-03-26 00:00:00', + 'Expected' => [ + '2023-03-26 00:00:00', + '2023-03-26 03:00:00', + '2023-03-26 04:00:00', + '2023-03-26 06:00:00', + '2023-03-26 08:00:00', + ], + ]; + yield 'During transition' => [ + 'Start' => '2023-03-26 00:15:00', + 'Expected' => [ + '2023-03-26 00:15:00', + '2023-03-26 03:15:00', + '2023-03-26 04:15:00', + '2023-03-26 06:15:00', + '2023-03-26 08:15:00', + ], + ]; + yield 'On transition end' => [ + 'Start' => '2023-03-26 01:00:00', + 'Expected' => [ + '2023-03-26 01:00:00', + '2023-03-26 03:00:00', + '2023-03-26 05:00:00', + '2023-03-26 07:00:00', + '2023-03-26 09:00:00', + ], + ]; + yield 'After transition end' => [ + 'Start' => '2023-03-26 01:15:00', + 'Expected' => [ + '2023-03-26 01:15:00', + '2023-03-26 03:15:00', + '2023-03-26 05:15:00', + '2023-03-26 07:15:00', + '2023-03-26 09:15:00', + ], + ]; + } + + /** + * @dataProvider dst6HourlyTransitionProvider + */ + public function testHourlyOnDstTransition(string $start, array $expected): void + { + $this->parse( + 'FREQ=HOURLY;INTERVAL=6;COUNT=5', + $start, + $expected, + null, + 'Europe/Zurich' + ); + } + + public function dst6HourlyTransitionProvider(): iterable + { + yield 'On transition start' => [ + 'Start' => '2023-03-25 20:00:00', + 'Expected' => [ + '2023-03-25 20:00:00', + '2023-03-26 03:00:00', + '2023-03-26 08:00:00', + '2023-03-26 14:00:00', + '2023-03-26 20:00:00', + ], + ]; + yield 'During transition' => [ + 'Start' => '2023-03-25 20:15:00', + 'Expected' => [ + '2023-03-25 20:15:00', + '2023-03-26 03:15:00', + '2023-03-26 08:15:00', + '2023-03-26 14:15:00', + '2023-03-26 20:15:00', + ], + ]; + yield 'On transition end' => [ + 'Start' => '2023-03-25 21:00:00', + 'Expected' => [ + '2023-03-25 21:00:00', + '2023-03-26 03:00:00', + '2023-03-26 09:00:00', + '2023-03-26 15:00:00', + '2023-03-26 21:00:00', + ], + ]; + yield 'After transition end' => [ + 'Start' => '2023-03-25 21:15:00', + 'Expected' => [ + '2023-03-25 21:15:00', + '2023-03-26 03:15:00', + '2023-03-26 09:15:00', + '2023-03-26 15:15:00', + '2023-03-26 21:15:00', + ], + ]; + } + public function testDaily() { $this->parse( @@ -146,6 +263,82 @@ public function testDailyByMonth() ); } + /** + * This test can take some seconds to complete. + * The "large" annotation means phpunit will let it run for + * up to 60 seconds by default. + * + * @large + */ + public function testDailyBySetPosLoop() + { + $this->parse( + 'FREQ=DAILY;INTERVAL=7;BYDAY=MO', + '2022-03-15', + [ + ], + '2022-05-01' + ); + } + + /** + * @dataProvider dstDailyTransitionProvider + */ + public function testDailyOnDstTransition(string $start, array $expected): void + { + $this->parse( + 'FREQ=DAILY;INTERVAL=1;COUNT=5', + $start, + $expected, + null, + 'Europe/Zurich' + ); + } + + public function dstDailyTransitionProvider(): iterable + { + yield 'On transition start' => [ + 'Start' => '2023-03-24 02:00:00', + 'Expected' => [ + '2023-03-24 02:00:00', + '2023-03-25 02:00:00', + '2023-03-26 03:00:00', + '2023-03-27 02:00:00', + '2023-03-28 02:00:00', + ], + ]; + yield 'During transition' => [ + 'Start' => '2023-03-24 02:15:00', + 'Expected' => [ + '2023-03-24 02:15:00', + '2023-03-25 02:15:00', + '2023-03-26 03:15:00', + '2023-03-27 02:15:00', + '2023-03-28 02:15:00', + ], + ]; + yield 'On transition end' => [ + 'Start' => '2023-03-24 03:00:00', + 'Expected' => [ + '2023-03-24 03:00:00', + '2023-03-25 03:00:00', + '2023-03-26 03:00:00', + '2023-03-27 03:00:00', + '2023-03-28 03:00:00', + ], + ]; + yield 'After transition end' => [ + 'Start' => '2023-03-24 03:15:00', + 'Expected' => [ + '2023-03-24 03:15:00', + '2023-03-25 03:15:00', + '2023-03-26 03:15:00', + '2023-03-27 03:15:00', + '2023-03-28 03:15:00', + ], + ]; + } + public function testWeekly() { $this->parse( @@ -249,6 +442,110 @@ public function testWeeklyByDaySpecificHour() ); } + public function testWeeklyByDaySpecificHourOnDstTransition(): void + { + $this->parse( + 'FREQ=WEEKLY;INTERVAL=2;BYDAY=SA,SU', + '2023-03-11 02:30:00', + [ + '2023-03-11 02:30:00', + '2023-03-12 02:30:00', + '2023-03-25 02:30:00', + '2023-03-26 03:30:00', + '2023-04-08 02:30:00', + '2023-04-09 02:30:00', + ], + null, + 'Europe/Zurich' + ); + } + + public function testWeeklyByDayByHourOnDstTransition(): void + { + $this->parse( + 'FREQ=WEEKLY;INTERVAL=2;BYDAY=SA,SU;WKST=MO;BYHOUR=2,14', + '2023-03-11 02:00:00', + [ + '2023-03-11 02:00:00', + '2023-03-11 14:00:00', + '2023-03-12 02:00:00', + '2023-03-12 14:00:00', + '2023-03-25 02:00:00', + '2023-03-25 14:00:00', + // 02:00:00 does not exist on 2023-03-26 because of summer-time start. + // The current implementation logic does not schedule a recurrence on + // the morning of 2023-03-26. But maybe it should schedule one at 03:00:00. + // The RFC is silent about the required behavior in this case. + // '2023-03-26 03:00:00', + '2023-03-26 14:00:00', + '2023-04-08 02:00:00', + '2023-04-08 14:00:00', + '2023-04-09 02:00:00', + '2023-04-09 14:00:00', + ], + null, + 'Europe/Zurich' + ); + } + + /** + * @dataProvider dstWeeklyTransitionProvider + */ + public function testWeeklyOnDstTransition(string $start, array $expected): void + { + $this->parse( + 'FREQ=WEEKLY;INTERVAL=1;COUNT=5', + $start, + $expected, + null, + 'Europe/Zurich' + ); + } + + public function dstWeeklyTransitionProvider(): iterable + { + yield 'On transition start' => [ + 'Start' => '2023-03-12 02:00:00', + 'Expected' => [ + '2023-03-12 02:00:00', + '2023-03-19 02:00:00', + '2023-03-26 03:00:00', + '2023-04-02 02:00:00', + '2023-04-09 02:00:00', + ], + ]; + yield 'During transition' => [ + 'Start' => '2023-03-12 02:15:00', + 'Expected' => [ + '2023-03-12 02:15:00', + '2023-03-19 02:15:00', + '2023-03-26 03:15:00', + '2023-04-02 02:15:00', + '2023-04-09 02:15:00', + ], + ]; + yield 'On transition end' => [ + 'Start' => '2023-03-12 03:00:00', + 'Expected' => [ + '2023-03-12 03:00:00', + '2023-03-19 03:00:00', + '2023-03-26 03:00:00', + '2023-04-02 03:00:00', + '2023-04-09 03:00:00', + ], + ]; + yield 'After transition end' => [ + 'Start' => '2023-03-12 03:15:00', + 'Expected' => [ + '2023-03-12 03:15:00', + '2023-03-19 03:15:00', + '2023-03-26 03:15:00', + '2023-04-02 03:15:00', + '2023-04-09 03:15:00', + ], + ]; + } + public function testMonthly() { $this->parse( @@ -264,7 +561,7 @@ public function testMonthly() ); } - public function testMonlthyEndOfMonth() + public function testMonthlyEndOfMonth() { $this->parse( 'FREQ=MONTHLY;INTERVAL=2;COUNT=12', @@ -305,6 +602,26 @@ public function testMonthlyByMonthDay() ); } + public function testMonthlyByMonthDayDstTransition(): void + { + $this->parse( + 'FREQ=MONTHLY;INTERVAL=1;COUNT=8;BYMONTHDAY=1,26', + '2023-01-01 02:15:00', + [ + '2023-01-01 02:15:00', + '2023-01-26 02:15:00', + '2023-02-01 02:15:00', + '2023-02-26 02:15:00', + '2023-03-01 02:15:00', + '2023-03-26 03:15:00', + '2023-04-01 02:15:00', + '2023-04-26 02:15:00', + ], + null, + 'Europe/Zurich' + ); + } + public function testMonthlyByDay() { $this->parse( @@ -331,6 +648,58 @@ public function testMonthlyByDay() ); } + public function testMonthlyByDayUntil() + { + $this->parse( + 'FREQ=MONTHLY;INTERVAL=1;BYDAY=WE;WKST=WE;UNTIL=20210317T000000Z', + '2021-02-10 00:00:00', + [ + '2021-02-10 00:00:00', + '2021-02-17 00:00:00', + '2021-02-24 00:00:00', + '2021-03-03 00:00:00', + '2021-03-10 00:00:00', + '2021-03-17 00:00:00', + ] + ); + } + + public function testMonthlyByDayOnDstTransition(): void + { + $this->parse( + 'FREQ=MONTHLY;INTERVAL=2;COUNT=13;BYDAY=SU', + '2023-01-01 02:30:00', + [ + '2023-01-01 02:30:00', + '2023-01-08 02:30:00', + '2023-01-15 02:30:00', + '2023-01-22 02:30:00', + '2023-01-29 02:30:00', + '2023-03-05 02:30:00', + '2023-03-12 02:30:00', + '2023-03-19 02:30:00', + '2023-03-26 03:30:00', + '2023-05-07 02:30:00', + '2023-05-14 02:30:00', + '2023-05-21 02:30:00', + '2023-05-28 02:30:00', + ], + null, + 'Europe/Zurich' + ); + } + + public function testMonthlyByDayUntilWithImpossibleNextOccurrence() + { + $this->parse( + 'FREQ=MONTHLY;INTERVAL=1;BYDAY=2WE;BYMONTHDAY=2;WKST=WE;UNTIL=20210317T000000Z', + '2021-02-10 00:00:00', + [ + '2021-02-10 00:00:00', + ] + ); + } + public function testMonthlyByDayByMonthDay() { $this->parse( @@ -371,6 +740,74 @@ public function testMonthlyByDayBySetPos() ); } + /** + * @dataProvider dstMonthlyTransitionProvider + */ + public function testMonthlyOnDstTransition(string $start, array $expected): void + { + $this->parse( + 'FREQ=MONTHLY;INTERVAL=1;COUNT=5', + $start, + $expected, + null, + 'Europe/Zurich' + ); + } + + public function dstMonthlyTransitionProvider(): iterable + { + yield 'On transition start' => [ + 'Start' => '2023-01-26 02:00:00', + 'Expected' => [ + '2023-01-26 02:00:00', + '2023-02-26 02:00:00', + '2023-03-26 03:00:00', + '2023-04-26 02:00:00', + '2023-05-26 02:00:00', + ], + ]; + yield 'During transition' => [ + 'Start' => '2023-01-26 02:15:00', + 'Expected' => [ + '2023-01-26 02:15:00', + '2023-02-26 02:15:00', + '2023-03-26 03:15:00', + '2023-04-26 02:15:00', + '2023-05-26 02:15:00', + ], + ]; + yield 'On transition end' => [ + 'Start' => '2023-01-26 03:00:00', + 'Expected' => [ + '2023-01-26 03:00:00', + '2023-02-26 03:00:00', + '2023-03-26 03:00:00', + '2023-04-26 03:00:00', + '2023-05-26 03:00:00', + ], + ]; + yield 'After transition end' => [ + 'Start' => '2023-01-26 03:15:00', + 'Expected' => [ + '2023-01-26 03:15:00', + '2023-02-26 03:15:00', + '2023-03-26 03:15:00', + '2023-04-26 03:15:00', + '2023-05-26 03:15:00', + ], + ]; + yield 'During transition on 31st day of month' => [ + 'Start' => '2024-01-31 02:15:00', + 'Expected' => [ + '2024-01-31 02:15:00', + '2024-03-31 03:15:00', + '2024-05-31 02:15:00', + '2024-07-31 02:15:00', + '2024-08-31 02:15:00', + ], + ]; + } + public function testYearly() { $this->parse( @@ -422,11 +859,29 @@ public function testYearlyByMonth() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ + public function testYearlyByMonthOnDstTransition(): void + { + $this->parse( + 'FREQ=YEARLY;COUNT=8;INTERVAL=2;BYMONTH=3,9', + '2019-03-26 02:30:00', + [ + '2019-03-26 02:30:00', + '2019-09-26 02:30:00', + '2021-03-26 02:30:00', + '2021-09-26 02:30:00', + '2023-03-26 03:30:00', + '2023-09-26 02:30:00', + '2025-03-26 02:30:00', + '2025-09-26 02:30:00', + ], + null, + 'Europe/Zurich' + ); + } + public function testYearlyByMonthInvalidValue1() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;COUNT=6;BYMONTHDAY=24;BYMONTH=0', '2011-04-07 00:00:00', @@ -434,11 +889,9 @@ public function testYearlyByMonthInvalidValue1() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testYearlyByMonthInvalidValue2() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;COUNT=6;BYMONTHDAY=24;BYMONTH=bla', '2011-04-07 00:00:00', @@ -446,11 +899,9 @@ public function testYearlyByMonthInvalidValue2() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testYearlyByMonthManyInvalidValues() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;COUNT=6;BYMONTHDAY=24;BYMONTH=0,bla', '2011-04-07 00:00:00', @@ -458,11 +909,9 @@ public function testYearlyByMonthManyInvalidValues() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testYearlyByMonthEmptyValue() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;COUNT=6;BYMONTHDAY=24;BYMONTH=', '2011-04-07 00:00:00', @@ -488,19 +937,61 @@ public function testYearlyByMonthByDay() ); } + public function testYearlyByMonthByDayOnDstTransition(): void + { + $this->parse( + 'FREQ=YEARLY;COUNT=13;INTERVAL=2;BYMONTH=3;BYDAY=SU', + '2021-03-07 02:30:00', + [ + '2021-03-07 02:30:00', + '2021-03-14 02:30:00', + '2021-03-21 02:30:00', + '2021-03-28 03:30:00', + '2023-03-05 02:30:00', + '2023-03-12 02:30:00', + '2023-03-19 02:30:00', + '2023-03-26 03:30:00', + '2025-03-02 02:30:00', + '2025-03-09 02:30:00', + '2025-03-16 02:30:00', + '2025-03-23 02:30:00', + '2025-03-30 03:30:00', + ], + null, + 'Europe/Zurich' + ); + } + + public function testYearlyNewYearsDay() + { + $this->parse( + 'FREQ=YEARLY;COUNT=7;INTERVAL=2;BYYEARDAY=1', + '2011-01-01 03:07:00', + [ + '2011-01-01 03:07:00', + '2013-01-01 03:07:00', + '2015-01-01 03:07:00', + '2017-01-01 03:07:00', + '2019-01-01 03:07:00', + '2021-01-01 03:07:00', + '2023-01-01 03:07:00', + ] + ); + } + public function testYearlyByYearDay() { $this->parse( 'FREQ=YEARLY;COUNT=7;INTERVAL=2;BYYEARDAY=190', - '2011-07-10 03:07:00', + '2011-07-09 03:07:00', [ - '2011-07-10 03:07:00', - '2013-07-10 03:07:00', - '2015-07-10 03:07:00', - '2017-07-10 03:07:00', - '2019-07-10 03:07:00', - '2021-07-10 03:07:00', - '2023-07-10 03:07:00', + '2011-07-09 03:07:00', + '2013-07-09 03:07:00', + '2015-07-09 03:07:00', + '2017-07-09 03:07:00', + '2019-07-09 03:07:00', + '2021-07-09 03:07:00', + '2023-07-09 03:07:00', ] ); } @@ -521,7 +1012,7 @@ public function testYearlyByYearDayImmutable() $parser->next(); $item = $parser->current(); - $this->assertEquals($item->format('Y-m-d H:i:s'), '2013-07-10 03:07:00'); + $this->assertEquals($item->format('Y-m-d H:i:s'), '2013-07-09 03:07:00'); } public function testYearlyByYearDayMultiple() @@ -531,13 +1022,13 @@ public function testYearlyByYearDayMultiple() '2011-07-10 14:53:11', [ '2011-07-10 14:53:11', - '2011-10-29 14:53:11', - '2014-07-10 14:53:11', - '2014-10-29 14:53:11', - '2017-07-10 14:53:11', - '2017-10-29 14:53:11', - '2020-07-09 14:53:11', - '2020-10-28 14:53:11', + '2011-10-28 14:53:11', + '2014-07-09 14:53:11', + '2014-10-28 14:53:11', + '2017-07-09 14:53:11', + '2017-10-28 14:53:11', + '2020-07-08 14:53:11', + '2020-10-27 14:53:11', ] ); } @@ -549,11 +1040,11 @@ public function testYearlyByYearDayByDay() '2001-04-07 14:53:11', [ '2001-04-07 14:53:11', - '2006-04-08 14:53:11', - '2012-04-07 14:53:11', - '2017-04-08 14:53:11', - '2023-04-08 14:53:11', - '2034-04-08 14:53:11', + '2007-04-07 14:53:11', + '2018-04-07 14:53:11', + '2024-04-06 14:53:11', + '2029-04-07 14:53:11', + '2035-04-07 14:53:11', ] ); } @@ -576,11 +1067,56 @@ public function testYearlyByYearDayNegative() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException + /* + * Verifies that -365 back in the year is usually 1 Jan, but + * in leap years it is 2 Jan. */ + public function testYearlyByYearDayLargeNegative() + { + $this->parse( + 'FREQ=YEARLY;COUNT=8;BYYEARDAY=-365', + '2001-01-01 14:53:11', + [ + '2001-01-01 14:53:11', + '2002-01-01 14:53:11', + '2003-01-01 14:53:11', + '2004-01-02 14:53:11', + '2005-01-01 14:53:11', + '2006-01-01 14:53:11', + '2007-01-01 14:53:11', + '2008-01-02 14:53:11', + ] + ); + } + + /* + * Verifies that -366 back in the year is 1 Jan in a leap year + * Interestingly, it goes back to 31 Dec of the previous year + * when not a leap year. The spec says that -366 is valid, and + * makes no mention of it being valid only in a leap year, so + * the behavior seems reasonable. + */ + public function testYearlyByYearDayMaxNegative() + { + $this->parse( + 'FREQ=YEARLY;COUNT=8;BYYEARDAY=-366', + '2001-01-01 14:53:11', + [ + '2001-01-01 14:53:11', + '2001-12-31 14:53:11', + '2002-12-31 14:53:11', + '2004-01-01 14:53:11', + '2004-12-31 14:53:11', + '2005-12-31 14:53:11', + '2006-12-31 14:53:11', + '2008-01-01 14:53:11', + ] + ); + } + public function testYearlyByYearDayInvalid390() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;COUNT=8;INTERVAL=4;BYYEARDAY=390', '2011-04-07 00:00:00', @@ -589,11 +1125,9 @@ public function testYearlyByYearDayInvalid390() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testYearlyByYearDayInvalid0() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;COUNT=8;INTERVAL=4;BYYEARDAY=0', '2011-04-07 00:00:00', @@ -602,6 +1136,77 @@ public function testYearlyByYearDayInvalid0() ); } + public function testYearlyByDayByWeekNo() + { + $this->parse( + 'FREQ=YEARLY;COUNT=3;BYDAY=MO;BYWEEKNO=13,15,50', + '2021-01-01 00:00:00', + [ + '2021-01-01 00:00:00', + '2021-03-29 00:00:00', + '2021-04-12 00:00:00', + ] + ); + } + + /** + * @dataProvider dstYearlyTransitionProvider + */ + public function testYearlyOnDstTransition(string $start, array $expected): void + { + $this->parse( + 'FREQ=YEARLY;INTERVAL=1;COUNT=5', + $start, + $expected, + null, + 'Europe/Zurich' + ); + } + + public function dstYearlyTransitionProvider(): iterable + { + yield 'On transition start' => [ + 'Start' => '2021-03-26 02:00:00', + 'Expected' => [ + '2021-03-26 02:00:00', + '2022-03-26 02:00:00', + '2023-03-26 03:00:00', + '2024-03-26 02:00:00', + '2025-03-26 02:00:00', + ], + ]; + yield 'During transition' => [ + 'Start' => '2021-03-26 02:15:00', + 'Expected' => [ + '2021-03-26 02:15:00', + '2022-03-26 02:15:00', + '2023-03-26 03:15:00', + '2024-03-26 02:15:00', + '2025-03-26 02:15:00', + ], + ]; + yield 'On transition end' => [ + 'Start' => '2021-03-26 03:00:00', + 'Expected' => [ + '2021-03-26 03:00:00', + '2022-03-26 03:00:00', + '2023-03-26 03:00:00', + '2024-03-26 03:00:00', + '2025-03-26 03:00:00', + ], + ]; + yield 'After transition end' => [ + 'Start' => '2021-03-26 03:15:00', + 'Expected' => [ + '2021-03-26 03:15:00', + '2022-03-26 03:15:00', + '2023-03-26 03:15:00', + '2024-03-26 03:15:00', + '2025-03-26 03:15:00', + ], + ]; + } + public function testFastForward() { // The idea is that we're fast-forwarding too far in the future, so @@ -639,7 +1244,7 @@ public function testFifthTuesdayProblem() * This bug came from a Fruux customer. This would result in a never-ending * request. */ - public function testFastFowardTooFar() + public function testFastForwardTooFar() { $this->parse( 'FREQ=WEEKLY;BYDAY=MO;UNTIL=20090704T205959Z;INTERVAL=1', @@ -770,11 +1375,9 @@ public function testMultipleValidByWeekNo() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testInvalidByWeekNo() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;BYWEEKNO=54', '2011-05-16 00:00:00', @@ -798,15 +1401,82 @@ public function testYearlyByMonthLoop() ); } + /** + * This test can take some seconds to complete. + * The "large" annotation means phpunit will let it run for + * up to 60 seconds by default. + * + * @large + */ + public function testYearlyBySetPosLoop() + { + $this->parse( + 'FREQ=YEARLY;BYMONTH=5;BYSETPOS=3;BYMONTHDAY=3', + '2022-03-03 15:45:00', + [ + ], + '2022-05-01' + ); + } + + /** + * This caused an incorrect date to be returned by the rule iterator when + * start date was not on the rrule list. + * + * @dataProvider yearlyStartDateNotOnRRuleListProvider + */ + public function testYearlyStartDateNotOnRRuleList(string $rule, string $start, array $expected): void + { + $this->parse($rule, $start, $expected); + } + + public function yearlyStartDateNotOnRRuleListProvider(): array + { + // When DTSTART does not match BYMONTH/BYDAY rules, the first occurrence + // should be the first valid date according to the RRULE, not DTSTART itself. + // See: https://github.com/linagora/esn-sabre/issues/50 + return [ + [ + 'FREQ=YEARLY;BYMONTH=6;BYDAY=-1FR;UNTIL=20250901T000000Z', + '2023-09-01 12:00:00', + [ + // DTSTART (2023-09-01) is not in June, so first occurrence is June 2024 + '2024-06-28 12:00:00', + '2025-06-27 12:00:00', + ], + ], + [ + 'FREQ=YEARLY;BYMONTH=6;BYDAY=-1FR;UNTIL=20250901T000000Z', + '2023-06-01 12:00:00', + [ + // DTSTART (2023-06-01) is in June but is not the last Friday, + // so first occurrence is the last Friday of June 2023 + '2023-06-30 12:00:00', + '2024-06-28 12:00:00', + '2025-06-27 12:00:00', + ], + ], + [ + 'FREQ=YEARLY;BYMONTH=6;BYDAY=-1FR;UNTIL=20250901T000000Z', + '2023-05-01 12:00:00', + [ + // DTSTART (2023-05-01) is not in June, so first occurrence is June 2023 + '2023-06-30 12:00:00', + '2024-06-28 12:00:00', + '2025-06-27 12:00:00', + ], + ], + ]; + } + /** * Something, somewhere produced an ics with an interval set to 0. Because * this means we increase the current day (or week, month) by 0, this also * results in an infinite loop. - * - * @expectedException \Sabre\VObject\InvalidDataException */ public function testZeroInterval() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=YEARLY;INTERVAL=0', '2012-08-24 14:57:00', @@ -815,11 +1485,9 @@ public function testZeroInterval() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testInvalidFreq() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=SMONTHLY;INTERVAL=3;UNTIL=20111025T000000Z', '2011-10-07', @@ -827,11 +1495,9 @@ public function testInvalidFreq() ); } - /** - * @expectedException \Sabre\VObject\InvalidDataException - */ public function testByDayBadOffset() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=WEEKLY;INTERVAL=1;COUNT=4;BYDAY=0MO;WKST=SA', '2014-08-01 00:00:00', @@ -898,10 +1564,29 @@ public function testMinusFifthThursday() } /** - * @expectedException \Sabre\VObject\InvalidDataException + * This test can take some seconds to complete. + * The "large" annotation means phpunit will let it run for + * up to 60 seconds by default. + * + * @large */ + public function testNeverEnding() + { + $this->parse( + 'FREQ=MONTHLY;BYDAY=2TU;BYSETPOS=2', + '2015-01-01 00:15:00', + [ + '2015-01-01 00:15:00', + ], + null, + 'UTC', + true + ); + } + public function testUnsupportedPart() { + $this->expectException(InvalidDataException::class); $this->parse( 'FREQ=DAILY;BYWODAN=1', '2014-08-02 00:15:00', @@ -934,7 +1619,30 @@ public function testIteratorFunctions() ); } - public function parse($rule, $start, $expected, $fastForward = null, $tz = 'UTC') + /** + * Test YEARLY recurrence with BYMONTH and BYMONTHDAY where DTSTART month differs from BYMONTH. + * + * Issue: https://github.com/linagora/esn-sabre/issues/50 + * + * When DTSTART is April 11 but RRULE specifies BYMONTH=5 (May) and BYMONTHDAY=15, + * the first occurrence should be May 15, not April 15. + */ + public function testYearlyByMonthByMonthDayDifferentFromDTSTART() + { + $this->parse( + 'FREQ=YEARLY;BYMONTH=5;BYMONTHDAY=15;COUNT=3', + '2030-04-11 10:00:00', + [ + '2030-05-15 10:00:00', + '2031-05-15 10:00:00', + '2032-05-15 10:00:00', + ], + null, + 'Asia/Ho_Chi_Minh' + ); + } + + public function parse($rule, $start, $expected, $fastForward = null, $tz = 'UTC', $runTillTheEnd = false) { $dt = new DateTime($start, new DateTimeZone($tz)); $parser = new RRuleIterator($rule, $dt); @@ -948,7 +1656,7 @@ public function parse($rule, $start, $expected, $fastForward = null, $tz = 'UTC' $item = $parser->current(); $result[] = $item->format('Y-m-d H:i:s'); - if ($parser->isInfinite() && count($result) >= count($expected)) { + if (!$runTillTheEnd && $parser->isInfinite() && count($result) >= count($expected)) { break; } $parser->next(); diff --git a/tests/VObject/Splitter/ICalendarTest.php b/tests/VObject/Splitter/ICalendarTest.php index 5addf9f6d..2788b96d6 100644 --- a/tests/VObject/Splitter/ICalendarTest.php +++ b/tests/VObject/Splitter/ICalendarTest.php @@ -4,12 +4,13 @@ use PHPUnit\Framework\TestCase; use Sabre\VObject; +use Sabre\VObject\ParseException; class ICalendarTest extends TestCase { protected $version; - public function setUp() + public function setUp(): void { $this->version = VObject\Version::VERSION; } @@ -45,11 +46,9 @@ public function testICalendarImportValidEvent() $this->assertEquals([], VObject\Reader::read($return)->validate()); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testICalendarImportWrongType() { + $this->expectException(ParseException::class); $data = <<assertNull($object = $objects->getNext()); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testICalendarImportInvalidEvent() { + $this->expectException(ParseException::class); $data = <<createStream($data); diff --git a/tests/VObject/Splitter/VCardTest.php b/tests/VObject/Splitter/VCardTest.php index d0a234ad9..1402b5094 100644 --- a/tests/VObject/Splitter/VCardTest.php +++ b/tests/VObject/Splitter/VCardTest.php @@ -3,6 +3,7 @@ namespace Sabre\VObject\Splitter; use PHPUnit\Framework\TestCase; +use Sabre\VObject\ParseException; class VCardTest extends TestCase { @@ -33,11 +34,9 @@ public function testVCardImportValidVCard() $this->assertEquals(1, $count); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testVCardImportWrongType() { + $this->expectException(ParseException::class); $event[] = <<assertEquals(4, $count); } + public function testVCardImportVCardNoComponent() + { + $this->expectException(ParseException::class); + $data = <<createStream($data); + + $splitter = new VCard($tempFile); + + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Invalid MimeDir file. Unexpected component: "BEGIN:VCARD" in document type VCARD'); + while ($object = $splitter->getNext()) { + } + } + + public function testVCardImportQuotedPrintableOptionForgivingLeading() + { + $data = <<createStream($data); + + $splitter = new VCard($tempFile, \Sabre\VObject\Parser\Parser::OPTION_FORGIVING); + + $count = 0; + while ($object = $splitter->getNext()) { + ++$count; + } + $this->assertEquals(2, $count); + } + public function testVCardImportEndOfData() { $data = <<assertNull($objects->getNext()); } - /** - * @expectedException \Sabre\VObject\ParseException - */ public function testVCardImportCheckInvalidArgumentException() { + $this->expectException(ParseException::class); $data = <<assertEquals(utf8_encode(chr(0xbf)), $string); + $this->assertEquals(mb_convert_encoding(chr(0xBF), 'UTF-8', 'ISO-8859-1'), $string); } public function testConvertToUTF8IsUTF8() diff --git a/tests/VObject/TimeZoneUtilTest.php b/tests/VObject/TimeZoneUtilTest.php index 2c23af6cb..034031866 100644 --- a/tests/VObject/TimeZoneUtilTest.php +++ b/tests/VObject/TimeZoneUtilTest.php @@ -6,10 +6,9 @@ class TimeZoneUtilTest extends TestCase { - public function setUp() + public function setUp(): void { - // clearning the tz cache - TimezoneUtil::$map = null; + TimeZoneUtil::clean(); } /** @@ -31,14 +30,19 @@ public function testCorrectTZ($timezoneName) public function getMapping() { - TimeZoneUtil::loadTzMaps(); + $map = array_merge( + include __DIR__.'/../../lib/timezonedata/windowszones.php', + include __DIR__.'/../../lib/timezonedata/lotuszones.php', + include __DIR__.'/../../lib/timezonedata/exchangezones.php', + include __DIR__.'/../../lib/timezonedata/php-workaround.php' + ); // PHPUNit requires an array of arrays return array_map( function ($value) { return [$value]; }, - TimeZoneUtil::$map + $map ); } @@ -82,7 +86,7 @@ public function testExchangeMap() $this->assertEquals($ex->getName(), $tz->getName()); } - public function testWetherMicrosoftIsStillInsane() + public function testWhetherMicrosoftIsStillInsane() { $vobj = <<assertEquals($ex->getName(), $tz->getName()); } + public function testEmptyTimeZone() + { + $tz = TimeZoneUtil::getTimeZone(''); + $ex = new \DateTimeZone('UTC'); + $this->assertEquals($ex->getName(), $tz->getName()); + } + public function testWindowsTimeZone() { $tz = TimeZoneUtil::getTimeZone('Eastern Standard Time'); @@ -170,6 +181,17 @@ public function testTimeZoneIdentifiers($tzid) */ public function testTimeZoneBCIdentifiers($tzid) { + /* + * A regression was introduced in PHP 8.1.14 and 8.2.1 + * Timezone ids containing a "+" like "GMT+10" do not work. + * See https://github.com/php/php-src/issues/10218 + * The regression should be fixed in the next patch releases of PHP + * that should be released in Feb 2023. + */ + $versionOfPHP = \phpversion(); + if ((('8.1.14' == $versionOfPHP) || ('8.2.1' == $versionOfPHP)) && \str_contains($tzid, '+')) { + $this->markTestSkipped("Timezone ids containing '+' do not work on PHP $versionOfPHP"); + } $tz = TimeZoneUtil::getTimeZone($tzid); $ex = new \DateTimeZone($tzid); @@ -194,7 +216,7 @@ public function getPHPTimeZoneBCIdentifiers() function ($value) { return [$value]; }, - TimeZoneUtil::getIdentifiersBC() + include __DIR__.'/../../lib/timezonedata/php-bc.php' ); } @@ -210,11 +232,9 @@ public function testTimezoneOffset() $this->assertEquals($ex->getName(), $tz->getName()); } - /** - * @expectedException \InvalidArgumentException - */ public function testTimezoneFail() { + $this->expectException(\InvalidArgumentException::class); $tz = TimeZoneUtil::getTimeZone('FooBar', null, true); } diff --git a/tests/VObject/TimezoneGuesser/FindFromTimezoneMapTest.php b/tests/VObject/TimezoneGuesser/FindFromTimezoneMapTest.php new file mode 100644 index 000000000..abda23823 --- /dev/null +++ b/tests/VObject/TimezoneGuesser/FindFromTimezoneMapTest.php @@ -0,0 +1,65 @@ +find($mapKey); + + self::assertNotNull($tz, "Expected '$mapKey' to resolve to '$expectedOlson'"); + self::assertSame($expectedOlson, $tz->getName()); + } + + public function updatedTimezoneProvider(): array + { + return [ + // windowszones.php + ['FLE Standard Time', 'Europe/Kyiv'], + ['India Standard Time', 'Asia/Kolkata'], + ['Nepal Standard Time', 'Asia/Kathmandu'], + ['Myanmar Standard Time', 'Asia/Yangon'], + ['Greenland Standard Time', 'America/Nuuk'], + ['Argentina Standard Time', 'America/Argentina/Buenos_Aires'], + ['US Eastern Standard Time', 'America/Indiana/Indianapolis'], + // lotuszones.php + ['India', 'Asia/Kolkata'], + ['Myanmar', 'Asia/Yangon'], + // exchangezones.php + ['Kolkata, Chennai, Mumbai, New Delhi, India Standard Time', 'Asia/Kolkata'], + ['Rangoon', 'Asia/Yangon'], + ]; + } + + /** + * Verify that the Microsoft-offset-prefix stripping path still works + * with updated timezone values. + */ + public function testMicrosoftOffsetPrefixStripping(): void + { + $finder = new FindFromTimezoneMap(); + $tz = $finder->find('(UTC+02:00) FLE Standard Time'); + + self::assertNotNull($tz); + self::assertSame('Europe/Kyiv', $tz->getName()); + } + + public function testUnknownTimezoneReturnsNull(): void + { + $finder = new FindFromTimezoneMap(); + + self::assertNull($finder->find('This/Does_Not_Exist')); + } +} diff --git a/tests/VObject/VCardConverterTest.php b/tests/VObject/VCardConverterTest.php index a5be3cc8c..7b31809a5 100644 --- a/tests/VObject/VCardConverterTest.php +++ b/tests/VObject/VCardConverterTest.php @@ -211,6 +211,8 @@ public function testConvertGroupCard() VERSION:3.0 PRODID:foo X-ADDRESSBOOKSERVER-KIND:GROUP +X-ADDRESSBOOKSERVER-MEMBER:mailto:someone@example.com +X-ADDRESSBOOKSERVER-MEMBER:mailto:sometwo@example.com END:VCARD IN; @@ -219,6 +221,8 @@ public function testConvertGroupCard() BEGIN:VCARD VERSION:4.0 KIND:GROUP +MEMBER:mailto:someone@example.com +MEMBER:mailto:sometwo@example.com END:VCARD OUT; @@ -236,6 +240,8 @@ public function testConvertGroupCard() BEGIN:VCARD VERSION:3.0 X-ADDRESSBOOKSERVER-KIND:GROUP +X-ADDRESSBOOKSERVER-MEMBER:mailto:someone@example.com +X-ADDRESSBOOKSERVER-MEMBER:mailto:sometwo@example.com END:VCARD OUT; @@ -294,11 +300,9 @@ public function testBDAYConversion() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testUnknownSourceVCardVersion() { + $this->expectException(\InvalidArgumentException::class); $input = <<convert(Document::VCARD40); } - /** - * @expectedException \InvalidArgumentException - */ public function testUnknownTargetVCardVersion() { + $this->expectException(\InvalidArgumentException::class); $input = <<assertInstanceOf('Sabre\\VObject\\Component\\VCard', $vcard); + $this->assertInstanceOf(Component\VCard::class, $vcard); $vcard = $vcard->convert(Document::VCARD40); $vcard = $vcard->serialize(); @@ -518,4 +520,34 @@ public function testNoLabel() $this->assertEquals($expected, str_replace("\r", '', $vcard)); } + + public function testPhoneNumberValueTypeGetsRemoved() + { + $input = <<convert(Document::VCARD40); + + $this->assertVObjectEqualsVObject( + $output, + $vcard + ); + } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 46e9014cb..2496aa4ff 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -13,13 +13,3 @@ break; } } - -$autoLoader->addPsr4('Sabre\\VObject\\', __DIR__.'/VObject'); - -if (!defined('SABRE_TEMPDIR')) { - define('SABRE_TEMPDIR', __DIR__.'/temp/'); -} - -if (!file_exists(SABRE_TEMPDIR)) { - mkdir(SABRE_TEMPDIR); -} diff --git a/tests/phpunit.xml b/tests/phpunit.xml index 46dad6a3d..16a75c3da 100644 --- a/tests/phpunit.xml +++ b/tests/phpunit.xml @@ -6,18 +6,22 @@ convertWarningsToExceptions="true" beStrictAboutTestsThatDoNotTestAnything="true" beStrictAboutOutputDuringTests="true" - beStrictAboutTestSize="true" + failOnRisky="true" + failOnWarning="true" + enforceTimeLimit="true" > - - VObject/ - + + + + + + . + + ../lib/ - - ../lib/Sabre/VObject/includes.php -