TYPO3 v15 dev-main snapshot ()

This commit is contained in:
2026-08-10 22:31:38 +02:00
commit 4392dbe2ce
142 changed files with 11824 additions and 0 deletions
+213
View File
@@ -0,0 +1,213 @@
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Scheduler\CronCommand;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* This class provides calculations for the cron command format.
*
* @internal not part of TYPO3 Public API
*/
class CronCommand
{
/**
* Normalized sections of the cron command.
* Comma separated lists of integers and the character '*' are allowed.
*
* field lower and upper bound
* ----- --------------
* minute 0-59
* hour 0-23
* day of month 1-31
* month 1-12
* day of week 1-7
*/
protected array $cronCommandSections;
/**
* Timestamp of next execution date.
* This value starts with 'now + 1 minute' if not set externally
* by unit tests. After a call to calculateNextValue() it holds the timestamp of
* the next execution date which matches the cron command restrictions.
*/
protected int $timestamp;
/**
* Constructor
*
* @param string $cronCommand The cron command can hold any combination documented as valid
* @param bool|int $timestamp Optional start time, used in unit tests
*/
public function __construct(string $cronCommand, bool|int $timestamp = false)
{
$cronCommand = NormalizeCommand::normalize($cronCommand);
// Explode cron command to sections
$this->cronCommandSections = GeneralUtility::trimExplode(' ', $cronCommand);
// Initialize the values with the starting time
// This takes care that the calculated time is always in the future
if ($timestamp === false) {
$timestamp = strtotime('+1 minute');
} else {
$timestamp += 60;
}
$this->timestamp = $this->roundTimestamp($timestamp);
}
/**
* Calculates the date of the next execution.
*
* @throws \RuntimeException
*/
public function calculateNextValue(): void
{
$newTimestamp = $this->getTimestamp();
// Calculate next minute and hour field
$loopCount = 0;
while (true) {
$loopCount++;
// If there was no match within two days, cron command is invalid.
// The second day is needed to catch the summertime leap in some countries.
if ($loopCount > 2880) {
throw new \RuntimeException('Unable to determine next execution timestamp: Hour and minute combination is invalid.', 1291494126);
}
if ($this->minuteAndHourMatchesCronCommand($newTimestamp)) {
break;
}
$newTimestamp += 60;
}
$loopCount = 0;
while (true) {
$loopCount++;
// A date must match within the next 4 years, this high number makes
// sure leap year cron command configuration are caught.
// If the loop runs longer than that, the cron command is invalid.
if ($loopCount > 1464) {
throw new \RuntimeException('Unable to determine next execution timestamp: Day of month, month and day of week combination is invalid.', 1291501280);
}
if ($this->dayMatchesCronCommand($newTimestamp)) {
break;
}
$newTimestamp += $this->numberOfSecondsInDay($newTimestamp);
}
$this->timestamp = $newTimestamp;
}
/**
* Get next timestamp
*/
public function getTimestamp(): int
{
return $this->timestamp;
}
/**
* Get cron command sections. Array of strings, each containing either
* a list of comma separated integers or *
*/
public function getCronCommandSections(): array
{
return $this->cronCommandSections;
}
/**
* Determine if current timestamp matches minute and hour cron command restriction.
*/
protected function minuteAndHourMatchesCronCommand(int $timestamp): bool
{
$minute = (int)date('i', $timestamp);
$hour = (int)date('G', $timestamp);
$commandMatch = false;
if ($this->isInCommandList($this->cronCommandSections[0], $minute) && $this->isInCommandList($this->cronCommandSections[1], $hour)) {
$commandMatch = true;
}
return $commandMatch;
}
/**
* Determine if current timestamp matches day of month, month and day of week
* cron command restriction
*/
protected function dayMatchesCronCommand(int $timestamp): bool
{
$dayOfMonth = (int)date('j', $timestamp);
$month = (int)date('n', $timestamp);
$dayOfWeek = (int)date('N', $timestamp);
$isInDayOfMonth = $this->isInCommandList($this->cronCommandSections[2], $dayOfMonth);
$isInMonth = $this->isInCommandList($this->cronCommandSections[3], $month);
$isInDayOfWeek = $this->isInCommandList($this->cronCommandSections[4], $dayOfWeek);
// Quote from vixiecron:
// Note: The day of a command's execution can be specified by two fields — day of month, and day of week.
// If both fields are restricted (i.e., aren't *), the command will be run when either field
// matches the current time. For example, `30 4 1,15 * 5' would cause
// a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.
$isDayOfMonthRestricted = (string)$this->cronCommandSections[2] !== '*';
$isDayOfWeekRestricted = (string)$this->cronCommandSections[4] !== '*';
if (!$isInMonth) {
return false;
}
// If both day-of-month and day-of-week are unrestricted, month match is enough.
if (!$isDayOfMonthRestricted && !$isDayOfWeekRestricted) {
return true;
}
// Otherwise, at least one restriction must match.
return ($isInDayOfMonth && $isDayOfMonthRestricted) || ($isInDayOfWeek && $isDayOfWeekRestricted);
}
/**
* Determine if a given number validates a cron command section. The given cron
* command must be a 'normalized' list with only comma separated integers or '*'
*/
protected function isInCommandList(string $commandExpression, int $numberToMatch): bool
{
if ($commandExpression === '*') {
$inList = true;
} else {
$inList = GeneralUtility::inList($commandExpression, (string)$numberToMatch);
}
return $inList;
}
/**
* Helper method to calculate number of seconds in a day.
*
* This is not always 86400 (60*60*24) and depends on the timezone:
* Some countries like Germany have a summertime / wintertime switch,
* on every last sunday in march clocks are forwarded by one hour (set from 2:00 to 3:00),
* and on last sunday of october they are set back one hour (from 3:00 to 2:00).
* This shortens and lengthens the length of a day by one hour.
*/
protected function numberOfSecondsInDay(int $timestamp): int
{
$now = mktime(0, 0, 0, (int)date('n', $timestamp), (int)date('j', $timestamp), (int)date('Y', $timestamp));
// Make sure to be in next day, even if day has 25 hours
$nextDay = $now + 60 * 60 * 25;
$nextDay = mktime(0, 0, 0, (int)date('n', $nextDay), (int)date('j', $nextDay), (int)date('Y', $nextDay));
return $nextDay - $now;
}
/**
* Round a timestamp down to full minute.
*/
protected function roundTimestamp(int $timestamp): int
{
return (int)(floor($timestamp / 60) * 60);
}
}
+336
View File
@@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Scheduler\CronCommand;
use TYPO3\CMS\Core\Utility\MathUtility;
/**
* Validate and normalize a cron command.
*
* Special fields like three letter weekdays, ranges and steps are substituted
* to a comma separated list of integers. Example:
* '2-4 10-40/10 * mar * fri' will be normalized to '2,4 10,20,30,40 * * 3 1,2'
*
* @internal not part of TYPO3 Public API
*/
class NormalizeCommand
{
/**
* Main API method: Get the cron command and normalize it.
*
* If no exception is thrown, the resulting cron command is validated
* and consists of five whitespace separated fields, which are either
* the letter '*' or a sorted, unique comma separated list of integers.
*
* @throws \InvalidArgumentException cron command is invalid or out of bounds
*/
public static function normalize(string $cronCommand): string
{
$cronCommand = trim($cronCommand);
$cronCommand = self::convertKeywordsToCronCommand($cronCommand);
return self::normalizeFields($cronCommand);
}
/**
* Accept special cron command keywords and convert to standard cron syntax.
* Allowed keywords: @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly
*/
protected static function convertKeywordsToCronCommand(string $cronCommand): string
{
switch ($cronCommand) {
case '@yearly':
case '@annually':
$cronCommand = '0 0 1 1 *';
break;
case '@monthly':
$cronCommand = '0 0 1 * *';
break;
case '@weekly':
$cronCommand = '0 0 * * 0';
break;
case '@daily':
case '@midnight':
$cronCommand = '0 0 * * *';
break;
case '@hourly':
$cronCommand = '0 * * * *';
break;
}
return $cronCommand;
}
/**
* Normalize cron command field to list of integers or *
*/
protected static function normalizeFields(string $cronCommand): string
{
$fieldArray = self::splitFields($cronCommand);
$fieldArray[0] = self::normalizeIntegerField($fieldArray[0]);
$fieldArray[1] = self::normalizeIntegerField($fieldArray[1], 0, 23);
$fieldArray[2] = self::normalizeIntegerField($fieldArray[2], 1, 31);
$fieldArray[3] = self::normalizeMonthAndWeekdayField($fieldArray[3], true);
$fieldArray[4] = self::normalizeMonthAndWeekdayField($fieldArray[4], false);
return implode(' ', $fieldArray);
}
/**
* Split a given cron command like '23 * * * *' to an array with five fields.
*
* @throws \InvalidArgumentException If splitted array does not contain five entries
*/
protected static function splitFields(string $cronCommand): array
{
$fields = explode(' ', $cronCommand);
if (count($fields) !== 5) {
throw new \InvalidArgumentException('Unable to split given cron command to five fields.', 1291227373);
}
return $fields;
}
/**
* Normalize month field.
*/
protected static function normalizeMonthAndWeekdayField(string $expression, bool $isMonthField = true): string
{
if ((string)$expression === '*') {
$fieldValues = '*';
} else {
// Fragment expression by , / and - and substitute three letter code of month and weekday to numbers
$listOfCommaValues = explode(',', $expression);
$fieldArray = [];
foreach ($listOfCommaValues as $listElement) {
if (str_contains($listElement, '/')) {
[$left, $right] = explode('/', $listElement);
if (str_contains($left, '-')) {
[$leftBound, $rightBound] = explode('-', $left);
$leftBound = self::normalizeMonthAndWeekday($leftBound, $isMonthField);
$rightBound = self::normalizeMonthAndWeekday($rightBound, $isMonthField);
$left = $leftBound . '-' . $rightBound;
} else {
if ((string)$left !== '*') {
$left = self::normalizeMonthAndWeekday($left, $isMonthField);
}
}
$fieldArray[] = $left . '/' . $right;
} elseif (str_contains($listElement, '-')) {
[$left, $right] = explode('-', $listElement);
$left = self::normalizeMonthAndWeekday($left, $isMonthField);
$right = self::normalizeMonthAndWeekday($right, $isMonthField);
$fieldArray[] = $left . '-' . $right;
} else {
$fieldArray[] = self::normalizeMonthAndWeekday($listElement, $isMonthField);
}
}
$fieldValues = implode(',', $fieldArray);
}
return $isMonthField ? self::normalizeIntegerField($fieldValues, 1, 12) : self::normalizeIntegerField($fieldValues, 1, 7);
}
/**
* Normalize integer field.
*
* @throws \InvalidArgumentException If field is invalid or out of bounds
*/
protected static function normalizeIntegerField(string $expression, int $lowerBound = 0, int $upperBound = 59): string
{
if ($expression === '*') {
$fieldValues = '*';
} else {
$listOfCommaValues = explode(',', $expression);
$fieldArray = [];
foreach ($listOfCommaValues as $listElement) {
if (str_contains($listElement, '/')) {
[$left, $right] = explode('/', $listElement);
if ($left === '*') {
$leftList = self::convertRangeToListOfValues($lowerBound . '-' . $upperBound);
} else {
$leftList = self::convertRangeToListOfValues($left);
}
$fieldArray[] = self::reduceListOfValuesByStepValue($leftList . '/' . $right);
} elseif (str_contains($listElement, '-')) {
$fieldArray[] = self::convertRangeToListOfValues($listElement);
} elseif (MathUtility::canBeInterpretedAsInteger($listElement)) {
$fieldArray[] = $listElement;
} elseif (strlen($listElement) === 2 && $listElement[0] === '0') {
$fieldArray[] = (int)$listElement;
} else {
throw new \InvalidArgumentException('Unable to normalize integer field.', 1291429389);
}
}
$fieldValues = implode(',', $fieldArray);
}
if ($fieldValues !== '*') {
$fieldList = explode(',', $fieldValues);
sort($fieldList);
$fieldList = array_unique($fieldList);
if (current($fieldList) < $lowerBound) {
throw new \InvalidArgumentException('Lowest element in list is smaller than allowed.', 1291470084);
}
if (end($fieldList) > $upperBound) {
throw new \InvalidArgumentException('An element in the list is higher than allowed.', 1291470170);
}
$fieldValues = implode(',', $fieldList);
}
return $fieldValues;
}
/**
* Convert a range of integers to a list: 4-6 results in a string '4,5,6'
*
* @param string $range integer-integer
* @throws \InvalidArgumentException If range can not be converted to list
*/
protected static function convertRangeToListOfValues(string $range): string
{
if ($range === '') {
throw new \InvalidArgumentException('Unable to convert range to list of values with empty string.', 1291234985);
}
$rangeArray = explode('-', $range);
// Sanitize fields and cast to integer
foreach ($rangeArray as $fieldNumber => $fieldValue) {
if (!MathUtility::canBeInterpretedAsInteger($fieldValue)) {
throw new \InvalidArgumentException('Unable to convert value to integer.', 1291237668);
}
$rangeArray[$fieldNumber] = (int)$fieldValue;
}
$rangeArrayCount = count($rangeArray);
if ($rangeArrayCount === 1) {
$resultList = $rangeArray[0];
} elseif ($rangeArrayCount === 2) {
$left = $rangeArray[0];
$right = $rangeArray[1];
if ($left > $right) {
throw new \InvalidArgumentException('Unable to convert range to list: Left integer must not be greater than right integer.', 1291237145);
}
$resultListArray = [];
for ($i = $left; $i <= $right; $i++) {
$resultListArray[] = $i;
}
$resultList = implode(',', $resultListArray);
} else {
throw new \InvalidArgumentException('Unable to convert range to list of values.', 1291234986);
}
return (string)$resultList;
}
/**
* Reduce a given list of values by step value.
* Following a range with ``/<number>'' specifies skips of the number's value through the range.
* 1-5/2 -> 1,3,5
* 2-10/3 -> 2,5,8
*
* @return string comma-separated list of valid values
* @throws \InvalidArgumentException if step value is invalid or if resulting list is empty
*/
protected static function reduceListOfValuesByStepValue(string $stepExpression): string
{
if ($stepExpression === '') {
throw new \InvalidArgumentException('Unable to convert step values.', 1291234987);
}
$stepValuesAndStepArray = explode('/', $stepExpression);
$stepValuesAndStepArrayCount = count($stepValuesAndStepArray);
if ($stepValuesAndStepArrayCount > 2) {
throw new \InvalidArgumentException('Unable to convert step values: Multiple slashes found.', 1291242168);
}
$left = $stepValuesAndStepArray[0];
$right = $stepValuesAndStepArray[1] ?? '';
if ($left === '') {
throw new \InvalidArgumentException('Unable to convert step values: Left part of / is empty.', 1291414955);
}
if ($right === '') {
throw new \InvalidArgumentException('Unable to convert step values: Right part of / is empty.', 1291414956);
}
if (!MathUtility::canBeInterpretedAsInteger($right)) {
throw new \InvalidArgumentException('Unable to convert step values: Right part must be a single integer.', 1291414957);
}
$right = (int)$right;
$leftArray = explode(',', $left);
$validValues = [];
$currentStep = $right;
foreach ($leftArray as $leftValue) {
if (!MathUtility::canBeInterpretedAsInteger($leftValue)) {
throw new \InvalidArgumentException('Unable to convert step values: Left part must be a single integer or comma separated list of integers.', 1291414958);
}
if ($currentStep === 0) {
$currentStep = $right;
}
if ($currentStep === $right) {
$validValues[] = (int)$leftValue;
}
$currentStep--;
}
if (empty($validValues)) {
throw new \InvalidArgumentException('Unable to convert step values: Result value list is empty.', 1291414959);
}
return implode(',', $validValues);
}
/**
* Dispatcher method for normalizeMonth and normalizeWeekday
*/
protected static function normalizeMonthAndWeekday(string $expression, bool $isMonth = true): string
{
$expression = $isMonth ? self::normalizeMonth($expression) : self::normalizeWeekday($expression);
return (string)$expression;
}
/**
* Accept a string representation or integer number of a month like
* 'jan', 'February', 01, ... and convert to normalized integer value between 1 and 12
*
* @throws \InvalidArgumentException If month string can not be converted to integer
*/
protected static function normalizeMonth(string $month): int
{
$timestamp = strtotime('2010-' . $month . '-01');
// timestamp must be >= 2010-01-01 and <= 2010-12-01
if (!$timestamp || $timestamp < strtotime('2010-01-01') || $timestamp > strtotime('2010-12-01')) {
throw new \InvalidArgumentException('Unable to convert given month name.', 1291083486);
}
return (int)date('n', $timestamp);
}
/**
* Accept a string representation or integer number of a weekday like
* 'mon', 'Friday', 3, ... and convert to normalized integer value between 1 and 7
*
* @throws \InvalidArgumentException If weekday string can not be converted
*/
protected static function normalizeWeekday(string $weekday): int
{
$normalizedWeekday = false;
// 0 (sunday) -> 7
if ($weekday === '0') {
$weekday = 7;
}
if ($weekday >= 1 && $weekday <= 7) {
$normalizedWeekday = (int)$weekday;
}
if (!$normalizedWeekday) {
// Convert string representation like 'sun' to integer
$timestamp = strtotime('next ' . $weekday, (int)mktime(0, 0, 0, 1, 1, 2010));
if (!$timestamp || $timestamp < strtotime('2010-01-01') || $timestamp > strtotime('2010-01-08')) {
throw new \InvalidArgumentException('Unable to convert given weekday name.', 1291163589);
}
$normalizedWeekday = (int)date('N', $timestamp);
}
return $normalizedWeekday;
}
}