array( icon, label, help ) */ public static function method_choices() { return array( 'random' => array( 'randomize', __( 'Random in a range', 'redate' ), __( 'Each post gets a random moment between two dates.', 'redate' ) ), 'even' => array( 'leftright', __( 'Evenly spread', 'redate' ), __( 'Posts are spread at equal distances across a range.', 'redate' ) ), 'sequence' => array( 'clock', __( 'One after another', 'redate' ), __( 'From a start date, one post every so many minutes, hours or days.', 'redate' ) ), 'shift' => array( 'controls-forward', __( 'Shift', 'redate' ), __( 'Move each post\'s own date earlier or later by a fixed amount.', 'redate' ) ), 'exact' => array( 'calendar-alt', __( 'One exact date', 'redate' ), __( 'Every post gets the same date and time.', 'redate' ) ), 'now' => array( 'update', __( 'Now', 'redate' ), __( 'Set the date to the moment the change is applied.', 'redate' ) ), ); } /** * What happens to the modified date when the published date changes. * * @return array key => label */ public static function mod_choices() { return array( 'keep' => __( 'Keep it (moved up only if it would come before the new published date)', 'redate' ), 'same' => __( 'Same as the new published date', 'redate' ), 'now' => __( 'Now, the moment the change is applied', 'redate' ), 'after' => __( 'A random moment between the new published date and now', 'redate' ), ); } /** * Defaults for the date options. * * @return array */ public static function defaults() { return array( 'change' => 'published', 'mod_mode' => 'keep', 'method' => 'random', 'range_type' => 'fixed', 'from' => '', 'to' => '', 'rel_amount' => 30, 'rel_unit' => 'days', 'win_on' => 0, 'win_from' => '09:00', 'win_to' => '18:00', 'days' => array(), 'keep_time' => 0, 'keep_order' => 1, 'seq_now' => 0, 'seq_start' => '', 'seq_step' => 1, 'seq_unit' => 'days', 'seq_dir' => 'forward', 'shift_dir' => 'earlier', 'shift_amount' => 1, 'shift_unit' => 'days', 'exact' => '', 'future' => 'cap', 'comments' => 1, ); } /** * A local "YYYY-MM-DDTHH:MM" (or with seconds, or a space) value, or ''. * * @param mixed $v Value. * @return string */ public static function clean_local( $v ) { $v = str_replace( ' ', 'T', trim( (string) $v ) ); if ( ! preg_match( '/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2}))?)?$/', $v, $m ) ) { return ''; } if ( ! checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) || (int) $m[1] < 1971 || (int) $m[1] > 2200 ) { return ''; } $h = isset( $m[4] ) ? min( 23, (int) $m[4] ) : 0; $i = isset( $m[5] ) ? min( 59, (int) $m[5] ) : 0; return sprintf( '%s-%s-%sT%02d:%02d', $m[1], $m[2], $m[3], $h, $i ); } /** * "HH:MM" or the fallback. * * @param mixed $v Value. * @param string $fallback Fallback. * @return string */ private static function clean_hm( $v, $fallback ) { return preg_match( '/^([01]\d|2[0-3]):([0-5]\d)$/', (string) $v ) ? (string) $v : $fallback; } /** * Validate date options from any source. * * @param array $in Raw values. * @return array */ public static function clean( array $in ) { $d = self::defaults(); $o = array_merge( $d, array_intersect_key( $in, $d ) ); $pick = function ( $v, array $allowed, $fallback ) { return in_array( (string) $v, $allowed, true ) ? (string) $v : $fallback; }; $days = array_values( array_unique( array_filter( array_map( 'intval', (array) $o['days'] ), function ( $x ) { return $x >= 0 && $x <= 6; } ) ) ); sort( $days ); return array( 'change' => $pick( $o['change'], array( 'published', 'modified' ), 'published' ), 'mod_mode' => $pick( $o['mod_mode'], array_keys( self::mod_choices() ), 'keep' ), 'method' => $pick( $o['method'], self::METHODS, 'random' ), 'range_type' => $pick( $o['range_type'], array( 'fixed', 'relative' ), 'fixed' ), 'from' => self::clean_local( $o['from'] ), 'to' => self::clean_local( $o['to'] ), 'rel_amount' => min( 36500, max( 1, (int) $o['rel_amount'] ) ), 'rel_unit' => $pick( $o['rel_unit'], array( 'hours', 'days', 'weeks', 'months', 'years' ), 'days' ), 'win_on' => $o['win_on'] ? 1 : 0, 'win_from' => self::clean_hm( $o['win_from'], '09:00' ), 'win_to' => self::clean_hm( $o['win_to'], '18:00' ), 'days' => 7 === count( $days ) ? array() : $days, 'keep_time' => $o['keep_time'] ? 1 : 0, 'keep_order' => $o['keep_order'] ? 1 : 0, 'seq_now' => $o['seq_now'] ? 1 : 0, 'seq_start' => self::clean_local( $o['seq_start'] ), 'seq_step' => min( 100000, max( 1, (int) $o['seq_step'] ) ), 'seq_unit' => $pick( $o['seq_unit'], array( 'minutes', 'hours', 'days', 'weeks' ), 'days' ), 'seq_dir' => $pick( $o['seq_dir'], array( 'forward', 'backward' ), 'forward' ), 'shift_dir' => $pick( $o['shift_dir'], array( 'earlier', 'later' ), 'earlier' ), 'shift_amount' => min( 100000, max( 1, (int) $o['shift_amount'] ) ), 'shift_unit' => $pick( $o['shift_unit'], array( 'minutes', 'hours', 'days', 'weeks', 'months', 'years' ), 'days' ), 'exact' => self::clean_local( $o['exact'] ), 'future' => $pick( $o['future'], array( 'cap', 'schedule' ), 'cap' ), 'comments' => $o['comments'] ? 1 : 0, ); } /** * Check that the options can make dates. Returns an error message or ''. * * @param array $o Clean options. * @param bool $auto For a schedule. * @return string */ public static function problem( array $o, $auto = false ) { if ( $auto && ! in_array( $o['method'], self::AUTO_METHODS, true ) ) { return __( 'A schedule can not use one exact date. Choose another way to set the dates.', 'redate' ); } if ( in_array( $o['method'], array( 'random', 'even' ), true ) ) { if ( $auto && 'relative' !== $o['range_type'] ) { return __( 'A schedule needs a range that moves with time. Choose "The last …" as the range.', 'redate' ); } if ( 'fixed' === $o['range_type'] ) { if ( ! $o['from'] || ! $o['to'] ) { return __( 'Enter both dates of the range.', 'redate' ); } if ( self::ts( $o['from'] ) >= self::ts( $o['to'] ) ) { return __( 'The end of the range must come after its start.', 'redate' ); } } if ( $o['win_on'] && $o['win_from'] >= $o['win_to'] ) { return __( 'The time of day must end after it starts.', 'redate' ); } } if ( 'sequence' === $o['method'] && ! $o['seq_now'] && ( $auto || ! $o['seq_start'] ) ) { return $auto ? __( 'A schedule\'s sequence must start now.', 'redate' ) : __( 'Enter the start date of the sequence.', 'redate' ); } if ( 'exact' === $o['method'] && ! $o['exact'] ) { return __( 'Enter the date and time to use.', 'redate' ); } return ''; } /* ------------------------------------------------------------------ * Time helpers. All moments are Unix timestamps; local times use the site time zone. * ------------------------------------------------------------------ */ /** * Timestamp of a local "YYYY-MM-DDTHH:MM". * * @param string $local Local time. * @return int */ public static function ts( $local ) { $d = date_create_immutable( str_replace( 'T', ' ', $local ), wp_timezone() ); return $d ? $d->getTimestamp() : 0; } /** * Local midnight of the day a moment falls on. * * @param int $ts Timestamp. * @return DateTimeImmutable */ private static function day_of( $ts ) { return ( new DateTimeImmutable( '@' . $ts ) )->setTimezone( wp_timezone() )->setTime( 0, 0, 0 ); } /** * Seconds since local midnight. * * @param int $ts Timestamp. * @return int */ private static function time_of_day( $ts ) { return $ts - self::day_of( $ts )->getTimestamp(); } /** * Seconds in a sequence step or relative unit (calendar units are handled apart). * * @param string $unit Unit. * @return int */ private static function unit_seconds( $unit ) { $map = array( 'minutes' => MINUTE_IN_SECONDS, 'hours' => HOUR_IN_SECONDS, 'days' => DAY_IN_SECONDS, 'weeks' => WEEK_IN_SECONDS, ); return isset( $map[ $unit ] ) ? $map[ $unit ] : DAY_IN_SECONDS; } /** * Move a moment by a calendar amount in the site time zone. * * @param int $ts Timestamp. * @param int $amount Signed amount. * @param string $unit minutes|hours|days|weeks|months|years. * @return int */ public static function move( $ts, $amount, $unit ) { if ( in_array( $unit, array( 'minutes', 'hours' ), true ) ) { return $ts + $amount * self::unit_seconds( $unit ); } $d = ( new DateTimeImmutable( '@' . $ts ) )->setTimezone( wp_timezone() ); if ( 'weeks' === $unit ) { $amount *= 7; $unit = 'days'; } if ( in_array( $unit, array( 'months', 'years' ), true ) ) { // Keep the day of the month inside the target month: 31 January plus one month is 28 or 29 February. $day = (int) $d->format( 'j' ); $first = $d->setDate( (int) $d->format( 'Y' ), (int) $d->format( 'n' ), 1 ); $first = $first->modify( sprintf( '%+d %s', $amount, $unit ) ); $target = $first->setDate( (int) $first->format( 'Y' ), (int) $first->format( 'n' ), min( $day, (int) $first->format( 't' ) ) ); return $target->getTimestamp(); } return $d->modify( sprintf( '%+d days', $amount ) )->getTimestamp(); } /** * Start and end of the range for random and even dates. * * @param array $o Clean options. * @param int $now Now. * @return int[] */ public static function range( array $o, $now ) { if ( 'relative' === $o['range_type'] ) { return array( self::move( $now, -$o['rel_amount'], $o['rel_unit'] ), $now ); } return array( self::ts( $o['from'] ), self::ts( $o['to'] ) ); } /** * True when a moment is on an allowed day and inside the time window. * * @param int $ts Timestamp. * @param array $o Clean options. * @return bool */ private static function allowed( $ts, array $o ) { $local = ( new DateTimeImmutable( '@' . $ts ) )->setTimezone( wp_timezone() ); if ( $o['days'] && ! in_array( (int) $local->format( 'w' ), $o['days'], true ) ) { return false; } if ( $o['win_on'] ) { $hm = $local->format( 'H:i' ); return $hm >= $o['win_from'] && $hm <= $o['win_to']; } return true; } /** * The allowed parts of a range: one interval per allowed day, narrowed to the time window. * * @param int $a Start. * @param int $b End. * @param array $o Clean options. * @return array[] Each array( start, end ). */ public static function intervals( $a, $b, array $o ) { if ( $b <= $a ) { return array(); } if ( ! $o['days'] && ! $o['win_on'] ) { return array( array( $a, $b ) ); } $out = array(); $day = self::day_of( $a ); $w0 = $o['win_on'] ? (int) substr( $o['win_from'], 0, 2 ) * 3600 + (int) substr( $o['win_from'], 3 ) * 60 : 0; $w1 = $o['win_on'] ? (int) substr( $o['win_to'], 0, 2 ) * 3600 + (int) substr( $o['win_to'], 3 ) * 60 + 59 : DAY_IN_SECONDS - 1; for ( $guard = 0; $guard < 80000 && $day->getTimestamp() <= $b; ++$guard ) { if ( ! $o['days'] || in_array( (int) $day->format( 'w' ), $o['days'], true ) ) { // Build the window from the local clock time, so days with a clock change stay right. $s = $day->setTime( intdiv( $w0, 3600 ), intdiv( $w0 % 3600, 60 ), 0 )->getTimestamp(); $e = $day->setTime( intdiv( $w1, 3600 ), intdiv( $w1 % 3600, 60 ), $w1 % 60 )->getTimestamp(); $s = max( $s, $a ); $e = min( $e, $b ); if ( $e > $s ) { $out[] = array( $s, $e ); } } $day = $day->modify( '+1 day' ); } return $out; } /** * Map positions on the allowed timeline (seconds from its start) to moments. * * @param int[] $pos Positions, sorted ascending. * @param array[] $intervals Allowed intervals. * @return int[] */ private static function place( array $pos, array $intervals ) { $out = array(); $i = 0; $base = 0; $n = count( $intervals ); foreach ( $pos as $p ) { while ( $i < $n - 1 && $p > $base + ( $intervals[ $i ][1] - $intervals[ $i ][0] ) ) { $base += $intervals[ $i ][1] - $intervals[ $i ][0]; ++$i; } $out[] = min( $intervals[ $i ][1], $intervals[ $i ][0] + (int) ( $p - $base ) ); } return $out; } /** * Fisher-Yates shuffle with a cryptographic random source. * * @param array $list List. * @return array */ private static function shuffle( array $list ) { for ( $i = count( $list ) - 1; $i > 0; --$i ) { $j = wp_rand( 0, $i ); $t = $list[ $i ]; $list[ $i ] = $list[ $j ]; $list[ $j ] = $t; } return $list; } /** * Make the new dates. * * @param array $o Clean options. * @param int[] $old The current dates being changed, sorted ascending (oldest first). * @param int $now Now. * @return int[]|string New dates in the same order as $old, or an error message. */ public static function generate( array $o, array $old, $now ) { $n = count( $old ); if ( ! $n ) { return array(); } $cap = 'modified' === $o['change']; switch ( $o['method'] ) { case 'random': case 'even': list( $a, $b ) = self::range( $o, $now ); if ( $cap || ( 'cap' === $o['future'] ) ) { $b = min( $b, $now ); } $iv = self::intervals( $a, $b, $o ); $t = 0; foreach ( $iv as $x ) { $t += $x[1] - $x[0]; } if ( $t <= 0 ) { return $b < self::range( $o, $now )[1] ? __( 'The range holds no allowed time before now. Widen the range, the days or the time of day.', 'redate' ) : __( 'The range holds no allowed time. Widen the range, the days or the time of day.', 'redate' ); } $pos = array(); if ( 'random' === $o['method'] ) { for ( $k = 0; $k < $n; ++$k ) { $pos[] = wp_rand( 0, $t ); } sort( $pos ); } else { for ( $k = 0; $k < $n; ++$k ) { $pos[] = 1 === $n ? intdiv( $t, 2 ) : (int) round( $k * $t / ( $n - 1 ) ); } } $new = self::place( $pos, $iv ); if ( ! $o['keep_order'] ) { $new = self::shuffle( $new ); } break; case 'sequence': $start = $o['seq_now'] ? $now : self::ts( $o['seq_start'] ); $step = $o['seq_step'] * self::unit_seconds( $o['seq_unit'] ); $dir = 'forward' === $o['seq_dir'] ? 1 : -1; $moments = array(); $t = $start; $tries = 0; while ( count( $moments ) < $n ) { if ( self::allowed( $t, $o ) ) { $moments[] = $t; } elseif ( ++$tries > 500000 ) { return __( 'The sequence found too few allowed moments. Check the days and the time of day.', 'redate' ); } $t += $dir * $step; } // Forward: the oldest post gets the start. Backward: the newest post gets the start. $new = 1 === $dir ? $moments : array_reverse( $moments ); if ( ! $o['keep_order'] ) { $new = self::shuffle( $new ); } break; case 'shift': $amount = 'earlier' === $o['shift_dir'] ? -$o['shift_amount'] : $o['shift_amount']; $new = array(); foreach ( $old as $ts ) { $new[] = self::move( $ts, $amount, $o['shift_unit'] ); } break; case 'exact': $new = array_fill( 0, $n, self::ts( $o['exact'] ) ); break; default: $new = array_fill( 0, $n, $now ); } if ( $o['keep_time'] && in_array( $o['method'], array( 'random', 'even', 'sequence' ), true ) ) { foreach ( $new as $k => $ts ) { $new[ $k ] = self::day_of( $ts )->getTimestamp() + self::time_of_day( $old[ $k ] ); } } return $new; } /** * Short text describing the options, for history and schedules. * * @param array $o Clean options. * @return string */ public static function describe( array $o ) { $what = 'modified' === $o['change'] ? __( 'Modified date', 'redate' ) : __( 'Published date', 'redate' ); switch ( $o['method'] ) { case 'random': case 'even': $random = 'random' === $o['method']; if ( 'relative' === $o['range_type'] ) { $span = self::amount( $o['rel_amount'], $o['rel_unit'] ); /* translators: %s: amount of time, such as "30 days". */ $how = $random ? sprintf( __( 'random over the last %s', 'redate' ), $span ) : sprintf( __( 'spread over the last %s', 'redate' ), $span ); } else { $from = str_replace( 'T', ' ', $o['from'] ); $to = str_replace( 'T', ' ', $o['to'] ); /* translators: 1: start date, 2: end date. */ $how = $random ? sprintf( __( 'random %1$s to %2$s', 'redate' ), $from, $to ) : sprintf( __( 'spread %1$s to %2$s', 'redate' ), $from, $to ); } break; case 'sequence': $step = self::amount( $o['seq_step'], $o['seq_unit'] ); $start = $o['seq_now'] ? __( 'now', 'redate' ) : str_replace( 'T', ' ', $o['seq_start'] ); /* translators: 1: step, such as "2 hours", 2: start date or "now". */ $how = 'forward' === $o['seq_dir'] ? sprintf( __( 'every %1$s from %2$s', 'redate' ), $step, $start ) : sprintf( __( 'every %1$s back from %2$s', 'redate' ), $step, $start ); break; case 'shift': $by = self::amount( $o['shift_amount'], $o['shift_unit'] ); /* translators: %s: amount of time, such as "3 days". */ $how = 'later' === $o['shift_dir'] ? sprintf( __( '%s later', 'redate' ), $by ) : sprintf( __( '%s earlier', 'redate' ), $by ); break; case 'exact': /* translators: %s: date and time. */ $how = sprintf( __( 'set to %s', 'redate' ), str_replace( 'T', ' ', $o['exact'] ) ); break; default: $how = __( 'set to now', 'redate' ); } /* translators: 1: which date changes ("Published date" or "Modified date"), 2: how it changes. */ return sprintf( __( '%1$s: %2$s', 'redate' ), $what, $how ); } /** * An amount of time with its unit, such as "3 days". * * @param int $n Amount. * @param string $unit minutes|hours|days|weeks|months|years. * @return string */ public static function amount( $n, $unit ) { $n = (int) $n; $num = number_format_i18n( $n ); switch ( $unit ) { case 'minutes': /* translators: %s: number of minutes. */ return sprintf( _n( '%s minute', '%s minutes', $n, 'redate' ), $num ); case 'hours': /* translators: %s: number of hours. */ return sprintf( _n( '%s hour', '%s hours', $n, 'redate' ), $num ); case 'weeks': /* translators: %s: number of weeks. */ return sprintf( _n( '%s week', '%s weeks', $n, 'redate' ), $num ); case 'months': /* translators: %s: number of months. */ return sprintf( _n( '%s month', '%s months', $n, 'redate' ), $num ); case 'years': /* translators: %s: number of years. */ return sprintf( _n( '%s year', '%s years', $n, 'redate' ), $num ); default: /* translators: %s: number of days. */ return sprintf( _n( '%s day', '%s days', $n, 'redate' ), $num ); } } }