Your IP : 216.73.216.162


Current Path : /home/x/b/o/xbodynamge/namtation/wp-content/
Upload File :
Current File : /home/x/b/o/xbodynamge/namtation/wp-content/classes.tar

class-twentynineteen-walker-comment.php000066600000010000151117342420014356 0ustar00<?php
/**
 * Custom comment walker for this theme
 *
 * @package WordPress
 * @subpackage Twenty_Nineteen
 * @since 1.0.0
 */

/**
 * This class outputs custom comment walker for HTML5 friendly WordPress comment and threaded replies.
 *
 * @since 1.0.0
 */
class TwentyNineteen_Walker_Comment extends Walker_Comment {

	/**
	 * Outputs a comment in the HTML5 format.
	 *
	 * @see wp_list_comments()
	 *
	 * @param WP_Comment $comment Comment to display.
	 * @param int        $depth   Depth of the current comment.
	 * @param array      $args    An array of arguments.
	 */
	protected function html5_comment( $comment, $depth, $args ) {

		$tag = ( 'div' === $args['style'] ) ? 'div' : 'li';

		?>
		<<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( $this->has_children ? 'parent' : '', $comment ); ?>>
			<article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
				<footer class="comment-meta">
					<div class="comment-author vcard">
						<?php
						$comment_author_url = get_comment_author_url( $comment );
						$comment_author     = get_comment_author( $comment );
						$avatar             = get_avatar( $comment, $args['avatar_size'] );
						if ( 0 != $args['avatar_size'] ) {
							if ( empty( $comment_author_url ) ) {
								echo $avatar;
							} else {
								printf( '<a href="%s" rel="external nofollow" class="url">', $comment_author_url );
								echo $avatar;
							}
						}
						/*
						 * Using the `check` icon instead of `check_circle`, since we can't add a
						 * fill color to the inner check shape when in circle form.
						 */
						if ( twentynineteen_is_comment_by_post_author( $comment ) ) {
							printf( '<span class="post-author-badge" aria-hidden="true">%s</span>', twentynineteen_get_icon_svg( 'check', 24 ) );
						}

						/*
						 * Using the `check` icon instead of `check_circle`, since we can't add a
						 * fill color to the inner check shape when in circle form.
						 */
						if ( twentynineteen_is_comment_by_post_author( $comment ) ) {
							printf( '<span class="post-author-badge" aria-hidden="true">%s</span>', twentynineteen_get_icon_svg( 'check', 24 ) );
						}

						printf(
							/* translators: %s: comment author link */
							wp_kses(
								__( '%s <span class="screen-reader-text says">says:</span>', 'twentynineteen' ),
								array(
									'span' => array(
										'class' => array(),
									),
								)
							),
							'<b class="fn">' . $comment_author . '</b>'
						);

						if ( ! empty( $comment_author_url ) ) {
							echo '</a>';
						}
						?>
					</div><!-- .comment-author -->

					<div class="comment-metadata">
						<a href="<?php echo esc_url( get_comment_link( $comment, $args ) ); ?>">
							<?php
								/* translators: 1: comment date, 2: comment time */
								$comment_timestamp = sprintf( __( '%1$s at %2$s', 'twentynineteen' ), get_comment_date( '', $comment ), get_comment_time() );
							?>
							<time datetime="<?php comment_time( 'c' ); ?>" title="<?php echo $comment_timestamp; ?>">
								<?php echo $comment_timestamp; ?>
							</time>
						</a>
						<?php
							$edit_comment_icon = twentynineteen_get_icon_svg( 'edit', 16 );
							edit_comment_link( __( 'Edit', 'twentynineteen' ), '<span class="edit-link-sep">&mdash;</span> <span class="edit-link">' . $edit_comment_icon, '</span>' );
						?>
					</div><!-- .comment-metadata -->

					<?php if ( '0' == $comment->comment_approved ) : ?>
					<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentynineteen' ); ?></p>
					<?php endif; ?>
				</footer><!-- .comment-meta -->

				<div class="comment-content">
					<?php comment_text(); ?>
				</div><!-- .comment-content -->

			</article><!-- .comment-body -->

			<?php
			comment_reply_link(
				array_merge(
					$args,
					array(
						'add_below' => 'div-comment',
						'depth'     => $depth,
						'max_depth' => $args['max_depth'],
						'before'    => '<div class="comment-reply">',
						'after'     => '</div>',
					)
				)
			);
			?>
		<?php
	}
}
class-twentynineteen-svg-icons.php000066600000167743151117342420013374 0ustar00<?php
/**
 * SVG Icons class
 *
 * @package WordPress
 * @subpackage Twenty_Nineteen
 * @since 1.0.0
 */

/**
 * This class is in charge of displaying SVG icons across the site.
 *
 * Place each <svg> source on its own array key, without adding the
 * both `width` and `height` attributes, since these are added dnamically,
 * before rendering the SVG code.
 *
 * All icons are assumed to have equal width and height, hence the option
 * to only specify a `$size` parameter in the svg methods.
 *
 * @since 1.0.0
 */
class TwentyNineteen_SVG_Icons {

	/**
	 * Gets the SVG code for a given icon.
	 */
	public static function get_svg( $group, $icon, $size ) {
		if ( 'ui' == $group ) {
			$arr = self::$ui_icons;
		} elseif ( 'social' == $group ) {
			$arr = self::$social_icons;
		} else {
			$arr = array();
		}
		if ( array_key_exists( $icon, $arr ) ) {
			$repl = sprintf( '<svg class="svg-icon" width="%d" height="%d" aria-hidden="true" role="img" focusable="false" ', $size, $size );
			$svg  = preg_replace( '/^<svg /', $repl, trim( $arr[ $icon ] ) ); // Add extra attributes to SVG code.
			$svg  = preg_replace( "/([\n\t]+)/", ' ', $svg ); // Remove newlines & tabs.
			$svg  = preg_replace( '/>\s*</', '><', $svg ); // Remove white space between SVG tags.
			return $svg;
		}
		return null;
	}

	/**
	 * Detects the social network from a URL and returns the SVG code for its icon.
	 */
	public static function get_social_link_svg( $uri, $size ) {
		static $regex_map; // Only compute regex map once, for performance.
		if ( ! isset( $regex_map ) ) {
			$regex_map = array();
			$map       = &self::$social_icons_map; // Use reference instead of copy, to save memory.
			foreach ( array_keys( self::$social_icons ) as $icon ) {
				$domains            = array_key_exists( $icon, $map ) ? $map[ $icon ] : array( sprintf( '%s.com', $icon ) );
				$domains            = array_map( 'trim', $domains ); // Remove leading/trailing spaces, to prevent regex from failing to match.
				$domains            = array_map( 'preg_quote', $domains );
				$regex_map[ $icon ] = sprintf( '/(%s)/i', implode( '|', $domains ) );
			}
		}
		foreach ( $regex_map as $icon => $regex ) {
			if ( preg_match( $regex, $uri ) ) {
				return self::get_svg( 'social', $icon, $size );
			}
		}
		return null;
	}

	/**
	 * User Interface icons – svg sources.
	 *
	 * @var array
	 */
	static $ui_icons = array(
		'link'                     => /* material-design – link */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"></path>
    <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"></path>
</svg>',

		'watch'                    => /* material-design – watch-later */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <defs>
        <path id="a" d="M0 0h24v24H0V0z"></path>
    </defs>
    <clipPath id="b">
        <use xlink:href="#a" overflow="visible"></use>
    </clipPath>
    <path clip-path="url(#b)" d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.5 2.7-.8 1.3z"></path>
</svg>',

		'archive'                  => /* material-design – folder */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"></path>
    <path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'tag'                      => /* material-design – local_offer */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
	<path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z"></path>
	<path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'comment'                  => /* material-design – comment */ '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18z"></path>
    <path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'person'                   => /* material-design – person */ '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"></path>
    <path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'edit'                     => /* material-design – edit */ '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"></path>
    <path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'chevron_left'             => /* material-design – chevron_left */ '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path>
    <path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'chevron_right'            => /* material-design – chevron_right */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path>
    <path d="M0 0h24v24H0z" fill="none"></path>
</svg>',

		'check'                    => /* material-design – check */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"></path>
    <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path>
</svg>',

		'arrow_drop_down_circle'   => /* material-design – arrow_drop_down_circle */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
	<path d="M0 0h24v24H0z" fill="none"></path>
	<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 12l-4-4h8l-4 4z"></path>
</svg>',

		'keyboard_arrow_down'      => /* material-design – keyboard_arrow_down */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
	<path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"></path>
	<path fill="none" d="M0 0h24v24H0V0z"></path>
</svg>',

		'keyboard_arrow_right'     => /* material-design – keyboard_arrow_right */ '
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
	<path d="M10 17l5-5-5-5v10z"></path>
	<path fill="none" d="M0 24V0h24v24H0z"></path>
</svg>',

		'keyboard_arrow_left'      => /* material-design – keyboard_arrow_left */ '
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
	<path d="M14 7l-5 5 5 5V7z"></path>
	<path fill="none" d="M24 0v24H0V0h24z"></path>
</svg>',

		'arrow_drop_down_ellipsis' => /* custom – arrow_drop_down_ellipsis */ '
<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">
    <g fill="none" fill-rule="evenodd">
        <path d="M0 0h24v24H0z"/>
        <path fill="currentColor" fill-rule="nonzero" d="M12 2c5.52 0 10 4.48 10 10s-4.48 10-10 10S2 17.52 2 12 6.48 2 12 2zM6 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm6 0a2 2 0 1 0 0-4 2 2 0 0 0 0 4zm6 0a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/>
    </g>
</svg>',

	);

	/**
	 * Social Icons – domain mappings.
	 *
	 * By default, each Icon ID is matched against a .com TLD. To override this behavior,
	 * specify all the domains it covers (including the .com TLD too, if applicable).
	 *
	 * @var array
	 */
	static $social_icons_map = array(
		'amazon'      => array(
			'amazon.com',
			'amazon.cn',
			'amazon.in',
			'amazon.fr',
			'amazon.de',
			'amazon.it',
			'amazon.nl',
			'amazon.es',
			'amazon.co',
			'amazon.ca',
		),
		'apple'       => array(
			'apple.com',
			'itunes.com',
		),
		'behance'     => array(
			'behance.net',
		),
		'codepen'     => array(
			'codepen.io',
		),
		'facebook'    => array(
			'facebook.com',
			'fb.me',
		),
		'feed'        => array(
			'feed',
		),
		'google-plus' => array(
			'plus.google.com',
		),
		'lastfm'      => array(
			'last.fm',
		),
		'mail'        => array(
			'mailto:',
		),
		'slideshare'  => array(
			'slideshare.net',
		),
		'pocket'      => array(
			'getpocket.com',
		),
		'twitch'      => array(
			'twitch.tv',
		),
		'wordpress'   => array(
			'wordpress.com',
			'wordpress.org',
		),
	);

	/**
	 * Social Icons – svg sources.
	 *
	 * @var array
	 */
	static $social_icons = array(
		'500px'       => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M6.94026,15.1412c.00437.01213.108.29862.168.44064a6.55008,6.55008,0,1,0,6.03191-9.09557,6.68654,6.68654,0,0,0-2.58357.51467A8.53914,8.53914,0,0,0,8.21268,8.61344L8.209,8.61725V3.22948l9.0504-.00008c.32934-.0036.32934-.46353.32934-.61466s0-.61091-.33035-.61467L7.47248,2a.43.43,0,0,0-.43131.42692v7.58355c0,.24466.30476.42131.58793.4819.553.11812.68074-.05864.81617-.2457l.018-.02481A10.52673,10.52673,0,0,1,9.32258,9.258a5.35268,5.35268,0,1,1,7.58985,7.54976,5.417,5.417,0,0,1-3.80867,1.56365,5.17483,5.17483,0,0,1-2.69822-.74478l.00342-4.61111a2.79372,2.79372,0,0,1,.71372-1.78792,2.61611,2.61611,0,0,1,1.98282-.89477,2.75683,2.75683,0,0,1,1.95525.79477,2.66867,2.66867,0,0,1,.79656,1.909,2.724,2.724,0,0,1-2.75849,2.748,4.94651,4.94651,0,0,1-.86254-.13719c-.31234-.093-.44519.34058-.48892.48349-.16811.54966.08453.65862.13687.67489a3.75751,3.75751,0,0,0,1.25234.18375,3.94634,3.94634,0,1,0-2.82444-6.742,3.67478,3.67478,0,0,0-1.13028,2.584l-.00041.02323c-.0035.11667-.00579,2.881-.00644,3.78811l-.00407-.00451a6.18521,6.18521,0,0,1-1.0851-1.86092c-.10544-.27856-.34358-.22925-.66857-.12917-.14192.04372-.57386.17677-.47833.489Zm4.65165-1.08338a.51346.51346,0,0,0,.19513.31818l.02276.022a.52945.52945,0,0,0,.3517.18416.24242.24242,0,0,0,.16577-.0611c.05473-.05082.67382-.67812.73287-.738l.69041.68819a.28978.28978,0,0,0,.21437.11032.53239.53239,0,0,0,.35708-.19486c.29792-.30419.14885-.46821.07676-.54751l-.69954-.69975.72952-.73469c.16-.17311.01874-.35708-.12218-.498-.20461-.20461-.402-.25742-.52855-.14083l-.7254.72665-.73354-.73375a.20128.20128,0,0,0-.14179-.05695.54135.54135,0,0,0-.34379.19648c-.22561.22555-.274.38149-.15656.5059l.73374.7315-.72942.73072A.26589.26589,0,0,0,11.59191,14.05782Zm1.59866-9.915A8.86081,8.86081,0,0,0,9.854,4.776a.26169.26169,0,0,0-.16938.22759.92978.92978,0,0,0,.08619.42094c.05682.14524.20779.531.50006.41955a8.40969,8.40969,0,0,1,2.91968-.55484,7.87875,7.87875,0,0,1,3.086.62286,8.61817,8.61817,0,0,1,2.30562,1.49315.2781.2781,0,0,0,.18318.07586c.15529,0,.30425-.15253.43167-.29551.21268-.23861.35873-.4369.1492-.63538a8.50425,8.50425,0,0,0-2.62312-1.694A9.0177,9.0177,0,0,0,13.19058,4.14283ZM19.50945,18.6236h0a.93171.93171,0,0,0-.36642-.25406.26589.26589,0,0,0-.27613.06613l-.06943.06929A7.90606,7.90606,0,0,1,7.60639,18.505a7.57284,7.57284,0,0,1-1.696-2.51537,8.58715,8.58715,0,0,1-.5147-1.77754l-.00871-.04864c-.04939-.25873-.28755-.27684-.62981-.22448-.14234.02178-.5755.088-.53426.39969l.001.00712a9.08807,9.08807,0,0,0,15.406,4.99094c.00193-.00192.04753-.04718.0725-.07436C19.79425,19.16234,19.87422,18.98728,19.50945,18.6236Z"></path>
</svg>',

		'amazon'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M13.582,8.182C11.934,8.367,9.78,8.49,8.238,9.166c-1.781,0.769-3.03,2.337-3.03,4.644 c0,2.953,1.86,4.429,4.253,4.429c2.02,0,3.125-0.477,4.685-2.065c0.516,0.747,0.685,1.109,1.629,1.894 c0.212,0.114,0.483,0.103,0.672-0.066l0.006,0.006c0.567-0.505,1.599-1.401,2.18-1.888c0.231-0.188,0.19-0.496,0.009-0.754 c-0.52-0.718-1.072-1.303-1.072-2.634V8.305c0-1.876,0.133-3.599-1.249-4.891C15.23,2.369,13.422,2,12.04,2 C9.336,2,6.318,3.01,5.686,6.351C5.618,6.706,5.877,6.893,6.109,6.945l2.754,0.298C9.121,7.23,9.308,6.977,9.357,6.72 c0.236-1.151,1.2-1.706,2.284-1.706c0.584,0,1.249,0.215,1.595,0.738c0.398,0.584,0.346,1.384,0.346,2.061V8.182z M13.049,14.088 c-0.451,0.8-1.169,1.291-1.967,1.291c-1.09,0-1.728-0.83-1.728-2.061c0-2.42,2.171-2.86,4.227-2.86v0.615 C13.582,12.181,13.608,13.104,13.049,14.088z M20.683,19.339C18.329,21.076,14.917,22,11.979,22c-4.118,0-7.826-1.522-10.632-4.057 c-0.22-0.199-0.024-0.471,0.241-0.317c3.027,1.762,6.771,2.823,10.639,2.823c2.608,0,5.476-0.541,8.115-1.66 C20.739,18.62,21.072,19.051,20.683,19.339z M21.336,21.043c-0.194,0.163-0.379,0.076-0.293-0.139 c0.284-0.71,0.92-2.298,0.619-2.684c-0.301-0.386-1.99-0.183-2.749-0.092c-0.23,0.027-0.266-0.173-0.059-0.319 c1.348-0.946,3.555-0.673,3.811-0.356C22.925,17.773,22.599,19.986,21.336,21.043z"></path>
</svg>',

		'apple'       => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M20.07,17.586a10.874,10.874,0,0,1-1.075,1.933,9.822,9.822,0,0,1-1.385,1.674,2.687,2.687,0,0,1-1.78.784,4.462,4.462,0,0,1-1.644-.393,4.718,4.718,0,0,0-1.77-.391,4.878,4.878,0,0,0-1.82.391A4.9,4.9,0,0,1,9.021,22a2.53,2.53,0,0,1-1.82-.8A10.314,10.314,0,0,1,5.752,19.46,11.987,11.987,0,0,1,4.22,16.417a11.143,11.143,0,0,1-.643-3.627,6.623,6.623,0,0,1,.87-3.465A5.1,5.1,0,0,1,6.268,7.483a4.9,4.9,0,0,1,2.463-.695,5.8,5.8,0,0,1,1.9.443,6.123,6.123,0,0,0,1.511.444,9.04,9.04,0,0,0,1.675-.523,5.537,5.537,0,0,1,2.277-.4,4.835,4.835,0,0,1,3.788,1.994,4.213,4.213,0,0,0-2.235,3.827,4.222,4.222,0,0,0,1.386,3.181,4.556,4.556,0,0,0,1.385.909q-.167.483-.353.927ZM16.211,2.4a4.267,4.267,0,0,1-1.094,2.8,3.726,3.726,0,0,1-3.1,1.528A3.114,3.114,0,0,1,12,6.347a4.384,4.384,0,0,1,1.16-2.828,4.467,4.467,0,0,1,1.414-1.061A4.215,4.215,0,0,1,16.19,2a3.633,3.633,0,0,1,.021.4Z"></path>
</svg>',

		'bandcamp'    => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M15.27 17.289 3 17.289 8.73 6.711 21 6.711 15.27 17.289"></path>
</svg>',

		'behance'     => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M7.799,5.698c0.589,0,1.12,0.051,1.606,0.156c0.482,0.102,0.894,0.273,1.241,0.507c0.344,0.235,0.612,0.546,0.804,0.938 c0.188,0.387,0.281,0.871,0.281,1.443c0,0.619-0.141,1.137-0.421,1.551c-0.284,0.413-0.7,0.751-1.255,1.014 c0.756,0.218,1.317,0.601,1.689,1.146c0.374,0.549,0.557,1.205,0.557,1.975c0,0.623-0.12,1.161-0.359,1.612 c-0.241,0.457-0.569,0.828-0.973,1.114c-0.408,0.288-0.876,0.5-1.399,0.637C9.052,17.931,8.514,18,7.963,18H2V5.698H7.799 M7.449,10.668c0.481,0,0.878-0.114,1.192-0.345c0.311-0.228,0.463-0.603,0.463-1.119c0-0.286-0.051-0.523-0.152-0.707 C8.848,8.315,8.711,8.171,8.536,8.07C8.362,7.966,8.166,7.894,7.94,7.854c-0.224-0.044-0.457-0.06-0.697-0.06H4.709v2.874H7.449z M7.6,15.905c0.267,0,0.521-0.024,0.759-0.077c0.243-0.053,0.457-0.137,0.637-0.261c0.182-0.12,0.332-0.283,0.441-0.491 C9.547,14.87,9.6,14.602,9.6,14.278c0-0.633-0.18-1.084-0.533-1.357c-0.356-0.27-0.83-0.404-1.413-0.404H4.709v3.388L7.6,15.905z M16.162,15.864c0.367,0.358,0.897,0.538,1.583,0.538c0.493,0,0.92-0.125,1.277-0.374c0.354-0.248,0.571-0.514,0.654-0.79h2.155 c-0.347,1.072-0.872,1.838-1.589,2.299C19.534,18,18.67,18.23,17.662,18.23c-0.701,0-1.332-0.113-1.899-0.337 c-0.567-0.227-1.041-0.544-1.439-0.958c-0.389-0.415-0.689-0.907-0.904-1.484c-0.213-0.574-0.32-1.21-0.32-1.899 c0-0.666,0.11-1.288,0.329-1.863c0.222-0.577,0.529-1.075,0.933-1.492c0.406-0.42,0.885-0.751,1.444-0.994 c0.558-0.241,1.175-0.363,1.857-0.363c0.754,0,1.414,0.145,1.98,0.44c0.563,0.291,1.026,0.686,1.389,1.181 c0.363,0.493,0.622,1.057,0.783,1.69c0.16,0.632,0.217,1.292,0.171,1.983h-6.428C15.557,14.84,15.795,15.506,16.162,15.864 M18.973,11.184c-0.291-0.321-0.783-0.496-1.384-0.496c-0.39,0-0.714,0.066-0.973,0.2c-0.254,0.132-0.461,0.297-0.621,0.491 c-0.157,0.197-0.265,0.405-0.328,0.628c-0.063,0.217-0.101,0.413-0.111,0.587h3.98C19.478,11.969,19.265,11.509,18.973,11.184z M15.057,7.738h4.985V6.524h-4.985L15.057,7.738z"></path>
</svg>',

		'chain'       => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M19.647,16.706a1.134,1.134,0,0,0-.343-.833l-2.549-2.549a1.134,1.134,0,0,0-.833-.343,1.168,1.168,0,0,0-.883.392l.233.226q.2.189.264.264a2.922,2.922,0,0,1,.184.233.986.986,0,0,1,.159.312,1.242,1.242,0,0,1,.043.337,1.172,1.172,0,0,1-1.176,1.176,1.237,1.237,0,0,1-.337-.043,1,1,0,0,1-.312-.159,2.76,2.76,0,0,1-.233-.184q-.073-.068-.264-.264l-.226-.233a1.19,1.19,0,0,0-.4.895,1.134,1.134,0,0,0,.343.833L15.837,19.3a1.13,1.13,0,0,0,.833.331,1.18,1.18,0,0,0,.833-.318l1.8-1.789a1.12,1.12,0,0,0,.343-.821Zm-8.615-8.64a1.134,1.134,0,0,0-.343-.833L8.163,4.7a1.134,1.134,0,0,0-.833-.343,1.184,1.184,0,0,0-.833.331L4.7,6.473a1.12,1.12,0,0,0-.343.821,1.134,1.134,0,0,0,.343.833l2.549,2.549a1.13,1.13,0,0,0,.833.331,1.184,1.184,0,0,0,.883-.38L8.728,10.4q-.2-.189-.264-.264A2.922,2.922,0,0,1,8.28,9.9a.986.986,0,0,1-.159-.312,1.242,1.242,0,0,1-.043-.337A1.172,1.172,0,0,1,9.254,8.079a1.237,1.237,0,0,1,.337.043,1,1,0,0,1,.312.159,2.761,2.761,0,0,1,.233.184q.073.068.264.264l.226.233a1.19,1.19,0,0,0,.4-.895ZM22,16.706a3.343,3.343,0,0,1-1.042,2.488l-1.8,1.789a3.536,3.536,0,0,1-4.988-.025l-2.525-2.537a3.384,3.384,0,0,1-1.017-2.488,3.448,3.448,0,0,1,1.078-2.561l-1.078-1.078a3.434,3.434,0,0,1-2.549,1.078,3.4,3.4,0,0,1-2.5-1.029L3.029,9.794A3.4,3.4,0,0,1,2,7.294,3.343,3.343,0,0,1,3.042,4.806l1.8-1.789A3.384,3.384,0,0,1,7.331,2a3.357,3.357,0,0,1,2.5,1.042l2.525,2.537a3.384,3.384,0,0,1,1.017,2.488,3.448,3.448,0,0,1-1.078,2.561l1.078,1.078a3.551,3.551,0,0,1,5.049-.049l2.549,2.549A3.4,3.4,0,0,1,22,16.706Z"></path>
</svg>',

		'codepen'     => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M22.016,8.84c-0.002-0.013-0.005-0.025-0.007-0.037c-0.005-0.025-0.008-0.048-0.015-0.072 c-0.003-0.015-0.01-0.028-0.013-0.042c-0.008-0.02-0.015-0.04-0.023-0.062c-0.007-0.015-0.013-0.028-0.02-0.042 c-0.008-0.02-0.018-0.037-0.03-0.057c-0.007-0.013-0.017-0.027-0.025-0.038c-0.012-0.018-0.023-0.035-0.035-0.052 c-0.01-0.013-0.02-0.025-0.03-0.037c-0.015-0.017-0.028-0.032-0.043-0.045c-0.01-0.012-0.022-0.023-0.035-0.035 c-0.015-0.015-0.032-0.028-0.048-0.04c-0.012-0.01-0.025-0.02-0.037-0.03c-0.005-0.003-0.01-0.008-0.015-0.012l-9.161-6.096 c-0.289-0.192-0.666-0.192-0.955,0L2.359,8.237C2.354,8.24,2.349,8.245,2.344,8.249L2.306,8.277 c-0.017,0.013-0.033,0.027-0.048,0.04C2.246,8.331,2.234,8.342,2.222,8.352c-0.015,0.015-0.028,0.03-0.042,0.047 c-0.012,0.013-0.022,0.023-0.03,0.037C2.139,8.453,2.125,8.471,2.115,8.488C2.107,8.501,2.099,8.514,2.09,8.526 C2.079,8.548,2.069,8.565,2.06,8.585C2.054,8.6,2.047,8.613,2.04,8.626C2.032,8.648,2.025,8.67,2.019,8.69 c-0.005,0.013-0.01,0.027-0.013,0.042C1.999,8.755,1.995,8.778,1.99,8.803C1.989,8.817,1.985,8.828,1.984,8.84 C1.978,8.879,1.975,8.915,1.975,8.954v6.093c0,0.037,0.003,0.075,0.008,0.112c0.002,0.012,0.005,0.025,0.007,0.038 c0.005,0.023,0.008,0.047,0.015,0.072c0.003,0.015,0.008,0.028,0.013,0.04c0.007,0.022,0.013,0.042,0.022,0.063 c0.007,0.015,0.013,0.028,0.02,0.04c0.008,0.02,0.018,0.038,0.03,0.058c0.007,0.013,0.015,0.027,0.025,0.038 c0.012,0.018,0.023,0.035,0.035,0.052c0.01,0.013,0.02,0.025,0.03,0.037c0.013,0.015,0.028,0.032,0.042,0.045 c0.012,0.012,0.023,0.023,0.035,0.035c0.015,0.013,0.032,0.028,0.048,0.04l0.038,0.03c0.005,0.003,0.01,0.007,0.013,0.01 l9.163,6.095C11.668,21.953,11.833,22,12,22c0.167,0,0.332-0.047,0.478-0.144l9.163-6.095l0.015-0.01 c0.013-0.01,0.027-0.02,0.037-0.03c0.018-0.013,0.035-0.028,0.048-0.04c0.013-0.012,0.025-0.023,0.035-0.035 c0.017-0.015,0.03-0.032,0.043-0.045c0.01-0.013,0.02-0.025,0.03-0.037c0.013-0.018,0.025-0.035,0.035-0.052 c0.008-0.013,0.018-0.027,0.025-0.038c0.012-0.02,0.022-0.038,0.03-0.058c0.007-0.013,0.013-0.027,0.02-0.04 c0.008-0.022,0.015-0.042,0.023-0.063c0.003-0.013,0.01-0.027,0.013-0.04c0.007-0.025,0.01-0.048,0.015-0.072 c0.002-0.013,0.005-0.027,0.007-0.037c0.003-0.042,0.007-0.079,0.007-0.117V8.954C22.025,8.915,22.022,8.879,22.016,8.84z M12.862,4.464l6.751,4.49l-3.016,2.013l-3.735-2.492V4.464z M11.138,4.464v4.009l-3.735,2.494L4.389,8.954L11.138,4.464z M3.699,10.562L5.853,12l-2.155,1.438V10.562z M11.138,19.536l-6.749-4.491l3.015-2.011l3.735,2.492V19.536z M12,14.035L8.953,12 L12,9.966L15.047,12L12,14.035z M12.862,19.536v-4.009l3.735-2.492l3.016,2.011L12.862,19.536z M20.303,13.438L18.147,12 l2.156-1.438L20.303,13.438z"></path>
</svg>',

		'deviantart'  => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M 18.19 5.636 18.19 2 18.188 2 14.553 2 14.19 2.366 12.474 5.636 11.935 6 5.81 6 5.81 10.994 9.177 10.994 9.477 11.357 5.81 18.363 5.81 22 5.811 22 9.447 22 9.81 21.634 11.526 18.364 12.065 18 18.19 18 18.19 13.006 14.823 13.006 14.523 12.641 18.19 5.636z"></path>
</svg>',

		'digg'        => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M4.5,5.4h2.2V16H1V8.5h3.5V5.4L4.5,5.4z M4.5,14.2v-4H3.2v4H4.5z M7.6,8.5V16h2.2V8.5C9.8,8.5,7.6,8.5,7.6,8.5z M7.6,5.4 v2.2h2.2V5.4C9.8,5.4,7.6,5.4,7.6,5.4z M10.7,8.5h5.7v10.1h-5.7v-1.8h3.5V16h-3.5C10.7,16,10.7,8.5,10.7,8.5z M14.2,14.2v-4h-1.3v4 H14.2z M17.3,8.5H23v10.1h-5.7v-1.8h3.5V16h-3.5C17.3,16,17.3,8.5,17.3,8.5z M20.8,14.2v-4h-1.3v4H20.8z"></path>
</svg>',

		'dribbble'    => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12,22C6.486,22,2,17.514,2,12S6.486,2,12,2c5.514,0,10,4.486,10,10S17.514,22,12,22z M20.434,13.369 c-0.292-0.092-2.644-0.794-5.32-0.365c1.117,3.07,1.572,5.57,1.659,6.09C18.689,17.798,20.053,15.745,20.434,13.369z M15.336,19.876c-0.127-0.749-0.623-3.361-1.822-6.477c-0.019,0.006-0.038,0.013-0.056,0.019c-4.818,1.679-6.547,5.02-6.701,5.334 c1.448,1.129,3.268,1.803,5.243,1.803C13.183,20.555,14.311,20.313,15.336,19.876z M5.654,17.724 c0.193-0.331,2.538-4.213,6.943-5.637c0.111-0.036,0.224-0.07,0.337-0.102c-0.214-0.485-0.448-0.971-0.692-1.45 c-4.266,1.277-8.405,1.223-8.778,1.216c-0.003,0.087-0.004,0.174-0.004,0.261C3.458,14.207,4.29,16.21,5.654,17.724z M3.639,10.264 c0.382,0.005,3.901,0.02,7.897-1.041c-1.415-2.516-2.942-4.631-3.167-4.94C5.979,5.41,4.193,7.613,3.639,10.264z M9.998,3.709 c0.236,0.316,1.787,2.429,3.187,5c3.037-1.138,4.323-2.867,4.477-3.085C16.154,4.286,14.17,3.471,12,3.471 C11.311,3.471,10.641,3.554,9.998,3.709z M18.612,6.612C18.432,6.855,17,8.69,13.842,9.979c0.199,0.407,0.389,0.821,0.567,1.237 c0.063,0.148,0.124,0.295,0.184,0.441c2.842-0.357,5.666,0.215,5.948,0.275C20.522,9.916,19.801,8.065,18.612,6.612z"></path>
</svg>',

		'dropbox'     => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12,6.134L6.069,9.797L2,6.54l5.883-3.843L12,6.134z M2,13.054l5.883,3.843L12,13.459L6.069,9.797L2,13.054z M12,13.459 l4.116,3.439L22,13.054l-4.069-3.257L12,13.459z M22,6.54l-5.884-3.843L12,6.134l5.931,3.663L22,6.54z M12.011,14.2l-4.129,3.426 l-1.767-1.153v1.291l5.896,3.539l5.897-3.539v-1.291l-1.769,1.153L12.011,14.2z"></path>
</svg>',

		'etsy'        => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M9.16033,4.038c0-.27174.02717-.43478.48913-.43478h6.22283c1.087,0,1.68478.92391,2.11957,2.663l.35326,1.38587h1.05978C19.59511,3.712,19.75815,2,19.75815,2s-2.663.29891-4.23913.29891h-7.962L3.29076,2.163v1.1413L4.731,3.57609c1.00543.19022,1.25.40761,1.33152,1.33152,0,0,.08152,2.71739.08152,7.20109s-.08152,7.17391-.08152,7.17391c0,.81522-.32609,1.11413-1.33152,1.30435l-1.44022.27174V22l4.2663-.13587h7.11957c1.60326,0,5.32609.13587,5.32609.13587.08152-.97826.625-5.40761.70652-5.89674H19.7038L18.644,18.52174c-.84239,1.90217-2.06522,2.038-3.42391,2.038H11.1712c-1.3587,0-2.01087-.54348-2.01087-1.712V12.65217s3.0163,0,3.99457.08152c.76087.05435,1.22283.27174,1.46739,1.33152l.32609,1.413h1.16848l-.08152-3.55978.163-3.587H15.02989l-.38043,1.57609c-.24457,1.03261-.40761,1.22283-1.46739,1.33152-1.38587.13587-4.02174.1087-4.02174.1087Z"></path>
</svg>',

		'facebook'    => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M20.007,3H3.993C3.445,3,3,3.445,3,3.993v16.013C3,20.555,3.445,21,3.993,21h8.621v-6.971h-2.346v-2.717h2.346V9.31 c0-2.325,1.42-3.591,3.494-3.591c0.993,0,1.847,0.074,2.096,0.107v2.43l-1.438,0.001c-1.128,0-1.346,0.536-1.346,1.323v1.734h2.69 l-0.35,2.717h-2.34V21h4.587C20.555,21,21,20.555,21,20.007V3.993C21,3.445,20.555,3,20.007,3z"></path>
</svg>',

		'feed'        => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M2,8.667V12c5.515,0,10,4.485,10,10h3.333C15.333,14.637,9.363,8.667,2,8.667z M2,2v3.333 c9.19,0,16.667,7.477,16.667,16.667H22C22,10.955,13.045,2,2,2z M4.5,17C3.118,17,2,18.12,2,19.5S3.118,22,4.5,22S7,20.88,7,19.5 S5.882,17,4.5,17z"></path>
</svg>',

		'flickr'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M6.5,7c-2.75,0-5,2.25-5,5s2.25,5,5,5s5-2.25,5-5S9.25,7,6.5,7z M17.5,7c-2.75,0-5,2.25-5,5s2.25,5,5,5s5-2.25,5-5 S20.25,7,17.5,7z"></path>
</svg>',

		'foursquare'  => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M17.573,2c0,0-9.197,0-10.668,0S5,3.107,5,3.805s0,16.948,0,16.948c0,0.785,0.422,1.077,0.66,1.172 c0.238,0.097,0.892,0.177,1.285-0.275c0,0,5.035-5.843,5.122-5.93c0.132-0.132,0.132-0.132,0.262-0.132h3.26 c1.368,0,1.588-0.977,1.732-1.552c0.078-0.318,0.692-3.428,1.225-6.122l0.675-3.368C19.56,2.893,19.14,2,17.573,2z M16.495,7.22 c-0.053,0.252-0.372,0.518-0.665,0.518c-0.293,0-4.157,0-4.157,0c-0.467,0-0.802,0.318-0.802,0.787v0.508 c0,0.467,0.337,0.798,0.805,0.798c0,0,3.197,0,3.528,0s0.655,0.362,0.583,0.715c-0.072,0.353-0.407,2.102-0.448,2.295 c-0.04,0.193-0.262,0.523-0.655,0.523c-0.33,0-2.88,0-2.88,0c-0.523,0-0.683,0.068-1.033,0.503 c-0.35,0.437-3.505,4.223-3.505,4.223c-0.032,0.035-0.063,0.027-0.063-0.015V4.852c0-0.298,0.26-0.648,0.648-0.648 c0,0,8.228,0,8.562,0c0.315,0,0.61,0.297,0.528,0.683L16.495,7.22z"></path>
</svg>',

		'goodreads'   => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M17.3,17.5c-0.2,0.8-0.5,1.4-1,1.9c-0.4,0.5-1,0.9-1.7,1.2C13.9,20.9,13.1,21,12,21c-0.6,0-1.3-0.1-1.9-0.2 c-0.6-0.1-1.1-0.4-1.6-0.7c-0.5-0.3-0.9-0.7-1.2-1.2c-0.3-0.5-0.5-1.1-0.5-1.7h1.5c0.1,0.5,0.2,0.9,0.5,1.2 c0.2,0.3,0.5,0.6,0.9,0.8c0.3,0.2,0.7,0.3,1.1,0.4c0.4,0.1,0.8,0.1,1.2,0.1c1.4,0,2.5-0.4,3.1-1.2c0.6-0.8,1-2,1-3.5v-1.7h0 c-0.4,0.8-0.9,1.4-1.6,1.9c-0.7,0.5-1.5,0.7-2.4,0.7c-1,0-1.9-0.2-2.6-0.5C8.7,15,8.1,14.5,7.7,14c-0.5-0.6-0.8-1.3-1-2.1 c-0.2-0.8-0.3-1.6-0.3-2.5c0-0.9,0.1-1.7,0.4-2.5c0.3-0.8,0.6-1.5,1.1-2c0.5-0.6,1.1-1,1.8-1.4C10.3,3.2,11.1,3,12,3 c0.5,0,0.9,0.1,1.3,0.2c0.4,0.1,0.8,0.3,1.1,0.5c0.3,0.2,0.6,0.5,0.9,0.8c0.3,0.3,0.5,0.6,0.6,1h0V3.4h1.5V15 C17.6,15.9,17.5,16.7,17.3,17.5z M13.8,14.1c0.5-0.3,0.9-0.7,1.3-1.1c0.3-0.5,0.6-1,0.8-1.6c0.2-0.6,0.3-1.2,0.3-1.9 c0-0.6-0.1-1.2-0.2-1.9c-0.1-0.6-0.4-1.2-0.7-1.7c-0.3-0.5-0.7-0.9-1.3-1.2c-0.5-0.3-1.1-0.5-1.9-0.5s-1.4,0.2-1.9,0.5 c-0.5,0.3-1,0.7-1.3,1.2C8.5,6.4,8.3,7,8.1,7.6C8,8.2,7.9,8.9,7.9,9.5c0,0.6,0.1,1.3,0.2,1.9C8.3,12,8.6,12.5,8.9,13 c0.3,0.5,0.8,0.8,1.3,1.1c0.5,0.3,1.1,0.4,1.9,0.4C12.7,14.5,13.3,14.4,13.8,14.1z"></path>
</svg>',

		'google-plus' => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M8,11h6.61c0.06,0.35,0.11,0.7,0.11,1.16c0,4-2.68,6.84-6.72,6.84c-3.87,0-7-3.13-7-7s3.13-7,7-7 c1.89,0,3.47,0.69,4.69,1.83l-1.9,1.83C10.27,8.16,9.36,7.58,8,7.58c-2.39,0-4.34,1.98-4.34,4.42S5.61,16.42,8,16.42 c2.77,0,3.81-1.99,3.97-3.02H8V11L8,11z M23,11h-2V9h-2v2h-2v2h2v2h2v-2h2"></path>
</svg>',

		'google'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12.02,10.18v3.72v0.01h5.51c-0.26,1.57-1.67,4.22-5.5,4.22c-3.31,0-6.01-2.75-6.01-6.12s2.7-6.12,6.01-6.12 c1.87,0,3.13,0.8,3.85,1.48l2.84-2.76C16.99,2.99,14.73,2,12.03,2c-5.52,0-10,4.48-10,10s4.48,10,10,10c5.77,0,9.6-4.06,9.6-9.77 c0-0.83-0.11-1.42-0.25-2.05H12.02z"></path>
</svg>',

		'github'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12,2C6.477,2,2,6.477,2,12c0,4.419,2.865,8.166,6.839,9.489c0.5,0.09,0.682-0.218,0.682-0.484 c0-0.236-0.009-0.866-0.014-1.699c-2.782,0.602-3.369-1.34-3.369-1.34c-0.455-1.157-1.11-1.465-1.11-1.465 c-0.909-0.62,0.069-0.608,0.069-0.608c1.004,0.071,1.532,1.03,1.532,1.03c0.891,1.529,2.341,1.089,2.91,0.833 c0.091-0.647,0.349-1.086,0.635-1.337c-2.22-0.251-4.555-1.111-4.555-4.943c0-1.091,0.39-1.984,1.03-2.682 C6.546,8.54,6.202,7.524,6.746,6.148c0,0,0.84-0.269,2.75,1.025C10.295,6.95,11.15,6.84,12,6.836 c0.85,0.004,1.705,0.114,2.504,0.336c1.909-1.294,2.748-1.025,2.748-1.025c0.546,1.376,0.202,2.394,0.1,2.646 c0.64,0.699,1.026,1.591,1.026,2.682c0,3.841-2.337,4.687-4.565,4.935c0.359,0.307,0.679,0.917,0.679,1.852 c0,1.335-0.012,2.415-0.012,2.741c0,0.269,0.18,0.579,0.688,0.481C19.138,20.161,22,16.416,22,12C22,6.477,17.523,2,12,2z"></path>
</svg>',

		'instagram'   => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12,4.622c2.403,0,2.688,0.009,3.637,0.052c0.877,0.04,1.354,0.187,1.671,0.31c0.42,0.163,0.72,0.358,1.035,0.673 c0.315,0.315,0.51,0.615,0.673,1.035c0.123,0.317,0.27,0.794,0.31,1.671c0.043,0.949,0.052,1.234,0.052,3.637 s-0.009,2.688-0.052,3.637c-0.04,0.877-0.187,1.354-0.31,1.671c-0.163,0.42-0.358,0.72-0.673,1.035 c-0.315,0.315-0.615,0.51-1.035,0.673c-0.317,0.123-0.794,0.27-1.671,0.31c-0.949,0.043-1.233,0.052-3.637,0.052 s-2.688-0.009-3.637-0.052c-0.877-0.04-1.354-0.187-1.671-0.31c-0.42-0.163-0.72-0.358-1.035-0.673 c-0.315-0.315-0.51-0.615-0.673-1.035c-0.123-0.317-0.27-0.794-0.31-1.671C4.631,14.688,4.622,14.403,4.622,12 s0.009-2.688,0.052-3.637c0.04-0.877,0.187-1.354,0.31-1.671c0.163-0.42,0.358-0.72,0.673-1.035 c0.315-0.315,0.615-0.51,1.035-0.673c0.317-0.123,0.794-0.27,1.671-0.31C9.312,4.631,9.597,4.622,12,4.622 M12,3 C9.556,3,9.249,3.01,8.289,3.054C7.331,3.098,6.677,3.25,6.105,3.472C5.513,3.702,5.011,4.01,4.511,4.511 c-0.5,0.5-0.808,1.002-1.038,1.594C3.25,6.677,3.098,7.331,3.054,8.289C3.01,9.249,3,9.556,3,12c0,2.444,0.01,2.751,0.054,3.711 c0.044,0.958,0.196,1.612,0.418,2.185c0.23,0.592,0.538,1.094,1.038,1.594c0.5,0.5,1.002,0.808,1.594,1.038 c0.572,0.222,1.227,0.375,2.185,0.418C9.249,20.99,9.556,21,12,21s2.751-0.01,3.711-0.054c0.958-0.044,1.612-0.196,2.185-0.418 c0.592-0.23,1.094-0.538,1.594-1.038c0.5-0.5,0.808-1.002,1.038-1.594c0.222-0.572,0.375-1.227,0.418-2.185 C20.99,14.751,21,14.444,21,12s-0.01-2.751-0.054-3.711c-0.044-0.958-0.196-1.612-0.418-2.185c-0.23-0.592-0.538-1.094-1.038-1.594 c-0.5-0.5-1.002-0.808-1.594-1.038c-0.572-0.222-1.227-0.375-2.185-0.418C14.751,3.01,14.444,3,12,3L12,3z M12,7.378 c-2.552,0-4.622,2.069-4.622,4.622S9.448,16.622,12,16.622s4.622-2.069,4.622-4.622S14.552,7.378,12,7.378z M12,15 c-1.657,0-3-1.343-3-3s1.343-3,3-3s3,1.343,3,3S13.657,15,12,15z M16.804,6.116c-0.596,0-1.08,0.484-1.08,1.08 s0.484,1.08,1.08,1.08c0.596,0,1.08-0.484,1.08-1.08S17.401,6.116,16.804,6.116z"></path>
</svg>',

		'lastfm'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M10.5002,0 C4.7006,0 0,4.70109753 0,10.4998496 C0,16.2989526 4.7006,21 10.5002,21 C16.299,21 21,16.2989526 21,10.4998496 C21,4.70109753 16.299,0 10.5002,0 Z M14.69735,14.7204413 C13.3164,14.7151781 12.4346,14.0870017 11.83445,12.6859357 L11.6816001,12.3451305 L10.35405,9.31011397 C9.92709997,8.26875064 8.85260001,7.57120012 7.68010001,7.57120012 C6.06945001,7.57120012 4.75925001,8.88509738 4.75925001,10.5009524 C4.75925001,12.1164565 6.06945001,13.4303036 7.68010001,13.4303036 C8.77200001,13.4303036 9.76514999,12.827541 10.2719501,11.8567047 C10.2893,11.8235214 10.3239,11.8019673 10.36305,11.8038219 C10.4007,11.8053759 10.43535,11.8287847 10.4504,11.8631709 L10.98655,13.1045863 C11.0016,13.1389726 10.9956,13.17782 10.97225,13.2068931 C10.1605001,14.1995341 8.96020001,14.7683115 7.68010001,14.7683115 C5.33305,14.7683115 3.42340001,12.8535563 3.42340001,10.5009524 C3.42340001,8.14679459 5.33300001,6.23203946 7.68010001,6.23203946 C9.45720002,6.23203946 10.8909,7.19074535 11.6138,8.86359341 C11.6205501,8.88018505 12.3412,10.5707777 12.97445,12.0190621 C13.34865,12.8739575 13.64615,13.3959676 14.6288,13.4291508 C15.5663001,13.4612814 16.25375,12.9121534 16.25375,12.1484869 C16.25375,11.4691321 15.8320501,11.3003585 14.8803,10.98216 C13.2365,10.4397989 12.34495,9.88605929 12.34495,8.51817658 C12.34495,7.1809207 13.26665,6.31615054 14.692,6.31615054 C15.62875,6.31615054 16.3155,6.7286858 16.79215,7.5768142 C16.80495,7.60062396 16.8079001,7.62814302 16.8004001,7.65420843 C16.7929,7.68027384 16.7748,7.70212868 16.7507001,7.713808 L15.86145,8.16900031 C15.8178001,8.19200805 15.7643,8.17807308 15.73565,8.13847371 C15.43295,7.71345711 15.0956,7.52513451 14.6423,7.52513451 C14.05125,7.52513451 13.6220001,7.92899802 13.6220001,8.48649708 C13.6220001,9.17382194 14.1529001,9.34144259 15.0339,9.61923972 C15.14915,9.65578139 15.26955,9.69397731 15.39385,9.73432853 C16.7763,10.1865133 17.57675,10.7311301 17.57675,12.1836251 C17.57685,13.629654 16.3389,14.7204413 14.69735,14.7204413 Z"></path>
</svg>',

		'linkedin'    => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M19.7,3H4.3C3.582,3,3,3.582,3,4.3v15.4C3,20.418,3.582,21,4.3,21h15.4c0.718,0,1.3-0.582,1.3-1.3V4.3 C21,3.582,20.418,3,19.7,3z M8.339,18.338H5.667v-8.59h2.672V18.338z M7.004,8.574c-0.857,0-1.549-0.694-1.549-1.548 c0-0.855,0.691-1.548,1.549-1.548c0.854,0,1.547,0.694,1.547,1.548C8.551,7.881,7.858,8.574,7.004,8.574z M18.339,18.338h-2.669 v-4.177c0-0.996-0.017-2.278-1.387-2.278c-1.389,0-1.601,1.086-1.601,2.206v4.249h-2.667v-8.59h2.559v1.174h0.037 c0.356-0.675,1.227-1.387,2.526-1.387c2.703,0,3.203,1.779,3.203,4.092V18.338z"></path>
</svg>',

		'mail'        => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M20,4H4C2.895,4,2,4.895,2,6v12c0,1.105,0.895,2,2,2h16c1.105,0,2-0.895,2-2V6C22,4.895,21.105,4,20,4z M20,8.236l-8,4.882 L4,8.236V6h16V8.236z"></path>
</svg>',

		'meetup'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M19.24775,14.722a3.57032,3.57032,0,0,1-2.94457,3.52073,3.61886,3.61886,0,0,1-.64652.05634c-.07314-.0008-.10187.02846-.12507.09547A2.38881,2.38881,0,0,1,13.49453,20.094a2.33092,2.33092,0,0,1-1.827-.50716.13635.13635,0,0,0-.19878-.00408,3.191,3.191,0,0,1-2.104.60248,3.26309,3.26309,0,0,1-3.00324-2.71993,2.19076,2.19076,0,0,1-.03512-.30865c-.00156-.08579-.03413-.1189-.11608-.13493a2.86421,2.86421,0,0,1-1.23189-.56111,2.945,2.945,0,0,1-1.166-2.05749,2.97484,2.97484,0,0,1,.87524-2.50774.112.112,0,0,0,.02091-.16107,2.7213,2.7213,0,0,1-.36648-1.48A2.81256,2.81256,0,0,1,6.57673,7.58838a.35764.35764,0,0,0,.28869-.22819,4.2208,4.2208,0,0,1,6.02892-1.90111.25161.25161,0,0,0,.22023.0243,3.65608,3.65608,0,0,1,3.76031.90678A3.57244,3.57244,0,0,1,17.95918,8.626a2.97339,2.97339,0,0,1,.01829.57356.10637.10637,0,0,0,.0853.12792,1.97669,1.97669,0,0,1,1.27939,1.33733,2.00266,2.00266,0,0,1-.57112,2.12652c-.05284.05166-.04168.08328-.01173.13489A3.51189,3.51189,0,0,1,19.24775,14.722Zm-6.35959-.27836a1.6984,1.6984,0,0,0,1.14556,1.61113,3.82039,3.82039,0,0,0,1.036.17935,1.46888,1.46888,0,0,0,.73509-.12255.44082.44082,0,0,0,.26057-.44274.45312.45312,0,0,0-.29211-.43375.97191.97191,0,0,0-.20678-.063c-.21326-.03806-.42754-.0701-.63973-.11215a.54787.54787,0,0,1-.50172-.60926,2.75864,2.75864,0,0,1,.1773-.901c.1763-.535.414-1.045.64183-1.55913A12.686,12.686,0,0,0,15.85,10.47863a1.58461,1.58461,0,0,0,.04861-.87208,1.04531,1.04531,0,0,0-.85432-.83981,1.60658,1.60658,0,0,0-1.23654.16594.27593.27593,0,0,1-.36286-.03413c-.085-.0747-.16594-.15379-.24918-.23055a.98682.98682,0,0,0-1.33577-.04933,6.1468,6.1468,0,0,1-.4989.41615.47762.47762,0,0,1-.51535.03566c-.17448-.09307-.35512-.175-.53531-.25665a1.74949,1.74949,0,0,0-.56476-.2016,1.69943,1.69943,0,0,0-1.61654.91787,8.05815,8.05815,0,0,0-.32952.80126c-.45471,1.2557-.82507,2.53825-1.20838,3.81639a1.24151,1.24151,0,0,0,.51532,1.44389,1.42659,1.42659,0,0,0,1.22008.17166,1.09728,1.09728,0,0,0,.66994-.69764c.44145-1.04111.839-2.09989,1.25981-3.14926.11581-.28876.22792-.57874.35078-.86438a.44548.44548,0,0,1,.69189-.19539.50521.50521,0,0,1,.15044.43836,1.75625,1.75625,0,0,1-.14731.50453c-.27379.69219-.55265,1.38236-.82766,2.074a2.0836,2.0836,0,0,0-.14038.42876.50719.50719,0,0,0,.27082.57722.87236.87236,0,0,0,.66145.02739.99137.99137,0,0,0,.53406-.532q.61571-1.20914,1.228-2.42031.28423-.55863.57585-1.1133a.87189.87189,0,0,1,.29055-.35253.34987.34987,0,0,1,.37634-.01265.30291.30291,0,0,1,.12434.31459.56716.56716,0,0,1-.04655.1915c-.05318.12739-.10286.25669-.16183.38156-.34118.71775-.68754,1.43273-1.02568,2.152A2.00213,2.00213,0,0,0,12.88816,14.44366Zm4.78568,5.28972a.88573.88573,0,0,0-1.77139.00465.8857.8857,0,0,0,1.77139-.00465Zm-14.83838-7.296a.84329.84329,0,1,0,.00827-1.68655.8433.8433,0,0,0-.00827,1.68655Zm10.366-9.43673a.83506.83506,0,1,0-.0091,1.67.83505.83505,0,0,0,.0091-1.67Zm6.85014,5.22a.71651.71651,0,0,0-1.433.0093.71656.71656,0,0,0,1.433-.0093ZM5.37528,6.17908A.63823.63823,0,1,0,6.015,5.54483.62292.62292,0,0,0,5.37528,6.17908Zm6.68214,14.80843a.54949.54949,0,1,0-.55052.541A.54556.54556,0,0,0,12.05742,20.98752Zm8.53235-8.49689a.54777.54777,0,0,0-.54027.54023.53327.53327,0,0,0,.532.52293.51548.51548,0,0,0,.53272-.5237A.53187.53187,0,0,0,20.58977,12.49063ZM7.82846,2.4715a.44927.44927,0,1,0,.44484.44766A.43821.43821,0,0,0,7.82846,2.4715Zm13.775,7.60492a.41186.41186,0,0,0-.40065.39623.40178.40178,0,0,0,.40168.40168A.38994.38994,0,0,0,22,10.48172.39946.39946,0,0,0,21.60349,10.07642ZM5.79193,17.96207a.40469.40469,0,0,0-.397-.39646.399.399,0,0,0-.396.405.39234.39234,0,0,0,.39939.389A.39857.39857,0,0,0,5.79193,17.96207Z"></path>
</svg>',

		'medium'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M20.962,7.257l-5.457,8.867l-3.923-6.375l3.126-5.08c0.112-0.182,0.319-0.286,0.527-0.286c0.05,0,0.1,0.008,0.149,0.02 c0.039,0.01,0.078,0.023,0.114,0.041l5.43,2.715l0.006,0.003c0.004,0.002,0.007,0.006,0.011,0.008 C20.971,7.191,20.98,7.227,20.962,7.257z M9.86,8.592v5.783l5.14,2.57L9.86,8.592z M15.772,17.331l4.231,2.115 C20.554,19.721,21,19.529,21,19.016V8.835L15.772,17.331z M8.968,7.178L3.665,4.527C3.569,4.479,3.478,4.456,3.395,4.456 C3.163,4.456,3,4.636,3,4.938v11.45c0,0.306,0.224,0.669,0.498,0.806l4.671,2.335c0.12,0.06,0.234,0.088,0.337,0.088 c0.29,0,0.494-0.225,0.494-0.602V7.231C9,7.208,8.988,7.188,8.968,7.178z"></path>
</svg>',

		'pinterest'   => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12.289,2C6.617,2,3.606,5.648,3.606,9.622c0,1.846,1.025,4.146,2.666,4.878c0.25,0.111,0.381,0.063,0.439-0.169 c0.044-0.175,0.267-1.029,0.365-1.428c0.032-0.128,0.017-0.237-0.091-0.362C6.445,11.911,6.01,10.75,6.01,9.668 c0-2.777,2.194-5.464,5.933-5.464c3.23,0,5.49,2.108,5.49,5.122c0,3.407-1.794,5.768-4.13,5.768c-1.291,0-2.257-1.021-1.948-2.277 c0.372-1.495,1.089-3.112,1.089-4.191c0-0.967-0.542-1.775-1.663-1.775c-1.319,0-2.379,1.309-2.379,3.059 c0,1.115,0.394,1.869,0.394,1.869s-1.302,5.279-1.54,6.261c-0.405,1.666,0.053,4.368,0.094,4.604 c0.021,0.126,0.167,0.169,0.25,0.063c0.129-0.165,1.699-2.419,2.142-4.051c0.158-0.59,0.817-2.995,0.817-2.995 c0.43,0.784,1.681,1.446,3.013,1.446c3.963,0,6.822-3.494,6.822-7.833C20.394,5.112,16.849,2,12.289,2"></path>
</svg>',

		'pocket'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M21.927,4.194C21.667,3.48,20.982,3,20.222,3h-0.01h-1.721H3.839C3.092,3,2.411,3.47,2.145,4.17 C2.066,4.378,2.026,4.594,2.026,4.814v6.035l0.069,1.2c0.29,2.73,1.707,5.115,3.899,6.778c0.039,0.03,0.079,0.059,0.119,0.089 l0.025,0.018c1.175,0.859,2.491,1.441,3.91,1.727c0.655,0.132,1.325,0.2,1.991,0.2c0.615,0,1.232-0.057,1.839-0.17 c0.073-0.014,0.145-0.028,0.219-0.044c0.02-0.004,0.042-0.012,0.064-0.023c1.359-0.297,2.621-0.864,3.753-1.691l0.025-0.018 c0.04-0.029,0.08-0.058,0.119-0.089c2.192-1.664,3.609-4.049,3.898-6.778l0.069-1.2V4.814C22.026,4.605,22,4.398,21.927,4.194z M17.692,10.481l-4.704,4.512c-0.266,0.254-0.608,0.382-0.949,0.382c-0.342,0-0.684-0.128-0.949-0.382l-4.705-4.512 C5.838,9.957,5.82,9.089,6.344,8.542c0.524-0.547,1.392-0.565,1.939-0.04l3.756,3.601l3.755-3.601 c0.547-0.524,1.415-0.506,1.939,0.04C18.256,9.089,18.238,9.956,17.692,10.481z"></path>
</svg>',

		'reddit'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M22,11.816c0-1.256-1.021-2.277-2.277-2.277c-0.593,0-1.122,0.24-1.526,0.614c-1.481-0.965-3.455-1.594-5.647-1.69 l1.171-3.702l3.18,0.748c0.008,1.028,0.846,1.862,1.876,1.862c1.035,0,1.877-0.842,1.877-1.878c0-1.035-0.842-1.877-1.877-1.877 c-0.769,0-1.431,0.466-1.72,1.13l-3.508-0.826c-0.203-0.047-0.399,0.067-0.46,0.261l-1.35,4.268 c-2.316,0.038-4.411,0.67-5.97,1.671C5.368,9.765,4.853,9.539,4.277,9.539C3.021,9.539,2,10.56,2,11.816 c0,0.814,0.433,1.523,1.078,1.925c-0.037,0.221-0.061,0.444-0.061,0.672c0,3.292,4.011,5.97,8.941,5.97s8.941-2.678,8.941-5.97 c0-0.214-0.02-0.424-0.053-0.632C21.533,13.39,22,12.661,22,11.816z M18.776,4.394c0.606,0,1.1,0.493,1.1,1.1s-0.493,1.1-1.1,1.1 s-1.1-0.494-1.1-1.1S18.169,4.394,18.776,4.394z M2.777,11.816c0-0.827,0.672-1.5,1.499-1.5c0.313,0,0.598,0.103,0.838,0.269 c-0.851,0.676-1.477,1.479-1.812,2.36C2.983,12.672,2.777,12.27,2.777,11.816z M11.959,19.606c-4.501,0-8.164-2.329-8.164-5.193 S7.457,9.22,11.959,9.22s8.164,2.329,8.164,5.193S16.46,19.606,11.959,19.606z M20.636,13.001c-0.326-0.89-0.948-1.701-1.797-2.384 c0.248-0.186,0.55-0.301,0.883-0.301c0.827,0,1.5,0.673,1.5,1.5C21.223,12.299,20.992,12.727,20.636,13.001z M8.996,14.704 c-0.76,0-1.397-0.616-1.397-1.376c0-0.76,0.637-1.397,1.397-1.397c0.76,0,1.376,0.637,1.376,1.397 C10.372,14.088,9.756,14.704,8.996,14.704z M16.401,13.328c0,0.76-0.616,1.376-1.376,1.376c-0.76,0-1.399-0.616-1.399-1.376 c0-0.76,0.639-1.397,1.399-1.397C15.785,11.931,16.401,12.568,16.401,13.328z M15.229,16.708c0.152,0.152,0.152,0.398,0,0.55 c-0.674,0.674-1.727,1.002-3.219,1.002c-0.004,0-0.007-0.002-0.011-0.002c-0.004,0-0.007,0.002-0.011,0.002 c-1.492,0-2.544-0.328-3.218-1.002c-0.152-0.152-0.152-0.398,0-0.55c0.152-0.152,0.399-0.151,0.55,0 c0.521,0.521,1.394,0.775,2.669,0.775c0.004,0,0.007,0.002,0.011,0.002c0.004,0,0.007-0.002,0.011-0.002 c1.275,0,2.148-0.253,2.669-0.775C14.831,16.556,15.078,16.556,15.229,16.708z"></path>
</svg>',

		'skype'       => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M10.113,2.699c0.033-0.006,0.067-0.013,0.1-0.02c0.033,0.017,0.066,0.033,0.098,0.051L10.113,2.699z M2.72,10.223 c-0.006,0.034-0.011,0.069-0.017,0.103c0.018,0.032,0.033,0.064,0.051,0.095L2.72,10.223z M21.275,13.771 c0.007-0.035,0.011-0.071,0.018-0.106c-0.018-0.031-0.033-0.064-0.052-0.095L21.275,13.771z M13.563,21.199 c0.032,0.019,0.065,0.035,0.096,0.053c0.036-0.006,0.071-0.011,0.105-0.017L13.563,21.199z M22,16.386 c0,1.494-0.581,2.898-1.637,3.953c-1.056,1.057-2.459,1.637-3.953,1.637c-0.967,0-1.914-0.251-2.75-0.725 c0.036-0.006,0.071-0.011,0.105-0.017l-0.202-0.035c0.032,0.019,0.065,0.035,0.096,0.053c-0.543,0.096-1.099,0.147-1.654,0.147 c-1.275,0-2.512-0.25-3.676-0.743c-1.125-0.474-2.135-1.156-3.002-2.023c-0.867-0.867-1.548-1.877-2.023-3.002 c-0.493-1.164-0.743-2.401-0.743-3.676c0-0.546,0.049-1.093,0.142-1.628c0.018,0.032,0.033,0.064,0.051,0.095L2.72,10.223 c-0.006,0.034-0.011,0.069-0.017,0.103C2.244,9.5,2,8.566,2,7.615c0-1.493,0.582-2.898,1.637-3.953 c1.056-1.056,2.46-1.638,3.953-1.638c0.915,0,1.818,0.228,2.622,0.655c-0.033,0.007-0.067,0.013-0.1,0.02l0.199,0.031 c-0.032-0.018-0.066-0.034-0.098-0.051c0.002,0,0.003-0.001,0.004-0.001c0.586-0.112,1.187-0.169,1.788-0.169 c1.275,0,2.512,0.249,3.676,0.742c1.124,0.476,2.135,1.156,3.002,2.024c0.868,0.867,1.548,1.877,2.024,3.002 c0.493,1.164,0.743,2.401,0.743,3.676c0,0.575-0.054,1.15-0.157,1.712c-0.018-0.031-0.033-0.064-0.052-0.095l0.034,0.201 c0.007-0.035,0.011-0.071,0.018-0.106C21.754,14.494,22,15.432,22,16.386z M16.817,14.138c0-1.331-0.613-2.743-3.033-3.282 l-2.209-0.49c-0.84-0.192-1.807-0.444-1.807-1.237c0-0.794,0.679-1.348,1.903-1.348c2.468,0,2.243,1.696,3.468,1.696 c0.645,0,1.209-0.379,1.209-1.031c0-1.521-2.435-2.663-4.5-2.663c-2.242,0-4.63,0.952-4.63,3.488c0,1.221,0.436,2.521,2.839,3.123 l2.984,0.745c0.903,0.223,1.129,0.731,1.129,1.189c0,0.762-0.758,1.507-2.129,1.507c-2.679,0-2.307-2.062-3.743-2.062 c-0.645,0-1.113,0.444-1.113,1.078c0,1.236,1.501,2.886,4.856,2.886C15.236,17.737,16.817,16.199,16.817,14.138z"></path>
</svg>',

		'slideshare'  => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M11.738,10.232a2.142,2.142,0,0,1-.721,1.619,2.556,2.556,0,0,1-3.464,0,2.183,2.183,0,0,1,0-3.243,2.572,2.572,0,0,1,3.464,0A2.136,2.136,0,0,1,11.738,10.232Zm5.7,0a2.15,2.15,0,0,1-.715,1.619,2.563,2.563,0,0,1-3.469,0,2.183,2.183,0,0,1,0-3.243,2.58,2.58,0,0,1,3.469,0A2.144,2.144,0,0,1,17.439,10.232Zm2.555,2.045V4.7a2.128,2.128,0,0,0-.363-1.4,1.614,1.614,0,0,0-1.261-.415H5.742a1.656,1.656,0,0,0-1.278.386A2.246,2.246,0,0,0,4.129,4.7v7.643a8.212,8.212,0,0,0,1,.454q.516.193.92.318a6.847,6.847,0,0,0,.92.21q.516.085.806.125a6.615,6.615,0,0,0,.795.045l.665.006q.16,0,.642-.023t.506-.023a1.438,1.438,0,0,1,1.079.307,1.134,1.134,0,0,0,.114.1,7.215,7.215,0,0,0,.693.579q.079-1.033,1.34-.988.057,0,.415.017l.488.023q.13.006.517.011t.6-.011l.619-.051a5.419,5.419,0,0,0,.693-.1l.7-.153a5.353,5.353,0,0,0,.761-.221q.345-.131.766-.307a8.727,8.727,0,0,0,.818-.392Zm1.851-.057a10.4,10.4,0,0,1-4.225,2.862,6.5,6.5,0,0,1-.261,5.281,3.524,3.524,0,0,1-2.078,1.681,2.452,2.452,0,0,1-2.067-.17,1.915,1.915,0,0,1-.931-1.863l-.011-3.7V16.3l-.279-.068q-.188-.045-.267-.057l-.011,3.839a1.9,1.9,0,0,1-.943,1.863,2.481,2.481,0,0,1-2.078.17,3.519,3.519,0,0,1-2.067-1.7,6.546,6.546,0,0,1-.25-5.258A10.4,10.4,0,0,1,2.152,12.22a.56.56,0,0,1-.045-.715q.238-.3.681.011l.125.079a.767.767,0,0,1,.125.091V3.8a1.987,1.987,0,0,1,.534-1.4,1.7,1.7,0,0,1,1.295-.579H19.141a1.7,1.7,0,0,1,1.295.579,1.985,1.985,0,0,1,.534,1.4v7.882l.238-.17q.443-.307.681-.011a.56.56,0,0,1-.045.715Z"></path>
</svg>',

		'snapchat'    => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12.065,2a5.526,5.526,0,0,1,3.132.892A5.854,5.854,0,0,1,17.326,5.4a5.821,5.821,0,0,1,.351,2.33q0,.612-.117,2.487a.809.809,0,0,0,.365.091,1.93,1.93,0,0,0,.664-.176,1.93,1.93,0,0,1,.664-.176,1.3,1.3,0,0,1,.729.234.7.7,0,0,1,.351.6.839.839,0,0,1-.41.7,2.732,2.732,0,0,1-.9.41,3.192,3.192,0,0,0-.9.378.728.728,0,0,0-.41.618,1.575,1.575,0,0,0,.156.56,6.9,6.9,0,0,0,1.334,1.953,5.6,5.6,0,0,0,1.881,1.315,5.875,5.875,0,0,0,1.042.3.42.42,0,0,1,.365.456q0,.911-2.852,1.341a1.379,1.379,0,0,0-.143.507,1.8,1.8,0,0,1-.182.605.451.451,0,0,1-.429.241,5.878,5.878,0,0,1-.807-.085,5.917,5.917,0,0,0-.833-.085,4.217,4.217,0,0,0-.807.065,2.42,2.42,0,0,0-.82.293,6.682,6.682,0,0,0-.755.5q-.351.267-.755.527a3.886,3.886,0,0,1-.989.436A4.471,4.471,0,0,1,11.831,22a4.307,4.307,0,0,1-1.256-.176,3.784,3.784,0,0,1-.976-.436q-.4-.26-.749-.527a6.682,6.682,0,0,0-.755-.5,2.422,2.422,0,0,0-.807-.293,4.432,4.432,0,0,0-.82-.065,5.089,5.089,0,0,0-.853.1,5,5,0,0,1-.762.1.474.474,0,0,1-.456-.241,1.819,1.819,0,0,1-.182-.618,1.411,1.411,0,0,0-.143-.521q-2.852-.429-2.852-1.341a.42.42,0,0,1,.365-.456,5.793,5.793,0,0,0,1.042-.3,5.524,5.524,0,0,0,1.881-1.315,6.789,6.789,0,0,0,1.334-1.953A1.575,1.575,0,0,0,6,12.9a.728.728,0,0,0-.41-.618,3.323,3.323,0,0,0-.9-.384,2.912,2.912,0,0,1-.9-.41.814.814,0,0,1-.41-.684.71.71,0,0,1,.338-.593,1.208,1.208,0,0,1,.716-.241,1.976,1.976,0,0,1,.625.169,2.008,2.008,0,0,0,.69.169.919.919,0,0,0,.416-.091q-.117-1.849-.117-2.474A5.861,5.861,0,0,1,6.385,5.4,5.516,5.516,0,0,1,8.625,2.819,7.075,7.075,0,0,1,12.062,2Z"></path>
</svg>',

		'soundcloud'  => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M8.9,16.1L9,14L8.9,9.5c0-0.1,0-0.1-0.1-0.1c0,0-0.1-0.1-0.1-0.1c-0.1,0-0.1,0-0.1,0.1c0,0-0.1,0.1-0.1,0.1L8.3,14l0.1,2.1 c0,0.1,0,0.1,0.1,0.1c0,0,0.1,0.1,0.1,0.1C8.8,16.3,8.9,16.3,8.9,16.1z M11.4,15.9l0.1-1.8L11.4,9c0-0.1,0-0.2-0.1-0.2 c0,0-0.1,0-0.1,0s-0.1,0-0.1,0c-0.1,0-0.1,0.1-0.1,0.2l0,0.1l-0.1,5c0,0,0,0.7,0.1,2v0c0,0.1,0,0.1,0.1,0.1c0.1,0.1,0.1,0.1,0.2,0.1 c0.1,0,0.1,0,0.2-0.1c0.1,0,0.1-0.1,0.1-0.2L11.4,15.9z M2.4,12.9L2.5,14l-0.2,1.1c0,0.1,0,0.1-0.1,0.1c0,0-0.1,0-0.1-0.1L2.1,14 l0.1-1.1C2.2,12.9,2.3,12.9,2.4,12.9C2.3,12.9,2.4,12.9,2.4,12.9z M3.1,12.2L3.3,14l-0.2,1.8c0,0.1,0,0.1-0.1,0.1 c-0.1,0-0.1,0-0.1-0.1L2.8,14L3,12.2C3,12.2,3,12.2,3.1,12.2C3.1,12.2,3.1,12.2,3.1,12.2z M3.9,11.9L4.1,14l-0.2,2.1 c0,0.1,0,0.1-0.1,0.1c-0.1,0-0.1,0-0.1-0.1L3.5,14l0.2-2.1c0-0.1,0-0.1,0.1-0.1C3.9,11.8,3.9,11.8,3.9,11.9z M4.7,11.9L4.9,14 l-0.2,2.1c0,0.1-0.1,0.1-0.1,0.1c-0.1,0-0.1,0-0.1-0.1L4.3,14l0.2-2.2c0-0.1,0-0.1,0.1-0.1C4.7,11.7,4.7,11.8,4.7,11.9z M5.6,12 l0.2,2l-0.2,2.1c0,0.1-0.1,0.1-0.1,0.1c0,0-0.1,0-0.1,0c0,0,0-0.1,0-0.1L5.1,14l0.2-2c0,0,0-0.1,0-0.1s0.1,0,0.1,0 C5.5,11.9,5.5,11.9,5.6,12L5.6,12z M6.4,10.7L6.6,14l-0.2,2.1c0,0,0,0.1,0,0.1c0,0-0.1,0-0.1,0c-0.1,0-0.1-0.1-0.2-0.2L5.9,14 l0.2-3.3c0-0.1,0.1-0.2,0.2-0.2c0,0,0.1,0,0.1,0C6.4,10.7,6.4,10.7,6.4,10.7z M7.2,10l0.2,4.1l-0.2,2.1c0,0,0,0.1,0,0.1 c0,0-0.1,0-0.1,0c-0.1,0-0.2-0.1-0.2-0.2l-0.1-2.1L6.8,10c0-0.1,0.1-0.2,0.2-0.2c0,0,0.1,0,0.1,0S7.2,9.9,7.2,10z M8,9.6L8.2,14 L8,16.1c0,0.1-0.1,0.2-0.2,0.2c-0.1,0-0.2-0.1-0.2-0.2L7.5,14l0.1-4.4c0-0.1,0-0.1,0.1-0.1c0,0,0.1-0.1,0.1-0.1c0.1,0,0.1,0,0.1,0.1 C8,9.6,8,9.6,8,9.6z M11.4,16.1L11.4,16.1L11.4,16.1z M9.7,9.6L9.8,14l-0.1,2.1c0,0.1,0,0.1-0.1,0.2s-0.1,0.1-0.2,0.1 c-0.1,0-0.1,0-0.1-0.1s-0.1-0.1-0.1-0.2L9.2,14l0.1-4.4c0-0.1,0-0.1,0.1-0.2s0.1-0.1,0.2-0.1c0.1,0,0.1,0,0.2,0.1S9.7,9.5,9.7,9.6 L9.7,9.6z M10.6,9.8l0.1,4.3l-0.1,2c0,0.1,0,0.1-0.1,0.2c0,0-0.1,0.1-0.2,0.1c-0.1,0-0.1,0-0.2-0.1c0,0-0.1-0.1-0.1-0.2L10,14 l0.1-4.3c0-0.1,0-0.1,0.1-0.2c0,0,0.1-0.1,0.2-0.1c0.1,0,0.1,0,0.2,0.1S10.6,9.7,10.6,9.8z M12.4,14l-0.1,2c0,0.1,0,0.1-0.1,0.2 c-0.1,0.1-0.1,0.1-0.2,0.1c-0.1,0-0.1,0-0.2-0.1c-0.1-0.1-0.1-0.1-0.1-0.2l-0.1-1l-0.1-1l0.1-5.5v0c0-0.1,0-0.2,0.1-0.2 c0.1,0,0.1-0.1,0.2-0.1c0,0,0.1,0,0.1,0c0.1,0,0.1,0.1,0.1,0.2L12.4,14z M22.1,13.9c0,0.7-0.2,1.3-0.7,1.7c-0.5,0.5-1.1,0.7-1.7,0.7 h-6.8c-0.1,0-0.1,0-0.2-0.1c-0.1-0.1-0.1-0.1-0.1-0.2V8.2c0-0.1,0.1-0.2,0.2-0.3c0.5-0.2,1-0.3,1.6-0.3c1.1,0,2.1,0.4,2.9,1.1 c0.8,0.8,1.3,1.7,1.4,2.8c0.3-0.1,0.6-0.2,1-0.2c0.7,0,1.3,0.2,1.7,0.7C21.8,12.6,22.1,13.2,22.1,13.9L22.1,13.9z"></path>
</svg>',

		'spotify'     => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12,2C6.477,2,2,6.477,2,12c0,5.523,4.477,10,10,10c5.523,0,10-4.477,10-10C22,6.477,17.523,2,12,2 M16.586,16.424 c-0.18,0.295-0.563,0.387-0.857,0.207c-2.348-1.435-5.304-1.76-8.785-0.964c-0.335,0.077-0.67-0.133-0.746-0.469 c-0.077-0.335,0.132-0.67,0.469-0.746c3.809-0.871,7.077-0.496,9.713,1.115C16.673,15.746,16.766,16.13,16.586,16.424 M17.81,13.7 c-0.226,0.367-0.706,0.482-1.072,0.257c-2.687-1.652-6.785-2.131-9.965-1.166C6.36,12.917,5.925,12.684,5.8,12.273 C5.675,11.86,5.908,11.425,6.32,11.3c3.632-1.102,8.147-0.568,11.234,1.328C17.92,12.854,18.035,13.335,17.81,13.7 M17.915,10.865 c-3.223-1.914-8.54-2.09-11.618-1.156C5.804,9.859,5.281,9.58,5.131,9.086C4.982,8.591,5.26,8.069,5.755,7.919 c3.532-1.072,9.404-0.865,13.115,1.338c0.445,0.264,0.59,0.838,0.327,1.282C18.933,10.983,18.359,11.129,17.915,10.865"></path>
</svg>',

		'stumbleupon' => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12,4.294c-2.469,0-4.471,2.002-4.471,4.471v6.353c0,0.585-0.474,1.059-1.059,1.059c-0.585,0-1.059-0.474-1.059-1.059 v-2.824H2v2.941c0,2.469,2.002,4.471,4.471,4.471c2.469,0,4.471-2.002,4.471-4.471V8.765c0-0.585,0.474-1.059,1.059-1.059 s1.059,0.474,1.059,1.059v1.294l1.412,0.647l2-0.647V8.765C16.471,6.296,14.469,4.294,12,4.294z M13.059,12.353v2.882 c0,2.469,2.002,4.471,4.471,4.471S22,17.704,22,15.235v-2.824h-3.412v2.824c0,0.585-0.474,1.059-1.059,1.059 c-0.585,0-1.059-0.474-1.059-1.059v-2.882l-2,0.647L13.059,12.353z"></path>
</svg>',

		'tumblr'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M16.749,17.396c-0.357,0.17-1.041,0.319-1.551,0.332c-1.539,0.041-1.837-1.081-1.85-1.896V9.847h3.861V6.937h-3.847V2.039 c0,0-2.77,0-2.817,0c-0.046,0-0.127,0.041-0.138,0.144c-0.165,1.499-0.867,4.13-3.783,5.181v2.484h1.945v6.282 c0,2.151,1.587,5.206,5.775,5.135c1.413-0.024,2.982-0.616,3.329-1.126L16.749,17.396z"></path>
</svg>',

		'twitch'      => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M16.499,8.089h-1.636v4.91h1.636V8.089z M12,8.089h-1.637v4.91H12V8.089z M4.228,3.178L3,6.451v13.092h4.499V22h2.456 l2.454-2.456h3.681L21,14.636V3.178H4.228z M19.364,13.816l-2.864,2.865H12l-2.453,2.453V16.68H5.863V4.814h13.501V13.816z"></path>
</svg>',

		'twitter'     => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M22.23,5.924c-0.736,0.326-1.527,0.547-2.357,0.646c0.847-0.508,1.498-1.312,1.804-2.27 c-0.793,0.47-1.671,0.812-2.606,0.996C18.324,4.498,17.257,4,16.077,4c-2.266,0-4.103,1.837-4.103,4.103 c0,0.322,0.036,0.635,0.106,0.935C8.67,8.867,5.647,7.234,3.623,4.751C3.27,5.357,3.067,6.062,3.067,6.814 c0,1.424,0.724,2.679,1.825,3.415c-0.673-0.021-1.305-0.206-1.859-0.513c0,0.017,0,0.034,0,0.052c0,1.988,1.414,3.647,3.292,4.023 c-0.344,0.094-0.707,0.144-1.081,0.144c-0.264,0-0.521-0.026-0.772-0.074c0.522,1.63,2.038,2.816,3.833,2.85 c-1.404,1.1-3.174,1.756-5.096,1.756c-0.331,0-0.658-0.019-0.979-0.057c1.816,1.164,3.973,1.843,6.29,1.843 c7.547,0,11.675-6.252,11.675-11.675c0-0.178-0.004-0.355-0.012-0.531C20.985,7.47,21.68,6.747,22.23,5.924z"></path>
</svg>',

		'vimeo'       => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M22.396,7.164c-0.093,2.026-1.507,4.799-4.245,8.32C15.322,19.161,12.928,21,10.97,21c-1.214,0-2.24-1.119-3.079-3.359 c-0.56-2.053-1.119-4.106-1.68-6.159C5.588,9.243,4.921,8.122,4.206,8.122c-0.156,0-0.701,0.328-1.634,0.98L1.594,7.841 c1.027-0.902,2.04-1.805,3.037-2.708C6.001,3.95,7.03,3.327,7.715,3.264c1.619-0.156,2.616,0.951,2.99,3.321 c0.404,2.557,0.685,4.147,0.841,4.769c0.467,2.121,0.981,3.181,1.542,3.181c0.435,0,1.09-0.688,1.963-2.065 c0.871-1.376,1.338-2.422,1.401-3.142c0.125-1.187-0.343-1.782-1.401-1.782c-0.498,0-1.012,0.115-1.541,0.341 c1.023-3.35,2.977-4.977,5.862-4.884C21.511,3.066,22.52,4.453,22.396,7.164z"></path>
</svg>',

		'vk'          => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M22,7.1c0.2,0.4-0.4,1.5-1.6,3.1c-0.2,0.2-0.4,0.5-0.7,0.9c-0.5,0.7-0.9,1.1-0.9,1.4c-0.1,0.3-0.1,0.6,0.1,0.8 c0.1,0.1,0.4,0.4,0.8,0.9h0l0,0c1,0.9,1.6,1.7,2,2.3c0,0,0,0.1,0.1,0.1c0,0.1,0,0.1,0.1,0.3c0,0.1,0,0.2,0,0.4 c0,0.1-0.1,0.2-0.3,0.3c-0.1,0.1-0.4,0.1-0.6,0.1l-2.7,0c-0.2,0-0.4,0-0.6-0.1c-0.2-0.1-0.4-0.1-0.5-0.2l-0.2-0.1 c-0.2-0.1-0.5-0.4-0.7-0.7s-0.5-0.6-0.7-0.8c-0.2-0.2-0.4-0.4-0.6-0.6C14.8,15,14.6,15,14.4,15c0,0,0,0-0.1,0c0,0-0.1,0.1-0.2,0.2 c-0.1,0.1-0.2,0.2-0.2,0.3c-0.1,0.1-0.1,0.3-0.2,0.5c-0.1,0.2-0.1,0.5-0.1,0.8c0,0.1,0,0.2,0,0.3c0,0.1-0.1,0.2-0.1,0.2l0,0.1 c-0.1,0.1-0.3,0.2-0.6,0.2h-1.2c-0.5,0-1,0-1.5-0.2c-0.5-0.1-1-0.3-1.4-0.6s-0.7-0.5-1.1-0.7s-0.6-0.4-0.7-0.6l-0.3-0.3 c-0.1-0.1-0.2-0.2-0.3-0.3s-0.4-0.5-0.7-0.9s-0.7-1-1.1-1.6c-0.4-0.6-0.8-1.3-1.3-2.2C2.9,9.4,2.5,8.5,2.1,7.5C2,7.4,2,7.3,2,7.2 c0-0.1,0-0.1,0-0.2l0-0.1c0.1-0.1,0.3-0.2,0.6-0.2l2.9,0c0.1,0,0.2,0,0.2,0.1S5.9,6.9,5.9,7L6,7c0.1,0.1,0.2,0.2,0.3,0.3 C6.4,7.7,6.5,8,6.7,8.4C6.9,8.8,7,9,7.1,9.2l0.2,0.3c0.2,0.4,0.4,0.8,0.6,1.1c0.2,0.3,0.4,0.5,0.5,0.7s0.3,0.3,0.4,0.4 c0.1,0.1,0.3,0.1,0.4,0.1c0.1,0,0.2,0,0.3-0.1c0,0,0,0,0.1-0.1c0,0,0.1-0.1,0.1-0.2c0.1-0.1,0.1-0.3,0.1-0.5c0-0.2,0.1-0.5,0.1-0.8 c0-0.4,0-0.8,0-1.3c0-0.3,0-0.5-0.1-0.8c0-0.2-0.1-0.4-0.1-0.5L9.6,7.6C9.4,7.3,9.1,7.2,8.7,7.1C8.6,7.1,8.6,7,8.7,6.9 C8.9,6.7,9,6.6,9.1,6.5c0.4-0.2,1.2-0.3,2.5-0.3c0.6,0,1,0.1,1.4,0.1c0.1,0,0.3,0.1,0.3,0.1c0.1,0.1,0.2,0.1,0.2,0.3 c0,0.1,0.1,0.2,0.1,0.3s0,0.3,0,0.5c0,0.2,0,0.4,0,0.6c0,0.2,0,0.4,0,0.7c0,0.3,0,0.6,0,0.9c0,0.1,0,0.2,0,0.4c0,0.2,0,0.4,0,0.5 c0,0.1,0,0.3,0,0.4s0.1,0.3,0.1,0.4c0.1,0.1,0.1,0.2,0.2,0.3c0.1,0,0.1,0,0.2,0c0.1,0,0.2,0,0.3-0.1c0.1-0.1,0.2-0.2,0.4-0.4 s0.3-0.4,0.5-0.7c0.2-0.3,0.5-0.7,0.7-1.1c0.4-0.7,0.8-1.5,1.1-2.3c0-0.1,0.1-0.1,0.1-0.2c0-0.1,0.1-0.1,0.1-0.1l0,0l0.1,0 c0,0,0,0,0.1,0s0.2,0,0.2,0l3,0c0.3,0,0.5,0,0.7,0S21.9,7,21.9,7L22,7.1z"></path>
</svg>',

		'wordpress'   => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12.158,12.786L9.46,20.625c0.806,0.237,1.657,0.366,2.54,0.366c1.047,0,2.051-0.181,2.986-0.51 c-0.024-0.038-0.046-0.079-0.065-0.124L12.158,12.786z M3.009,12c0,3.559,2.068,6.634,5.067,8.092L3.788,8.341 C3.289,9.459,3.009,10.696,3.009,12z M18.069,11.546c0-1.112-0.399-1.881-0.741-2.48c-0.456-0.741-0.883-1.368-0.883-2.109 c0-0.826,0.627-1.596,1.51-1.596c0.04,0,0.078,0.005,0.116,0.007C16.472,3.904,14.34,3.009,12,3.009 c-3.141,0-5.904,1.612-7.512,4.052c0.211,0.007,0.41,0.011,0.579,0.011c0.94,0,2.396-0.114,2.396-0.114 C7.947,6.93,8.004,7.642,7.52,7.699c0,0-0.487,0.057-1.029,0.085l3.274,9.739l1.968-5.901l-1.401-3.838 C9.848,7.756,9.389,7.699,9.389,7.699C8.904,7.67,8.961,6.93,9.446,6.958c0,0,1.484,0.114,2.368,0.114 c0.94,0,2.397-0.114,2.397-0.114c0.485-0.028,0.542,0.684,0.057,0.741c0,0-0.488,0.057-1.029,0.085l3.249,9.665l0.897-2.996 C17.841,13.284,18.069,12.316,18.069,11.546z M19.889,7.686c0.039,0.286,0.06,0.593,0.06,0.924c0,0.912-0.171,1.938-0.684,3.22 l-2.746,7.94c2.673-1.558,4.47-4.454,4.47-7.771C20.991,10.436,20.591,8.967,19.889,7.686z M12,22C6.486,22,2,17.514,2,12 C2,6.486,6.486,2,12,2c5.514,0,10,4.486,10,10C22,17.514,17.514,22,12,22z"></path>
</svg>',

		'yelp'        => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M12.271,16.718v1.417q-.011,3.257-.067,3.4a.707.707,0,0,1-.569.446,4.637,4.637,0,0,1-2.024-.424A4.609,4.609,0,0,1,7.8,20.565a.844.844,0,0,1-.19-.4.692.692,0,0,1,.044-.29,3.181,3.181,0,0,1,.379-.524q.335-.412,2.019-2.409.011,0,.669-.781a.757.757,0,0,1,.44-.274.965.965,0,0,1,.552.039.945.945,0,0,1,.418.324.732.732,0,0,1,.139.468Zm-1.662-2.8a.783.783,0,0,1-.58.781l-1.339.435q-3.067.981-3.257.981a.711.711,0,0,1-.6-.4,2.636,2.636,0,0,1-.19-.836,9.134,9.134,0,0,1,.011-1.857,3.559,3.559,0,0,1,.335-1.389.659.659,0,0,1,.625-.357,22.629,22.629,0,0,1,2.253.859q.781.324,1.283.524l.937.379a.771.771,0,0,1,.4.34A.982.982,0,0,1,10.609,13.917Zm9.213,3.313a4.467,4.467,0,0,1-1.021,1.8,4.559,4.559,0,0,1-1.512,1.417.671.671,0,0,1-.7-.078q-.156-.112-2.052-3.2l-.524-.859a.761.761,0,0,1-.128-.513.957.957,0,0,1,.217-.513.774.774,0,0,1,.926-.29q.011.011,1.327.446,2.264.736,2.7.887a2.082,2.082,0,0,1,.524.229.673.673,0,0,1,.245.68Zm-7.5-7.049q.056,1.137-.6,1.361-.647.19-1.272-.792L6.237,4.08a.7.7,0,0,1,.212-.691,5.788,5.788,0,0,1,2.314-1,5.928,5.928,0,0,1,2.5-.352.681.681,0,0,1,.547.5q.034.2.245,3.407T12.327,10.181Zm7.384,1.2a.679.679,0,0,1-.29.658q-.167.112-3.67.959-.747.167-1.015.257l.011-.022a.769.769,0,0,1-.513-.044.914.914,0,0,1-.413-.357.786.786,0,0,1,0-.971q.011-.011.836-1.137,1.394-1.908,1.673-2.275a2.423,2.423,0,0,1,.379-.435A.7.7,0,0,1,17.435,8a4.482,4.482,0,0,1,1.372,1.489,4.81,4.81,0,0,1,.9,1.868v.034Z"></path>
</svg>',

		'youtube'     => '
<svg viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
	<path d="M21.8,8.001c0,0-0.195-1.378-0.795-1.985c-0.76-0.797-1.613-0.801-2.004-0.847c-2.799-0.202-6.997-0.202-6.997-0.202 h-0.009c0,0-4.198,0-6.997,0.202C4.608,5.216,3.756,5.22,2.995,6.016C2.395,6.623,2.2,8.001,2.2,8.001S2,9.62,2,11.238v1.517 c0,1.618,0.2,3.237,0.2,3.237s0.195,1.378,0.795,1.985c0.761,0.797,1.76,0.771,2.205,0.855c1.6,0.153,6.8,0.201,6.8,0.201 s4.203-0.006,7.001-0.209c0.391-0.047,1.243-0.051,2.004-0.847c0.6-0.607,0.795-1.985,0.795-1.985s0.2-1.618,0.2-3.237v-1.517 C22,9.62,21.8,8.001,21.8,8.001z M9.935,14.594l-0.001-5.62l5.404,2.82L9.935,14.594z"></path>
</svg>',

	);

}
class-view.php000066600000036373151120041030007335 0ustar00<?php
/**
 * TablePress Base View with members and methods for all views
 *
 * @package TablePress
 * @subpackage Views
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress Base View class
 * @package TablePress
 * @subpackage Views
 * @author Tobias Bäthge
 * @since 1.0.0
 */
abstract class TablePress_View {

	/**
	 * Data for the view.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $data = array();

	/**
	 * Number of screen columns for post boxes.
	 *
	 * @since 1.0.0
	 * @var int
	 */
	protected $screen_columns = 0;

	/**
	 * User action for this screen.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	protected $action = '';

	/**
	 * Instance of the Admin Page Helper Class, with necessary functions.
	 *
	 * @since 1.0.0
	 * @var TablePress_Admin_Page
	 */
	protected $admin_page;

	/**
	 * List of text boxes (similar to post boxes, but just with text and without extra functionality).
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $textboxes = array();

	/**
	 * List of messages that are to be displayed as boxes below the page title.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $header_messages = array();

	/**
	 * Whether there are post boxes registered for this screen,
	 * is automatically set to true, when a meta box is added.
	 *
	 * @since 1.0.0
	 * @var bool
	 */
	protected $has_meta_boxes = false;

	/**
	 * List of WP feature pointers for this view.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $wp_pointers = array();

	/**
	 * Initialize the View class, by setting the correct screen columns and adding help texts.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$screen = get_current_screen();
		if ( 0 !== $this->screen_columns ) {
			$screen->add_option( 'layout_columns', array( 'max' => $this->screen_columns ) );
		}
		// Enable two column layout.
		add_filter( "get_user_option_screen_layout_{$screen->id}", array( $this, 'set_current_screen_layout_columns' ) );

		$screen->add_help_tab( array(
			'id'      => 'tablepress-help', // This should be unique for the screen.
			'title'   => __( 'TablePress Help', 'tablepress' ),
			'content' => '<p>' . $this->help_tab_content() . '</p>'
						. '<p>' . sprintf( __( 'More information about TablePress can be found on the <a href="%1$s">plugin&#8217;s website</a> or on its page in the <a href="%2$s">WordPress Plugin Directory</a>.', 'tablepress' ), 'https://tablepress.org/', 'https://wordpress.org/plugins/tablepress/' ) . ' '
						. sprintf( __( 'For technical information, please see the <a href="%s">documentation</a>.', 'tablepress' ), 'https://tablepress.org/documentation/' ) . ' '
						. sprintf( __( '<a href="%1$s">Support</a> is provided through the <a href="%2$s">WordPress Support Forums</a>.', 'tablepress' ), 'https://tablepress.org/support/', 'https://wordpress.org/tags/tablepress' ) . ' '
						. sprintf( __( 'Before asking for support, please carefully read the <a href="%s">Frequently Asked Questions</a>, where you will find answers to the most common questions, and search through the forums.', 'tablepress' ), 'https://tablepress.org/faq/' ) . '<br />'
						. sprintf( __( 'If you like the plugin, <a href="%1$s"><strong>a donation</strong></a> is recommended.', 'tablepress' ), 'https://tablepress.org/donate/' ) . '</p>',
		) );
		// "sidebar" in the help tab.
		$screen->set_help_sidebar( '<p><strong>' . __( 'For more information:', 'tablepress' ) . '</strong></p><p><a href="https://tablepress.org/" target="_blank">TablePress Website</a></p><p><a href="https://tablepress.org/faq/" target="_blank">TablePress FAQ</a></p><p><a href="https://tablepress.org/documentation/" target="_blank">TablePress Documentation</a></p><p><a href="https://tablepress.org/support/" target="_blank">TablePress Support</a></p>' );
	}

	/**
	 * Change the value of the user option "screen_layout_{$screen->id}" through a filter.
	 *
	 * @since 1.0.0
	 *
	 * @param int|bool Current value of the user option.
	 * @return int New value for the user option.
	 */
	public function set_current_screen_layout_columns( $result ) {
		if ( false === $result ) {
			// The user option does not yet exist.
			$result = $this->screen_columns;
		} elseif ( $result > $this->screen_columns ) {
			// The value of the user option is bigger than what is possible on this screen (e.g. because the number of columns was reduced in an update).
			$result = $this->screen_columns;
		}
		return $result;
	}

	/**
	 * Set up the view with data and do things that are necessary for all views.
	 *
	 * @since 1.0.0
	 *
	 * @param string $action Action for this view.
	 * @param array  $data   Data for this view.
	 */
	public function setup( $action, array $data ) {
		$this->action = $action;
		$this->data = $data;

		// Set page title.
		$GLOBALS['title'] = sprintf( __( '%1$s &lsaquo; %2$s', 'tablepress' ), $this->data['view_actions'][ $this->action ]['page_title'], 'TablePress' );

		// Admin page helpers, like script/style loading, could be moved to view.
		$this->admin_page = TablePress::load_class( 'TablePress_Admin_Page', 'class-admin-page-helper.php', 'classes' );
		$this->admin_page->enqueue_style( 'common' );
		// RTL styles for the admin interface.
		if ( is_rtl() ) {
			$this->admin_page->enqueue_style( 'common-rtl', array( 'tablepress-common' ) );
		}
		$this->admin_page->enqueue_script( 'common', array( 'jquery-core', 'postbox' ), array(
			'common' => array(
				'ays_delete_single_table'    => _n( 'Do you really want to delete this table?', 'Do you really want to delete these tables?', 1, 'tablepress' ),
				'ays_delete_multiple_tables' => _n( 'Do you really want to delete this table?', 'Do you really want to delete these tables?', 2, 'tablepress' ),
			)
		) );

		$this->admin_page->add_admin_footer_text();

		// Initialize WP feature pointers for TablePress.
		$this->_init_wp_pointers();

		// Necessary fields for all views.
		$this->add_text_box( 'default_nonce_fields', array( $this, 'default_nonce_fields' ), 'header', false );
		$this->add_text_box( 'action_nonce_field', array( $this, 'action_nonce_field' ), 'header', false );
		$this->add_text_box( 'action_field', array( $this, 'action_field' ), 'header', false );
	}

	/**
	 * Register a header message for the view.
	 *
	 * @since 1.0.0
	 *
	 * @param string $text  Text for the header message.
	 * @param string $class Optional. Additional CSS class for the header message.
	 */
	protected function add_header_message( $text, $class = 'notice-success' ) {
		if ( ! stripos( $class, 'not-dismissible' ) ) {
			$class .= ' is-dismissible';
		}
		$this->header_messages[] = "<div class=\"notice {$class}\"><p>{$text}</p></div>\n";
	}

	/**
	 * Process header action messages, i.e. check if a message should be added to the page.
	 *
	 * @since 1.0.0
	 *
	 * @param array $action_messages Action messages for the screen.
	 */
	protected function process_action_messages( array $action_messages ) {
		if ( $this->data['message'] && isset( $action_messages[ $this->data['message'] ] ) ) {
			$class = ( 'error' === substr( $this->data['message'], 0, 5 ) ) ? 'notice-error' : 'notice-success';
			$this->add_header_message( "<strong>{$action_messages[ $this->data['message'] ]}</strong>", $class );
		}
	}

	/**
	 * Register a text box for the view.
	 *
	 * @since 1.0.0
	 *
	 * @param string   $id       Unique HTML ID for the text box container (only visible with $wrap = true).
	 * @param callback $callback Callback that prints the contents of the text box.
	 * @param string   $context  Optional. Context/position of the text box (normal, side, additional, header, submit).
	 * @param bool $   wrap      Whether the content of the text box shall be wrapped in a <div> container.
	 */
	protected function add_text_box( $id, $callback, $context = 'normal', $wrap = false ) {
		if ( ! isset( $this->textboxes[ $context ] ) ) {
			$this->textboxes[ $context ] = array();
		}

		$long_id = "tablepress_{$this->action}-{$id}";
		$this->textboxes[ $context ][ $id ] = array(
			'id'       => $long_id,
			'callback' => $callback,
			'context'  => $context,
			'wrap'     => $wrap,
		);
	}

	/**
	 * Register a post meta box for the view, that is drag/droppable with WordPress functionality.
	 *
	 * @since 1.0.0
	 *
	 * @param string   $id            Unique ID for the meta box.
	 * @param string   $title         Title for the meta box.
	 * @param callback $callback      Callback that prints the contents of the post meta box.
	 * @param string   $context       Optional. Context/position of the post meta box (normal, side, additional).
	 * @param string   $priority      Optional. Order of the post meta box for the $context position (high, default, low).
	 * @param bool     $callback_args Optional. Additional data for the callback function (e.g. useful when in different class).
	 */
	protected function add_meta_box( $id, $title, $callback, $context = 'normal', $priority = 'default', $callback_args = null ) {
		$this->has_meta_boxes = true;
		add_meta_box( "tablepress_{$this->action}-{$id}", $title, $callback, null, $context, $priority, $callback_args );
	}

	/**
	 * Render all text boxes for the given context.
	 *
	 * @since 1.0.0
	 *
	 * @param string $context Context (normal, side, additional, header, submit) for which registered text boxes shall be rendered.
	 */
	protected function do_text_boxes( $context ) {
		if ( empty( $this->textboxes[ $context ] ) ) {
			return;
		}

		foreach ( $this->textboxes[ $context ] as $box ) {
			if ( $box['wrap'] ) {
				echo "<div id=\"{$box['id']}\" class=\"textbox\">\n";
			}
			call_user_func( $box['callback'], $this->data, $box );
			if ( $box['wrap'] ) {
				echo "</div>\n";
			}
		}
	}

	/**
	 * Render all post meta boxes for the given context, if there are post meta boxes.
	 *
	 * @since 1.0.0
	 *
	 * @param string $context Context (normal, side, additional) for which registered post meta boxes shall be rendered.
	 */
	protected function do_meta_boxes( $context ) {
		if ( ! $this->has_meta_boxes ) {
			return;
		}
		do_meta_boxes( null, $context, $this->data );
	}

	/**
	 * Print hidden fields with nonces for post meta box AJAX handling, if there are post meta boxes on the screen.
	 *
	 * The check is possible as this function is executed after post meta boxes have to be registered.
	 *
	 * @since 1.0.0
	 *
	 * @param array $data Data for this screen.
	 * @param array $box  Information about the text box.
	 */
	protected function default_nonce_fields( array $data, array $box ) {
		if ( ! $this->has_meta_boxes ) {
			return;
		}
		wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
		echo "\n";
		wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
		echo "\n";
	}

	/**
	 * Print hidden field with a nonce for the screen's action, to be transmitted in HTTP requests.
	 *
	 * @since 1.0.0
	 *
	 * @param array $data Data for this screen.
	 * @param array $box  Information about the text box.
	 */
	protected function action_nonce_field( array $data, array $box ) {
		wp_nonce_field( TablePress::nonce( $this->action ) );
		echo "\n";
	}

	/**
	 * Print hidden field with the screen action.
	 *
	 * @since 1.0.0
	 *
	 * @param array $data Data for this screen.
	 * @param array $box  Information about the text box.
	 */
	protected function action_field( array $data, array $box ) {
		echo "<input type=\"hidden\" name=\"action\" value=\"tablepress_{$this->action}\" />\n";
	}

	/**
	 * Render the current view.
	 *
	 * @since 1.0.0
	 */
	public function render() {
		?>
		<div id="tablepress-page" class="wrap">
		<?php
			$this->print_nav_tab_menu();
			// Print all header messages.
			foreach ( $this->header_messages as $message ) {
				echo $message;
			}
			// "Import" screen has file upload.
			$enctype = ( 'import' === $this->action ) ? ' enctype="multipart/form-data"' : '';
		?>
		<form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post"<?php echo $enctype; ?>>
			<?php
			$this->do_text_boxes( 'header' );
			?>
			<div id="poststuff">
				<div id="post-body" class="metabox-holder columns-<?php echo ( isset( $GLOBALS['screen_layout_columns'] ) && ( 2 === $GLOBALS['screen_layout_columns'] ) ) ? '2' : '1'; ?>">
					<div id="postbox-container-2" class="postbox-container">
						<?php
						$this->do_text_boxes( 'normal' );
						$this->do_meta_boxes( 'normal' );

						$this->do_text_boxes( 'additional' );
						$this->do_meta_boxes( 'additional' );

						// Print all submit buttons.
						$this->do_text_boxes( 'submit' );
						?>
					</div>
					<div id="postbox-container-1" class="postbox-container">
					<?php
						// Print all boxes in the sidebar.
						$this->do_text_boxes( 'side' );
						$this->do_meta_boxes( 'side' );
					?>
					</div>
				</div>
				<br class="clear" />
			</div>
		</form>
		</div>
		<?php
	}

	/**
	 * Render the navigation menu with links to the possible actions, highlighting the current one.
	 *
	 * @since 1.0.0
	 */
	protected function print_nav_tab_menu() {
		?>
		<div id="tablepress-nav" class="nav-tab-wrapper">
			<h1 class="wp-heading-inline"><?php _e( 'TablePress', 'tablepress' ); ?></h1>
			<?php
			foreach ( $this->data['view_actions'] as $action => $entry ) {
				if ( '' === $entry['nav_tab_title'] ) {
					continue;
				}
				if ( ! current_user_can( $entry['required_cap'] ) ) {
					continue;
				}

				$url = esc_url( TablePress::url( array( 'action' => $action ) ) );
				$active = ( $action === $this->action ) ? ' nav-tab-active' : '';
				$separator = ( 'options' === $action ) ? ' nav-tab-separator' : ''; // Make the "Plugin Options" entry a separator, for some spacing.
				echo "<a class=\"nav-tab{$active}{$separator}\" href=\"{$url}\">{$entry['nav_tab_title']}</a>";
			}
			?>
		</div><hr class="wp-header-end" />
		<?php
	}

	/**
	 * Print a submit button (only done when function is used as a callback for a text box).
	 *
	 * @since 1.0.0
	 *
	 * @param array $data Data for this screen.
	 * @param array $box  Information about the text box.
	 */
	protected function textbox_submit_button( array $data, array $box ) {
		$caption = isset( $data['submit_button_caption'] ) ? $data['submit_button_caption'] : __( 'Save Changes', 'tablepress' );
		?>
		<p class="submit"><input type="submit" value="<?php echo esc_attr( $caption ); ?>" class="button button-primary button-large" name="submit" /></p>
		<?php
	}

	/**
	 * Return the content for the help tab for this screen.
	 *
	 * Has to be implemented for every view that is visible in the WP Dashboard!
	 *
	 * @since 1.0.0
	 */
	protected function help_tab_content() {
		// Has to be implemented for every view that is visible in the WP Dashboard!
		return '';
	}

	/**
	 * Initialize the WP feature pointers for TablePress.
	 *
	 * @since 1.0.0
	 */
	protected function _init_wp_pointers() {
		// Check if there are WP pointers for this view.
		if ( empty( $this->wp_pointers ) ) {
			return;
		}

		// Get dismissed pointers.
		$dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );

		$got_pointers = false;
		foreach ( array_diff( $this->wp_pointers, $dismissed ) as $pointer ) {
			// Bind pointer print function.
			add_action( "admin_footer-{$GLOBALS['hook_suffix']}", array( $this, 'wp_pointer_' . $pointer ) );
			$got_pointers = true;
		}

		if ( ! $got_pointers ) {
			return;
		}

		// Add pointers script and style to queue.
		wp_enqueue_style( 'wp-pointer' );
		wp_enqueue_script( 'wp-pointer' );
	}

} // class TablePress_View
class-wp_option.php000066600000007774151120041030010404 0ustar00<?php
/**
 * TablePress WP Option Wrapper class for WordPress Options
 *
 * Wraps the WordPress Options API, so that (especially) arrays are stored as JSON, instead of being serialized by PHP.
 *
 * @package TablePress
 * @subpackage Classes
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress WP Option Wrapper class
 * @package TablePress
 * @subpackage Classes
 * @author Tobias Bäthge
 * @since 1.0.0
 */
class TablePress_WP_Option {

	/**
	 * Name/Key of the Option (in its location in the database).
	 *
	 * @since 1.0.0
	 * @var string
	 */
	protected $option_name;

	/**
	 * Current value of the option.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $option_value;

	/**
	 * Initialize with Option Name.
	 *
	 * @since 1.0.0
	 *
	 * @param array $params {
	 *     @type string $option_name   Name of the Option.
	 *     @type array  $default_value Default values for the Option.
	 * }
	 */
	public function __construct( array $params ) {
		$this->option_name = $params['option_name'];

		$option_value = $this->_get_option( $this->option_name, null );
		if ( ! is_null( $option_value ) ) {
			$this->option_value = (array) json_decode( $option_value, true );
		} else {
			$this->option_value = $params['default_value'];
		}
	}

	/**
	 * Check if Option is set.
	 *
	 * @since 1.0.0
	 *
	 * @param string $name Name of the option to check.
	 * @return bool Whether the option is set.
	 */
	public function is_set( $name ) {
		return isset( $this->option_value[ $name ] );
	}

	/**
	 * Get a single Option, or get all Options.
	 *
	 * @since 1.0.0
	 *
	 * @param string|bool $name          Optional. Name of a single option to get, or false for all options.
	 * @param mixed       $default_value Optional. Default value to return, if a single option $name does not exist.
	 * @return mixed|array Value of the retrieved option $name or $default_value if it does not exist, or all options.
	 */
	public function get( $name = false, $default_value = null ) {
		if ( false === $name ) {
			return $this->option_value;
		}

		// Single Option wanted.
		if ( isset( $this->option_value[ $name ] ) ) {
			return $this->option_value[ $name ];
		} else {
			return $default_value;
		}
	}

	/**
	 * Update Option.
	 *
	 * @since 1.0.0
	 *
	 * @param array $new_options New options (name => value).
	 * @return bool True on success, false on failure.
	 */
	public function update( array $new_options ) {
		$this->option_value = $new_options;
		return $this->_update_option( $this->option_name, wp_json_encode( $this->option_value, TABLEPRESS_JSON_OPTIONS ) );
	}

	/**
	 * Delete Option.
	 *
	 * @since 1.0.0
	 *
	 * @return bool True on success, false on failure.
	 */
	public function delete() {
		return $this->_delete_option( $this->option_name );
	}

	/**
	 * Internal functions mapping - This needs to be re-defined by child classes.
	 */

	/**
	 * Get the value of a WP Option with the WP Options API.
	 *
	 * @since 1.0.0
	 *
	 * @param string $option_name   Name of the WP Option.
	 * @param mixed  $default_value Default value of the WP Option.
	 * @return mixed Current value of the WP Option, or $default_value if it does not exist.
	 */
	protected function _get_option( $option_name, $default_value ) {
		return get_option( $option_name, $default_value );
	}

	/**
	 * Update the value of a WP Option with the WP Options API.
	 *
	 * @since 1.0.0
	 *
	 * @param string $option_name Name of the WP Option.
	 * @param string $new_value   New value of the WP Option.
	 * @return bool True on success, false on failure.
	 */
	protected function _update_option( $option_name, $new_value ) {
		return update_option( $option_name, $new_value );
	}

	/**
	 * Delete a WP Option with the WP Options API.
	 *
	 * @since 1.0.0
	 *
	 * @param string $option_name Name of the WP Option.
	 * @return bool True on success, false on failure.
	 */
	protected function _delete_option( $option_name ) {
		return delete_option( $option_name );
	}

} // class TablePress_WP_Option
class-wp_user_option.php000066600000005606151120041030011432 0ustar00<?php
/**
 * TablePress WP User Option Wrapper class for WordPress Options
 *
 * Wraps the WordPress Options API, so that (especially) arrays are stored as JSON, instead of being serialized by PHP.
 *
 * @package TablePress
 * @subpackage Classes
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

// Load parent class.
TablePress::load_file( 'class-wp_option.php', 'classes' );

/**
 * TablePress WP User Option Wrapper class
 * @package TablePress
 * @subpackage Classes
 * @author Tobias Bäthge
 * @since 1.0.0
 */
class TablePress_WP_User_Option extends TablePress_WP_Option {

	/**
	 * Get the value of a WP User Option with the WP User Options API.
	 *
	 * @since 1.0.0
	 *
	 * @param string $option_name   Name of the WP User Option.
	 * @param mixed  $default_value Default value of the WP User Option.
	 * @return mixed Current value of the WP User Option, or $default_value if it does not exist.
	 */
	protected function _get_option( $option_name, $default_value ) {
		// Non-logged-in user can never have a saved option value.
		if ( ! is_user_logged_in() ) {
			return $default_value;
		}

		$option_value = get_user_option( $option_name );
		// get_user_option() only knows false as the default value, so we have to wrap that.
		if ( false === $option_value ) {
			$option_value = $default_value;
		}
		return $option_value;
	}

	/**
	 * Update the value of a WP User Option with the WP User Options API.
	 *
	 * @since 1.0.0
	 *
	 * @param string $option_name Name of the WP User Option.
	 * @param string $new_value   New value of the WP User Option (not slashed).
	 * @return bool True on success, false on failure.
	 */
	protected function _update_option( $option_name, $new_value ) {
		// Non-logged-in user can never have a saved option value to be updated.
		if ( ! is_user_logged_in() ) {
			return false;
		}

		// WP expects a slashed value.
		$new_value = wp_slash( $new_value );
		return update_user_option( get_current_user_id(), $option_name, $new_value, false );
	}

	/**
	 * Delete a WP User Option with the WP User Options API.
	 *
	 * @since 1.0.0
	 *
	 * @param string $option_name Name of the WP User Option.
	 * @return bool True on success, false on failure.
	 */
	protected function _delete_option( $option_name ) {
		// Non-logged-in user can never have a saved option value to be deleted.
		if ( ! is_user_logged_in() ) {
			return false;
		}

		return delete_user_option( get_current_user_id(), $option_name, false );
	}

	/**
	 * Delete a WP User Option with the WP User Options API, for all users of the site.
	 *
	 * @since 1.0.0
	 */
	public function delete_for_all_users() {
		$users = get_users();
		foreach ( $users as $user ) {
			delete_user_option( $user->ID, $this->option_name, false );
			// @TODO: Add other user options for different actions as well.
		}
	}

} // class TablePress_WP_User_Option
class-import.php000066600000033766151120041030007700 0ustar00<?php
/**
 * TablePress Table Import Class
 *
 * @package TablePress
 * @subpackage Export/Import
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress Table Import Class
 * @package TablePress
 * @subpackage Export/Import
 * @author Tobias Bäthge
 * @since 1.0.0
 */
class TablePress_Import {

	/**
	 * File/Data Formats that are available for import.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	public $import_formats = array();

	/**
	 * Whether ZIP archive support is available in the PHP installation on the server.
	 *
	 * @since 1.0.0
	 * @var bool
	 */
	public $zip_support_available = false;

	/**
	 * Whether HTML import support is available in the PHP installation on the server.
	 *
	 * @since 1.0.0
	 * @var bool
	 */
	public $html_import_support_available = false;

	/**
	 * Data to be imported.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	protected $import_data;

	/**
	 * Imported table.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $imported_table = false;

	/**
	 * Initialize the Import class.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		/** This filter is documented in the WordPress function unzip_file() in wp-admin/includes/file.php */
		if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
			$this->zip_support_available = true;
		}

		if ( class_exists( 'DOMDocument', false ) && function_exists( 'simplexml_import_dom' ) && function_exists( 'libxml_use_internal_errors' ) ) {
			$this->html_import_support_available = true;
		}

		// Initiate here, because function call not possible outside a class method.
		$this->import_formats = array();
		$this->import_formats['csv'] = __( 'CSV - Character-Separated Values', 'tablepress' );
		if ( $this->html_import_support_available ) {
			$this->import_formats['html'] = __( 'HTML - Hypertext Markup Language', 'tablepress' );
		}
		$this->import_formats['json'] = __( 'JSON - JavaScript Object Notation', 'tablepress' );
		$this->import_formats['xls'] = __( 'XLS - Microsoft Excel 97-2003 (experimental)', 'tablepress' );
		$this->import_formats['xlsx'] = __( 'XLSX - Microsoft Excel 2007-2013 (experimental)', 'tablepress' );
	}

	/**
	 * Import a table.
	 *
	 * @since 1.0.0
	 *
	 * @param string $format Import format.
	 * @param string $data   Data to import.
	 * @return bool|array False on error, table array on success.
	 */
	public function import_table( $format, $data ) {
		$this->import_data = apply_filters( 'tablepress_import_table_data', $data, $format );

		if ( ! in_array( $format, array( 'xlsx', 'xls' ) ) ) {
			$this->fix_table_encoding();
		}

		switch ( $format ) {
			case 'csv':
				$this->import_csv();
				break;
			case 'html':
				$this->import_html();
				break;
			case 'json':
				$this->import_json();
				break;
			case 'xlsx':
				$this->import_xlsx();
				break;
			case 'xls':
				$this->import_xls();
				break;
			default:
				return false;
		}

		return $this->imported_table;
	}

	/**
	 * Import CSV data.
	 *
	 * @since 1.0.0
	 */
	protected function import_csv() {
		$csv_parser = TablePress::load_class( 'CSV_Parser', 'csv-parser.class.php', 'libraries' );
		$csv_parser->load_data( $this->import_data );
		$delimiter = $csv_parser->find_delimiter();
		$data = $csv_parser->parse( $delimiter );
		$this->imported_table = array( 'data' => $this->pad_array_to_max_cols( $data ) );
	}

	/**
	 * Import HTML data.
	 *
	 * @since 1.0.0
	 */
	protected function import_html() {
		if ( ! $this->html_import_support_available ) {
			return false;
		}

		if ( false === stripos( $this->import_data, '<table' ) || false === stripos( $this->import_data, '</table>' ) ) {
			$this->imported_table = false;
			return;
		}

		// Prepend XML declaration, for better encoding support.
		$full_html = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . $this->import_data;
		if ( function_exists( 'libxml_disable_entity_loader' ) ) {
			// Don't expand external entities, see https://websec.io/2012/08/27/Preventing-XXE-in-PHP.html.
			libxml_disable_entity_loader( true );
		}
		// No warnings/errors raised, but stored internally.
		libxml_use_internal_errors( true );
		$dom = new DOMDocument( '1.0', 'UTF-8' );
		// No strict checking for invalid HTML.
		$dom->strictErrorChecking = false;
		$dom->loadHTML( $full_html );
		if ( false === $dom ) {
			$this->imported_table = false;
			return;
		}
		$dom_tables = $dom->getElementsByTagName( 'table' );
		if ( 0 === count( $dom_tables ) ) {
			$this->imported_table = false;
			return;
		}
		libxml_clear_errors(); // Clear errors so that we only catch those inside the table in the next line.
		$table = simplexml_import_dom( $dom_tables->item( 0 ) );
		if ( false === $table ) {
			$this->imported_table = false;
			return;
		}

		$errors = libxml_get_errors();
		libxml_clear_errors();
		if ( ! empty( $errors ) ) {
			$output = '<strong>' . __( 'The imported file contains errors:', 'tablepress' ) . '</strong><br /><br />';
			foreach ( $errors as $error ) {
				switch ( $error->level ) {
					case LIBXML_ERR_WARNING:
						$output .= "Warning {$error->code}: {$error->message} in line {$error->line}, column {$error->column}<br />";
						break;
					case LIBXML_ERR_ERROR:
						$output .= "Error {$error->code}: {$error->message} in line {$error->line}, column {$error->column}<br />";
						break;
					case LIBXML_ERR_FATAL:
						$output .= "Fatal Error {$error->code}: {$error->message} in line {$error->line}, column {$error->column}<br />";
						break;
				}
			}
			wp_die( $output, 'Import Error', array( 'response' => 200, 'back_link' => true ) );
		}

		$html_table = array(
			'data'    => array(),
			'options' => array(),
		);
		if ( isset( $table->thead ) ) {
			$html_table['data'] = array_merge( $html_table['data'], $this->_import_html_rows( $table->thead[0]->tr ) );
			$html_table['options']['table_head'] = true;
		}
		if ( isset( $table->tbody ) ) {
			$html_table['data'] = array_merge( $html_table['data'], $this->_import_html_rows( $table->tbody[0]->tr ) );
		}
		if ( isset( $table->tr ) ) {
			$html_table['data'] = array_merge( $html_table['data'], $this->_import_html_rows( $table->tr ) );
		}
		if ( isset( $table->tfoot ) ) {
			$html_table['data'] = array_merge( $html_table['data'], $this->_import_html_rows( $table->tfoot[0]->tr ) );
			$html_table['options']['table_foot'] = true;
		}

		$html_table['data'] = $this->pad_array_to_max_cols( $html_table['data'] );
		$this->imported_table = $html_table;
	}

	/**
	 * Helper for HTML import.
	 *
	 * @since 1.0.0
	 *
	 * @param SimpleXMLElement $element XMLElement.
	 * @return array SimpleXMLElement exported to an array.
	 */
	protected function _import_html_rows( $element ) {
		$rows = array();
		foreach ( $element as $row ) {
			$new_row = array();
			foreach ( $row as $cell ) {
				// Get text between <td>...</td>, or <th>...</th>, possibly with attributes.
				if ( 1 === preg_match( '#<t(?:d|h).*?>(.*)</t(?:d|h)>#is', $cell->asXML(), $matches ) ) {
					/*
					 * Decode HTML entities again, as there might be some left especially in attributes of HTML tags in the cells,
					 * see https://secure.php.net/manual/en/simplexmlelement.asxml.php#107137.
					 */
					$matches[1] = html_entity_decode( $matches[1], ENT_NOQUOTES, 'UTF-8' );
					$new_row[] = $matches[1];

					// Look for colspan and add correct number of cells.
					if ( 1 === preg_match( '#<t(?:d|h).*colspan="(\d+)".*?>#is', $cell->asXml(), $matches ) ) {
						for ( $i = 1; $i < (int) $matches[1]; $i++ ) {
							$new_row[] = '#colspan#';
						}
					}
				} else {
					$new_row[] = '';
				}
			}
			$rows[] = $new_row;
		}
		return $rows;
	}

	/**
	 * Import JSON data.
	 *
	 * @since 1.0.0
	 */
	protected function import_json() {
		$json_table = json_decode( $this->import_data, true );

		// Check if JSON could be decoded.
		if ( is_null( $json_table ) ) {
			// If possible, try to find out what error prevented the JSON from being decoded.
			$json_error = 'The error could not be determined.';
			$json_error_msg = json_last_error_msg();
			if ( false !== $json_error_msg ) {
				$json_error = $json_error_msg;
			}
			$output = '<strong>' . __( 'The imported file contains errors:', 'tablepress' ) . "</strong><br /><br />JSON error: {$json_error}<br />";
			wp_die( $output, 'Import Error', array( 'response' => 200, 'back_link' => true ) );
		} else {
			// Specifically cast to an array again.
			$json_table = (array) $json_table;
		}

		if ( isset( $json_table['data'] ) ) {
			// JSON data contained a full export.
			$table = $json_table;
		} else {
			// JSON data contained only the data of a table, but no options.
			$table = array( 'data' => array() );
			foreach ( $json_table as $row ) {
				$table['data'][] = array_values( (array) $row );
			}
		}

		$table['data'] = $this->pad_array_to_max_cols( $table['data'] );
		$this->imported_table = $table;
	}

	/**
	 * Import Microsoft Excel 97-2003 data.
	 *
	 * @since 1.1.0
	 */
	protected function import_xls() {
		$excel_reader = TablePress::load_class( 'Spreadsheet_Excel_Reader', 'excel-reader.class.php', 'libraries', $this->import_data );

		// Loop through Excel file and retrieve value and colspan/rowspan properties for each cell.
		$sheet = 0; // 0 means first sheet of the Workbook
		$table = array();
		for ( $row = 1; $row <= $excel_reader->rowcount( $sheet ); $row++ ) {
			$table_row = array();
			for ( $col = 1; $col <= $excel_reader->colcount( $sheet ); $col++ ) {
				$cell = array();
				$cell['rowspan'] = $excel_reader->rowspan( $row, $col, $sheet );
				$cell['colspan'] = $excel_reader->colspan( $row, $col, $sheet );
				$cell['val'] = $excel_reader->val( $row, $col, $sheet );
				$table_row[] = $cell;
			}
			$table[] = $table_row;
		}

		// Transform colspan/rowspan properties to TablePress equivalent (cell content).
		foreach ( $table as $row_idx => $row ) {
			foreach ( $row as $col_idx => $cell ) {
				if ( 1 === $cell['rowspan'] && 1 === $cell['colspan'] ) {
					continue;
				}

				if ( 1 < $cell['colspan'] ) {
					for ( $i = 1; $i < $cell['colspan']; $i++ ) {
						$table[ $row_idx ][ $col_idx + $i ]['val'] = '#colspan#';
					}
				}
				if ( 1 < $cell['rowspan'] ) {
					for ( $i = 1; $i < $cell['rowspan']; $i++ ) {
						$table[ $row_idx + $i ][ $col_idx ]['val'] = '#rowspan#';
					}
				}

				if ( 1 < $cell['rowspan'] && 1 < $cell['colspan'] ) {
					for ( $i = 1; $i < $cell['rowspan']; $i++ ) {
						for ( $j = 1; $j < $cell['colspan']; $j++ ) {
							$table[ $row_idx + $i ][ $col_idx + $j ]['val'] = '#span#';
						}
					}
				}
			}
		}

		// Flatten value property to two-dimensional array.
		$result_table = array();
		foreach ( $table as $row_idx => $row ) {
			$table_row = array();
			foreach ( $row as $col_idx => $cell ) {
				$table_row[] = (string) $cell['val'];
			}
			$result_table[] = $table_row;
		}

		$this->imported_table = array( 'data' => $this->pad_array_to_max_cols( $result_table ) );
	}

	/**
	 * Import Microsoft Excel 2007-2013 data.
	 *
	 * @since 1.1.0
	 */
	protected function import_xlsx() {
		TablePress::load_file( 'simplexlsx.class.php', 'libraries' );
		$xlsx_file = SimpleXLSX::parse( $this->import_data, true );

		if ( $xlsx_file ) {
			$this->imported_table = array( 'data' => $xlsx_file->rows() );
		} else {
			$output = '<strong>' . __( 'The imported file contains errors:', 'tablepress' ) . '</strong><br /><br />' . SimpleXLSX::parse_error() . '<br />';
			wp_die( $output, 'Import Error', array( 'response' => 200, 'back_link' => true ) );
		}
	}

	/**
	 * Make sure array is rectangular with $max_cols columns in every row.
	 *
	 * @since 1.0.0
	 *
	 * @param array $array Two-dimensional array to be padded.
	 * @return array Padded array.
	 */
	public function pad_array_to_max_cols( array $array ) {
		$rows = count( $array );
		$rows = ( $rows > 0 ) ? $rows : 1;
		$max_columns = $this->count_max_columns( $array );
		$max_columns = ( $max_columns > 0 ) ? $max_columns : 1;
		// array_map wants arrays as additional parameters, so we create one with the max_columns to pad to and one with the value to use (empty string).
		$max_columns_array = array_fill( 1, $rows, $max_columns );
		$pad_values_array = array_fill( 1, $rows, '' );
		return array_map( 'array_pad', $array, $max_columns_array, $pad_values_array );
	}

	/**
	 * Get the highest number of columns in the rows.
	 *
	 * @since 1.0.0
	 *
	 * @param array $array Two-dimensional array.
	 * @return int Highest number of columns in the rows of the array.
	 */
	protected function count_max_columns( array $array ) {
		$max_columns = 0;
		foreach ( $array as $row_idx => $row ) {
			$num_columns = count( $row );
			$max_columns = max( $num_columns, $max_columns );
		}
		return $max_columns;
	}

	/**
	 * Fixes the encoding to UTF-8 for the entire string that is to be imported.
	 *
	 * @since 1.0.0
	 *
	 * @link http://stevephillips.me/blog/dealing-php-and-character-encoding
	 */
	protected function fix_table_encoding() {
		// Check and remove possible UTF-8 Byte-Order Mark (BOM).
		$bom = pack( 'CCC', 0xef, 0xbb, 0xbf );
		if ( 0 === strncmp( $this->import_data, $bom, 3 ) ) {
			$this->import_data = substr( $this->import_data, 3 );
			// If data has a BOM, it's UTF-8, so further checks unnecessary.
			return;
		}

		// Require the iconv() function for the following checks.
		if ( ! function_exists( 'iconv' ) ) {
			return;
		}

		// Check for possible UTF-16 BOMs ("little endian" and "big endian") and try to convert the data to UTF-8.
		if ( "\xFF\xFE" === substr( $this->import_data, 0, 2 ) || "\xFE\xFF" === substr( $this->import_data, 0, 2 ) ) {
			$data = @iconv( 'UTF-16', 'UTF-8', $this->import_data );
			if ( false !== $data ) {
				$this->import_data = $data;
				return;
			}
		}

		// Detect the character encoding and convert to UTF-8, if it's different.
		if ( function_exists( 'mb_detect_encoding' ) ) {
			$current_encoding = mb_detect_encoding( $this->import_data, 'ASCII, UTF-8, ISO-8859-1' );
			if ( 'UTF-8' !== $current_encoding ) {
				$data = @iconv( $current_encoding, 'UTF-8', $this->import_data );
				if ( false !== $data ) {
					$this->import_data = $data;
					return;
				}
			}
		}
	}

} // class TablePress_Import
class-admin-page-helper.php000066600000010332151120041030011625 0ustar00<?php
/**
 * Admin Page Helper Class for TablePress with functions needed in the admin area
 *
 * @package TablePress
 * @subpackage Views
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * Admin Page class
 * @package TablePress
 * @subpackage Views
 * @author Tobias Bäthge
 * @since 1.0.0
 */
class TablePress_Admin_Page {

	/**
	 * Enqueue a CSS file.
	 *
	 * @since 1.0.0
	 *
	 * @param string $name         Name of the CSS file, without extension.
	 * @param array  $dependencies Optional. List of names of CSS stylesheets that this stylesheet depends on, and which need to be included before this one.
	 */
	public function enqueue_style( $name, array $dependencies = array() ) {
		$suffix = SCRIPT_DEBUG ? '' : '.min';
		$css_file = "admin/css/{$name}{$suffix}.css";
		$css_url = plugins_url( $css_file, TABLEPRESS__FILE__ );
		wp_enqueue_style( "tablepress-{$name}", $css_url, $dependencies, TablePress::version );
	}

	/**
	 * Enqueue a JavaScript file, possibly with dependencies and extra information.
	 *
	 * @since 1.0.0
	 *
	 * @param string $name            Name of the JS file, without extension.
	 * @param array  $dependencies    Optional. List of names of JS scripts that this script depends on, and which need to be included before this one.
	 * @param array  $localize_script Optional. An array with strings that gets transformed into a JS object and is added to the page before the script is included.
	 * @param bool   $force_minified  Optional. Always load the minified version, regardless of SCRIPT_DEBUG constant value.
	 */
	public function enqueue_script( $name, array $dependencies = array(), array $localize_script = array(), $force_minified = false ) {
		$suffix = ( ! $force_minified && SCRIPT_DEBUG ) ? '' : '.min';
		$js_file = "admin/js/{$name}{$suffix}.js";
		$js_url = plugins_url( $js_file, TABLEPRESS__FILE__ );
		wp_enqueue_script( "tablepress-{$name}", $js_url, $dependencies, TablePress::version, true );
		if ( ! empty( $localize_script ) ) {
			foreach ( $localize_script as $var_name => $var_data ) {
				wp_localize_script( "tablepress-{$name}", "tablepress_{$var_name}", $var_data );
			}
		}
	}

	/**
	 * Register a filter hook on the admin footer.
	 *
	 * @since 1.0.0
	 */
	public function add_admin_footer_text() {
		// Show admin footer message (only on TablePress admin screens).
		add_filter( 'admin_footer_text', array( $this, '_admin_footer_text' ) );
	}

	/**
	 * Add a TablePress "Thank You" message to the admin footer content.
	 *
	 * @since 1.0.0
	 *
	 * @param string $content Current admin footer content.
	 * @return string New admin footer content.
	 */
	public function _admin_footer_text( $content ) {
		$content .= ' &bull; ' . sprintf( __( 'Thank you for using <a href="%s">TablePress</a>.', 'tablepress' ), 'https://tablepress.org/' );
		$content .= ' ' . sprintf( __( 'Support the plugin with your <a href="%s">donation</a>!', 'tablepress' ), 'https://tablepress.org/donate/' );
		return $content;
	}

	/**
	 * Print the JavaScript code for a WP feature pointer.
	 *
	 * @since 1.0.0
	 *
	 * @param string $pointer_id The pointer ID.
	 * @param string $selector   The HTML elements, on which the pointer should be attached.
	 * @param array  $args       Arguments to be passed to the pointer JS (see wp-pointer.js).
	 */
	public function print_wp_pointer_js( $pointer_id, $selector, array $args ) {
		if ( empty( $pointer_id ) || empty( $selector ) || empty( $args ) || empty( $args['content'] ) ) {
			return;
		}
		?>
		<script type="text/javascript">
		( function( $ ) {
			var options = <?php echo wp_json_encode( $args, TABLEPRESS_JSON_OPTIONS ); ?>, setup;

			if ( ! options ) {
				return;
			}

			options = $.extend( options, {
				close: function() {
					$.post( ajaxurl, {
						pointer: '<?php echo $pointer_id; ?>',
						action: 'dismiss-wp-pointer'
					} );
				}
			} );

			setup = function() {
				$( '<?php echo $selector; ?>' ).pointer( options ).pointer( 'open' );
			};

			if ( options.position && options.position.defer_loading ) {
				$( window ).bind( 'load.wp-pointers', setup );
			} else {
				$( document ).ready( setup );
			}
		} )( jQuery );
		</script>
		<?php
	}

} // class TablePress_Admin_Page
class-model.php000066600000001114151120041030007444 0ustar00<?php
/**
 * TablePress Base Model with members and methods for all models
 *
 * @package TablePress
 * @subpackage Models
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress Base Model class
 * @package TablePress
 * @subpackage Models
 * @author Tobias Bäthge
 * @since 1.0.0
 */
abstract class TablePress_Model {

	/**
	 * Initialize all models.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Intentionally left blank.
	}

} // class TablePress_Model
class-evaluate.php000066600000016400151120041030010156 0ustar00<?php
/**
 * TablePress Formula Evaluation Class
 *
 * @package TablePress
 * @subpackage Formulas
 * @author Tobias Bäthge
 * @since 1.5.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress Formula Evaluation Class
 *
 * Before TablePress 1.5, this was part of the TablePress_Render class.
 *
 * @package TablePress
 * @subpackage Formulas
 * @author Tobias Bäthge
 * @since 1.5.0
 */
class TablePress_Evaluate {

	/**
	 * Instance of the EvalMath class.
	 *
	 * @since 1.0.0
	 * @var EvalMath
	 */
	protected $evalmath;

	/**
	 * Table data in which formulas shall be evaluated.
	 *
	 * @since 1.5.0
	 * @var array
	 */
	protected $table_data;

	/**
	 * Storage for cell ranges that have been replaced in formulas.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $known_ranges = array();

	/**
	 * Initialize the Formula Evaluation class, include the EvalMath class.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->evalmath = TablePress::load_class( 'EvalMath', 'evalmath.class.php', 'libraries' );
		// Don't raise PHP warnings.
		$this->evalmath->suppress_errors = true;
	}

	/**
	 * Evaluate formulas in the passed table.
	 *
	 * @since 1.0.0
	 *
	 * @param array $table_data Table data in which formulas shall be evaluated.
	 * @return array Table data with evaluated formulas.
	 */
	public function evaluate_table_data( array $table_data ) {
		$this->table_data = $table_data;

		$rows = count( $this->table_data );
		$columns = count( $this->table_data[0] );
		// Use two for-loops instead of foreach here to be sure to always work on the "live" table data and not some in-memory copy.
		for ( $row_idx = 0; $row_idx < $rows; $row_idx++ ) {
			for ( $col_idx = 0; $col_idx < $columns; $col_idx++ ) {
				$this->table_data[ $row_idx ][ $col_idx ] = $this->_evaluate_cell( $this->table_data[ $row_idx ][ $col_idx ] );
			}
		}

		return $this->table_data;
	}

	/**
	 * Parse and evaluate the content of a cell.
	 *
	 * @since 1.0.0
	 *
	 * @param string $content Content of a cell.
	 * @param array  $parents Optional. List of cells that depend on this cell (to prevent circle references).
	 * @return string Result of the parsing/evaluation.
	 */
	protected function _evaluate_cell( $content, array $parents = array() ) {
		if ( '' === $content || '=' === $content || '=' !== $content[0] ) {
			return $content;
		}

		// Cut off the leading =.
		$content = substr( $content, 1 );

		// Support putting formulas in strings, like =Total: {A3+A4}.
		$expressions = array();
		if ( preg_match_all( '#{(.+?)}#', $content, $expressions, PREG_SET_ORDER ) ) {
			$formula_in_string = true;
		} else {
			$formula_in_string = false;
			// Fill array so that it has the same structure as if it came from preg_match_all().
			$expressions[] = array( $content, $content );
		}

		foreach ( $expressions as $expression ) {
			$orig_expression = $expression[0];
			$expression = $expression[1];

			$replaced_references = $replaced_ranges = array();

			// Remove all whitespace characters.
			$expression = str_replace( array( "\n", "\r", "\t", ' ' ), '', $expression );

			// Expand cell ranges (like A3:A6) to a list of single cells (like A3,A4,A5,A6).
			if ( preg_match_all( '#([A-Z]+)([0-9]+):([A-Z]+)([0-9]+)#', $expression, $referenced_cell_ranges, PREG_SET_ORDER ) ) {
				foreach ( $referenced_cell_ranges as $cell_range ) {
					if ( in_array( $cell_range[0], $replaced_ranges, true ) ) {
						continue;
					}

					$replaced_ranges[] = $cell_range[0];

					if ( isset( $this->known_ranges[ $cell_range[0] ] ) ) {
						$expression = preg_replace( '#(?<![A-Z])' . preg_quote( $cell_range[0], '#' ) . '(?![0-9])#', $this->known_ranges[ $cell_range[0] ], $expression );
						continue;
					}

					// No -1 necessary for this transformation, as we don't actually access the table.
					$first_col = TablePress::letter_to_number( $cell_range[1] );
					$first_row = $cell_range[2];
					$last_col = TablePress::letter_to_number( $cell_range[3] );
					$last_row = $cell_range[4];

					$col_start = min( $first_col, $last_col );
					$col_end = max( $first_col, $last_col ) + 1; // +1 for loop below
					$row_start = min( $first_row, $last_row );
					$row_end = max( $first_row, $last_row ) + 1; // +1 for loop below

					$cell_list = array();
					for ( $col = $col_start; $col < $col_end; $col++ ) {
						for ( $row = $row_start; $row < $row_end; $row++ ) {
							$column = TablePress::number_to_letter( $col );
							$cell_list[] = "{$column}{$row}";
						}
					}
					$cell_list = implode( ',', $cell_list );

					$expression = preg_replace( '#(?<![A-Z])' . preg_quote( $cell_range[0], '#' ) . '(?![0-9])#', $cell_list, $expression );
					$this->known_ranges[ $cell_range[0] ] = $cell_list;
				}
			}

			// Parse and evaluate single cell references (like A3 or XY312), while prohibiting circle references.
			if ( preg_match_all( '#([A-Z]+)([0-9]+)#', $expression, $referenced_cells, PREG_SET_ORDER ) ) {
				foreach ( $referenced_cells as $cell_reference ) {
					if ( in_array( $cell_reference[0], $parents, true ) ) {
						return '!ERROR! Circle Reference';
					}

					if ( in_array( $cell_reference[0], $replaced_references, true ) ) {
						continue;
					}

					$replaced_references[] = $cell_reference[0];

					$ref_col = TablePress::letter_to_number( $cell_reference[1] ) - 1;
					$ref_row = $cell_reference[2] - 1;

					if ( ! isset( $this->table_data[ $ref_row ] ) || ! isset( $this->table_data[ $ref_row ][ $ref_col ] ) ) {
						return "!ERROR! Cell {$cell_reference[0]} does not exist";
					}

					$ref_parents = $parents;
					$ref_parents[] = $cell_reference[0];

					$result = $this->table_data[ $ref_row ][ $ref_col ] = $this->_evaluate_cell( $this->table_data[ $ref_row ][ $ref_col ], $ref_parents );
					// Bail if there was an error already.
					if ( false !== strpos( $result, '!ERROR!' ) ) {
						return $result;
					}
					// Remove all whitespace characters.
					$result = str_replace( array( "\n", "\r", "\t", ' ' ), '', $result );
					// Treat empty cells as 0.
					if ( '' === $result ) {
						$result = 0;
					}
					// Bail if the cell does not result in a number (meaning it was a number or expression before being evaluated).
					if ( ! is_numeric( $result ) ) {
						return "!ERROR! {$cell_reference[0]} does not contain a number or expression";
					}

					$expression = preg_replace( '#(?<![A-Z])' . $cell_reference[0] . '(?![0-9])#', $result, $expression );
				}
			}

			$result = $this->_evaluate_math_expression( $expression );
			// Support putting formulas in strings, like =Total: {A3+A4}.
			if ( $formula_in_string ) {
				$content = str_replace( $orig_expression, $result, $content );
			} else {
				$content = $result;
			}
		}

		return $content;
	}

	/**
	 * Evaluate a math expression.
	 *
	 * @since 1.0.0
	 *
	 * @param string $expression without leading = sign.
	 * @return string Result of the evaluation.
	 */
	protected function _evaluate_math_expression( $expression ) {
		// Straight up evaluation, without parsing of variable or function assignments (which is why we only need one instance of the object).
		$result = $this->evalmath->evaluate( $expression );
		if ( false === $result ) {
			return '!ERROR! ' . $this->evalmath->last_error;
		} else {
			return (string) $result;
		}
	}

} // class TablePress_Evaluate
class-export.php000066600000013504151120041030007673 0ustar00<?php
/**
 * TablePress Table Export Class
 *
 * @package TablePress
 * @subpackage Export/Import
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress Table Export Class
 * @package TablePress
 * @subpackage Export/Import
 * @author Tobias Bäthge
 * @since 1.0.0
 */
class TablePress_Export {

	/**
	 * File/Data Formats that are available for the export.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	public $export_formats = array();

	/**
	 * Delimiters for the CSV export.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	public $csv_delimiters = array();

	/**
	 * Whether ZIP archive support is available in the PHP installation on the server.
	 *
	 * @since 1.0.0
	 * @var bool
	 */
	public $zip_support_available = false;

	/**
	 * Initialize the Export class.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Initiate here, because function call not possible outside a class method.
		$this->export_formats = array(
			'csv'  => __( 'CSV - Character-Separated Values', 'tablepress' ),
			'html' => __( 'HTML - Hypertext Markup Language', 'tablepress' ),
			'json' => __( 'JSON - JavaScript Object Notation', 'tablepress' ),
		);
		$this->csv_delimiters = array(
			';'   => __( '; (semicolon)', 'tablepress' ),
			','   => __( ', (comma)', 'tablepress' ),
			'tab' => __( '\t (tabulator)', 'tablepress' ),
		);

		/** This filter is documented in the WordPress function unzip_file() in wp-admin/includes/file.php */
		if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
			$this->zip_support_available = true;
		}
	}

	/**
	 * Export a table.
	 *
	 * @since 1.0.0
	 *
	 * @param array  $table         Table to be exported.
	 * @param string $export_format Format for the export ('csv', 'html', 'json').
	 * @param string $csv_delimiter Delimiter for CSV export.
	 * @return string Exported table (only data for CSV and HTML, full tables (including options) for JSON).
	 */
	public function export_table( array $table, $export_format, $csv_delimiter ) {
		switch ( $export_format ) {
			case 'csv':
				$output = '';
				if ( 'tab' === $csv_delimiter ) {
					$csv_delimiter = "\t";
				}
				foreach ( $table['data'] as $row_idx => $row ) {
					$csv_row = array();
					foreach ( $row as $column_idx => $cell_content ) {
						$csv_row[] = $this->csv_wrap_and_escape( $cell_content, $csv_delimiter );
					}
					$output .= implode( $csv_delimiter, $csv_row );
					$output .= "\n";
				}
				break;
			case 'html':
				$num_rows = count( $table['data'] );
				$last_row_idx = $num_rows - 1;
				$thead = '';
				$tfoot = '';
				$tbody = array();

				foreach ( $table['data'] as $row_idx => $row ) {
					// First row, need to check for head (but only if at least two rows).
					if ( 0 === $row_idx && $table['options']['table_head'] && $num_rows > 1 ) {
						$thead = $this->html_render_row( $row, 'th' );
						continue;
					}
					// Last row, need to check for footer (but only if at least two rows).
					if ( $last_row_idx === $row_idx && $table['options']['table_foot'] && $num_rows > 1 ) {
						$tfoot = $this->html_render_row( $row, 'th' );
						continue;
					}
					// Neither first nor last row (with respective head/foot enabled), so render as body row.
					$tbody[] = $this->html_render_row( $row, 'td' );
				}

				// <thead>, <tfoot>, and <tbody> tags.
				if ( ! empty( $thead ) ) {
					$thead = "\t<thead>\n{$thead}\t</thead>\n";
				}
				if ( ! empty( $tfoot ) ) {
					$tfoot = "\t<tfoot>\n{$tfoot}\t</tfoot>\n";
				}
				$tbody = "\t<tbody>\n" . implode( '', $tbody ) . "\t</tbody>\n";

				$output = "<table>\n" . $thead . $tfoot . $tbody . "</table>\n";
				break;
			case 'json':
				$output = wp_json_encode( $table, TABLEPRESS_JSON_OPTIONS );
				break;
			default:
				$output = '';
		}

		return $output;
	}

	/**
	 * Wrap and escape a cell for CSV export.
	 *
	 * @since 1.0.0
	 *
	 * @param string $string    Content of a cell.
	 * @param string $delimiter CSV delimiter character.
	 * @return string Wrapped string for CSV export
	 */
	protected function csv_wrap_and_escape( $string, $delimiter ) {
		// Escape CSV delimiter for RegExp (e.g. '|').
		$delimiter = preg_quote( $delimiter, '#' );
		if ( 1 === preg_match( '#' . $delimiter . '|"|\n|\r#i', $string ) || ' ' === substr( $string, 0, 1 ) || ' ' === substr( $string, -1 ) ) {
			// Escape single " as double "".
			$string = str_replace( '"', '""', $string );
			// Wrap string in "".
			$string = '"' . $string . '"';
		}
		return $string;
	}

	/**
	 * Generate the HTML of a row.
	 *
	 * @since 1.0.0
	 *
	 * @param array  $row Cells of the row to be rendered.
	 * @param string $tag HTML tag to use for the cells (td or th).
	 * @return string HTML code for the row.
	 */
	protected function html_render_row( array $row, $tag ) {
		$output = "\t\t<tr>\n";
		array_walk( $row, array( $this, 'html_wrap_and_escape' ), $tag );
		$output .= implode( '', $row );
		$output .= "\t\t</tr>\n";
		return $output;
	}

	/**
	 * Wrap and escape a cell for HTML export.
	 *
	 * @since 1.0.0
	 *
	 * @param string   $cell_content Content of a cell.
	 * @param int|null $column_idx   Column index, or null if omitted. Unused, but defined to be able to use function as callback in array_walk().
	 * @param string   $html_tag     HTML tag that shall be used for the cell.
	 */
	protected function html_wrap_and_escape( &$cell_content, $column_idx, $html_tag ) {
		/*
		 * Replace any & with &amp; that is not already an encoded entity (from function htmlentities2 in WP 2.8).
		 * A complete htmlentities2() or htmlspecialchars() would encode <HTML> tags, which we don't want.
		 */
		$cell_content = preg_replace( '/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,4};)/', '&amp;', $cell_content );
		$cell_content = "\t\t\t<{$html_tag}>{$cell_content}</{$html_tag}>\n";
	}

} // class TablePress_Export
class-css.php000066600000036346151120041030007153 0ustar00<?php
/**
 * TablePress CSS Class
 *
 * @package TablePress
 * @subpackage CSS
 * @author Tobias Bäthge
 * @since 1.1.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress CSS Class
 * @package TablePress
 * @subpackage CSS
 * @author Tobias Bäthge
 * @since 1.1.0
 */
class TablePress_CSS {

	/**
	 * Sanitize and tidy a string of CSS.
	 *
	 * @since 1.1.0
	 *
	 * @param string $css CSS code.
	 * @return string Sanitized and tidied CSS code.
	 */
	public function sanitize_css( $css ) {
		$csstidy = TablePress::load_class( 'TablePress_CSSTidy', 'class.csstidy.php', 'libraries/csstidy' );

		// Sanitization and not just tidying for users without enough privileges.
		if ( ! current_user_can( 'unfiltered_html' ) ) {
			$csstidy->optimise = new TablePress_CSSTidy_custom_sanitize( $csstidy );

			// Let "arrows" survive, otherwise this might be recognized as the beginning of an HTML tag and removed with other stuff behind it.
			$css = str_replace( '<=', '&lt;=', $css );
			// Remove all HTML tags.
			$css = wp_kses( $css, 'strip' );
			// KSES replaces single ">" with "&gt;", but ">" is valid in CSS selectors.
			$css = str_replace( '&gt;', '>', $css );
			// strip_tags again, because of the just added ">" (KSES for a second time would again bring the ">" problem).
			$css = strip_tags( $css );
		}

		$csstidy->set_cfg( 'remove_bslash', false );
		$csstidy->set_cfg( 'compress_colors', false );
		$csstidy->set_cfg( 'compress_font-weight', false );
		$csstidy->set_cfg( 'lowercase_s', false );
		$csstidy->set_cfg( 'optimise_shorthands', false );
		$csstidy->set_cfg( 'remove_last_;', false );
		$csstidy->set_cfg( 'case_properties', false );
		$csstidy->set_cfg( 'sort_properties', false );
		$csstidy->set_cfg( 'sort_selectors', false );
		$csstidy->set_cfg( 'discard_invalid_selectors', false );
		$csstidy->set_cfg( 'discard_invalid_properties', true );
		$csstidy->set_cfg( 'merge_selectors', false );
		$csstidy->set_cfg( 'css_level', 'CSS3.0' );
		$csstidy->set_cfg( 'preserve_css', true );
		$csstidy->set_cfg( 'timestamp', false );
		$csstidy->set_cfg( 'template', dirname( TABLEPRESS__FILE__ ) . '/libraries/csstidy/tablepress-standard.tpl' );

		$csstidy->parse( $css );
		return $csstidy->print->plain();
	}

	/**
	 * Minify a string of CSS code, that should have been sanitized/tidied before.
	 *
	 * @since 1.1.0
	 *
	 * @param string $css CSS code.
	 * @return string Minified CSS code.
	 */
	public function minify_css( $css ) {
		$csstidy = TablePress::load_class( 'TablePress_CSSTidy', 'class.csstidy.php', 'libraries/csstidy' );
		$csstidy->optimise = new TablePress_CSSTidy_custom_sanitize( $csstidy );
		$csstidy->set_cfg( 'remove_bslash', false );
		$csstidy->set_cfg( 'compress_colors', true );
		$csstidy->set_cfg( 'compress_font-weight', true );
		$csstidy->set_cfg( 'lowercase_s', false );
		$csstidy->set_cfg( 'optimise_shorthands', 1 );
		$csstidy->set_cfg( 'remove_last_;', true );
		$csstidy->set_cfg( 'case_properties', false );
		$csstidy->set_cfg( 'sort_properties', false );
		$csstidy->set_cfg( 'sort_selectors', false );
		$csstidy->set_cfg( 'discard_invalid_selectors', false );
		$csstidy->set_cfg( 'discard_invalid_properties', true );
		$csstidy->set_cfg( 'merge_selectors', false );
		$csstidy->set_cfg( 'css_level', 'CSS3.0' );
		$csstidy->set_cfg( 'preserve_css', false );
		$csstidy->set_cfg( 'timestamp', false );
		$csstidy->set_cfg( 'template', 'highest' );

		$csstidy->parse( $css );
		return $csstidy->print->plain();
	}

	/**
	 * Get the location (file path or URL) of the "Custom CSS" file, depending on whether it's a Multisite install or not.
	 *
	 * @since 1.0.0
	 *
	 * @param string $type     "normal" version, "minified" version, or "combined" (with TablePress Default CSS) version.
	 * @param string $location "path" or "url", for file path or URL.
	 * @return string Full file path or full URL for the "Custom CSS" file.
	 */
	public function get_custom_css_location( $type, $location ) {
		switch ( $type ) {
			case 'combined':
				$file = 'tablepress-combined.min.css';
				break;
			case 'minified':
				$file = 'tablepress-custom.min.css';
				break;
			case 'normal':
			default:
				$file = 'tablepress-custom.css';
				break;
		}

		if ( is_multisite() ) {
			// Multisite installation: /wp-content/uploads/sites/<ID>/
			$upload_location = wp_upload_dir();
		} else {
			// Singlesite installation: /wp-content/
			$upload_location = array(
				'basedir' => WP_CONTENT_DIR,
				'baseurl' => content_url(),
			);
		}

		switch ( $location ) {
			case 'url':
				$url = set_url_scheme( $upload_location['baseurl'] . '/' . $file );
				/**
				 * Filter the URL from which the "Custom CSS" file is loaded.
				 *
				 * @since 1.0.0
				 *
				 * @param string $url  URL of the "Custom CSS" file.
				 * @param string $file File name of the "Custom CSS" file.
				 * @param string $type Type of the "Custom CSS" file ("normal", "minified", or "combined").
				 */
				$url = apply_filters( 'tablepress_custom_css_url', $url, $file, $type );
				return $url;
				// break; // unreachable
			case 'path':
				$path = $upload_location['basedir'] . '/' . $file;
				/**
				 * Filter the file path on the server from which the "Custom CSS" file is loaded.
				 *
				 * @since 1.0.0
				 *
				 * @param string $path File path of the "Custom CSS" file.
				 * @param string $file File name of the "Custom CSS" file.
				 * @param string $type Type of the "Custom CSS" file ("normal", "minified", or "combined").
				 */
				$path = apply_filters( 'tablepress_custom_css_file_name', $path, $file, $type );
				return $path;
				// break; // unreachable
		}
	}

	/**
	 * Load the contents of the file with the "Custom CSS".
	 *
	 * @since 1.0.0
	 *
	 * @param string $type Optional. Whether to load "normal" version or "minified" version. Default "normal".
	 * @return string|bool Custom CSS on success, false on error.
	 */
	public function load_custom_css_from_file( $type = 'normal' ) {
		$filename = $this->get_custom_css_location( $type, 'path' );
		// Check if file name is valid (0 means yes).
		if ( 0 !== validate_file( $filename ) ) {
			return false;
		}
		if ( ! @is_file( $filename ) ) {
			return false;
		}
		if ( ! @is_readable( $filename ) ) {
			return false;
		}
		return file_get_contents( $filename );
	}

	/**
	 * Load the contents of the file with the TablePress Default CSS.
	 *
	 * @since 1.1.0
	 *
	 * @return string|bool TablePress Default CSS on success, false on error.
	 */
	public function load_default_css_from_file() {
		$filename = TABLEPRESS_ABSPATH . 'css/default.min.css';
		// Check if file name is valid (0 means yes).
		if ( 0 !== validate_file( $filename ) ) {
			return false;
		}
		if ( ! @is_file( $filename ) ) {
			return false;
		}
		if ( ! @is_readable( $filename ) ) {
			return false;
		}
		return file_get_contents( $filename );
	}

	/**
	 * Try to save "Custom CSS" to a file (requires "direct" method in WP_Filesystem, or stored FTP credentials).
	 *
	 * @since 1.1.0
	 *
	 * @param string $custom_css_normal   Custom CSS code to be saved.
	 * @param string $custom_css_minified Minified CSS code to be saved.
	 * @return bool True on success, false on failure.
	 */
	public function save_custom_css_to_file( $custom_css_normal, $custom_css_minified ) {
		/**
		 * Filter whether the "Custom CSS" code shall be saved to a file on the server.
		 *
		 * @since 1.1.0
		 *
		 * @param bool $save Whether to save the "Custom CSS" to a file. Default true.
		 */
		if ( ! apply_filters( 'tablepress_save_custom_css_to_file', true ) ) {
			return false;
		}

		// Start capturing the output, to later prevent it.
		ob_start();
		$credentials = request_filesystem_credentials( '', '', false, false, null );
		/*
		 * Do we have credentials already? (Otherwise the form will have been rendered, which is not supported here.)
		 * Or, if we have credentials, are they valid?
		 */
		if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
			ob_end_clean();
			return false;
		}

		// We have valid access to the filesystem now -> try to save the files.
		return $this->_custom_css_save_helper( $custom_css_normal, $custom_css_minified );
	}

	/**
	 * Save "Custom CSS" to files, delete "Custom CSS" files, or return HTML for the credentials form.
	 *
	 * Only used from "Plugin Options" screen, save_custom_css_to_file() is used in cases where no form output/redirection is possible (plugin updates, WP-Table Reloaded Import).
	 *
	 * @since 1.0.0
	 *
	 * @param string $custom_css_normal   Custom CSS code to be saved. If empty, files will be deleted.
	 * @param string $custom_css_minified Minified CSS code to be saved.
	 * @return bool|string True on success, false on failure, or string of HTML for the credentials form for the WP_Filesystem API, if necessary.
	 */
	public function save_custom_css_to_file_plugin_options( $custom_css_normal, $custom_css_minified ) {
		/** This filter is documented in classes/class-css.php */
		if ( ! apply_filters( 'tablepress_save_custom_css_to_file', true ) ) {
			return false;
		}

		// Start capturing the output, to get HTML of the credentials form (if needed).
		ob_start();
		$credentials = request_filesystem_credentials( '', '', false, false, null );
		// Do we have credentials already? (Otherwise the form will have been rendered already.)
		if ( false === $credentials ) {
			$form_data = ob_get_clean();
			$form_data = str_replace( 'name="upgrade" id="upgrade" class="button"', 'name="upgrade" id="upgrade" class="button button-primary button-large"', $form_data );
			return $form_data;
		}

		// We have received credentials, but don't know if they are valid yet.
		if ( ! WP_Filesystem( $credentials ) ) {
			// Credentials failed, so ask again (with $error flag true).
			request_filesystem_credentials( '', '', true, false, null );
			$form_data = ob_get_clean();
			$form_data = str_replace( 'name="upgrade" id="upgrade" class="button"', 'name="upgrade" id="upgrade" class="button button-primary button-large"', $form_data );
			return $form_data;
		}

		// We have valid access to the filesystem now -> try to save the files, or delete them if the "Custom CSS" is empty.
		if ( '' !== $custom_css_normal ) {
			return $this->_custom_css_save_helper( $custom_css_normal, $custom_css_minified );
		} else {
			return $this->_custom_css_delete_helper();
		}
	}

	/**
	 * Save "Custom CSS" to files, if validated access to the WP_Filesystem exists.
	 *
	 * Helper function to prevent code duplication.
	 *
	 * @since 1.1.0
	 *
	 * @global WP_Filesystem_* $wp_filesystem WordPress file system abstraction object.
	 * @see save_custom_css_to_file()
	 * @see save_custom_css_to_file_plugin_options()
	 *
	 * @param string $custom_css_normal   Custom CSS code to be saved.
	 * @param string $custom_css_minified Minified CSS code to be saved.
	 * @return bool True on success, false on failure.
	 */
	protected function _custom_css_save_helper( $custom_css_normal, $custom_css_minified ) {
		global $wp_filesystem;

		/*
		 * WP_CONTENT_DIR and (FTP-)Content-Dir can be different (e.g. if FTP working dir is /).
		 * We need to account for that by replacing the path difference in the filename.
		 */
		$path_difference = str_replace( $wp_filesystem->wp_content_dir(), '', trailingslashit( WP_CONTENT_DIR ) );

		$css_types = array( 'normal', 'minified', 'combined' );

		$default_css = $this->load_default_css_from_file();
		if ( false === $default_css ) {
			$default_css = '';
		} else {
			// Change relative URLs to web font files to absolute URLs, as combining the CSS files and saving to another directory breaks the relative URLs.
			$absolute_path = plugins_url( 'css/tablepress.', TABLEPRESS__FILE__ );
			// Make the absolute URL protocol-relative to prevent mixed content warnings.
			$absolute_path = str_replace( array( 'http:', 'https:' ), '', $absolute_path );
			$default_css = str_replace( 'url(tablepress.', 'url(' . $absolute_path, $default_css );
		}
		$file_content = array(
			'normal'   => $custom_css_normal,
			'minified' => $custom_css_minified,
			'combined' => $default_css . "\n" . $custom_css_minified,
		);

		$total_result = true; // whether all files were saved successfully
		foreach ( $css_types as $css_type ) {
			$filename = $this->get_custom_css_location( $css_type, 'path' );
			// Check if filename is valid (0 means yes).
			if ( 0 !== validate_file( $filename ) ) {
				$total_result = false;
				continue;
			}
			if ( '' !== $path_difference ) {
				$filename = str_replace( $path_difference, '', $filename );
			}
			$result = $wp_filesystem->put_contents( $filename, $file_content[ $css_type ], FS_CHMOD_FILE );
			$total_result = ( $total_result && $result );
		}

		$this->_flush_caching_plugins_css_minify_caches();

		return $total_result;
	}

	/**
	 * Delete the "Custom CSS" files, if possible.
	 *
	 * @since 1.0.0
	 *
	 * @return bool True on success, false on failure.
	 */
	public function delete_custom_css_files() {
		// Start capturing the output, to later prevent it.
		ob_start();
		$credentials = request_filesystem_credentials( '', '', false, false, null );
		/*
		 * Do we have credentials already? (Otherwise the form will have been rendered, which is not supported here.)
		 * Or, if we have credentials, are they valid?
		 */
		if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
			ob_end_clean();
			return false;
		}

		// We have valid access to the filesystem now -> try to delete the files.
		return $this->_custom_css_delete_helper();
	}

	/**
	 * Delete "Custom CSS" files, if validated access to the WP_Filesystem exists.
	 *
	 * Helper function to prevent code duplication
	 *
	 * @since 1.1.0
	 *
	 * @global WP_Filesystem_* $wp_filesystem WordPress file system abstraction object.
	 * @see delete_custom_css_files()
	 * @see save_custom_css_to_file_plugin_options()
	 *
	 * @return bool True on success, false on failure.
	 */
	protected function _custom_css_delete_helper() {
		global $wp_filesystem;

		/*
		 * WP_CONTENT_DIR and (FTP-)Content-Dir can be different (e.g. if FTP working dir is /).
		 * We need to account for that by replacing the path difference in the filename.
		 */
		$path_difference = str_replace( $wp_filesystem->wp_content_dir(), '', trailingslashit( WP_CONTENT_DIR ) );

		$css_types = array( 'normal', 'minified', 'combined' );
		$total_result = true; // whether all files were deleted successfully
		foreach ( $css_types as $css_type ) {
			$filename = $this->get_custom_css_location( $css_type, 'path' );
			// Check if filename is valid (0 means yes).
			if ( 0 !== validate_file( $filename ) ) {
				$total_result = false;
				continue;
			}
			if ( '' !== $path_difference ) {
				$filename = str_replace( $path_difference, '', $filename );
			}
			// We have valid access to the filesystem now -> try to delete the file.
			if ( $wp_filesystem->exists( $filename ) ) {
				$result = $wp_filesystem->delete( $filename );
				$total_result = ( $total_result && $result );
			}
		}

		$this->_flush_caching_plugins_css_minify_caches();

		return $total_result;
	}

	/**
	 * Flush the CSS minification cache of W3 Total Cache.
	 *
	 * @since 1.4.0
	 */
	protected function _flush_caching_plugins_css_minify_caches() {
		/** This filter is documented in models/model-table.php */
		if ( ! apply_filters( 'tablepress_flush_caching_plugins_caches', true ) ) {
			return;
		}

		// W3 Total Cache
		if ( function_exists( 'w3tc_minify_flush' ) ) {
			w3tc_minify_flush();
		}
	}

} // class TablePress_CSS
class-render.php000066600000100660151120041030007631 0ustar00<?php
/**
 * TablePress Rendering Class
 *
 * @package TablePress
 * @subpackage Rendering
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress Rendering Class
 * @package TablePress
 * @subpackage Rendering
 * @author Tobias Bäthge
 * @since 1.0.0
 */
class TablePress_Render {

	/**
	 * Table data that is rendered.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $table = array();

	/**
	 * Table options that influence the output result.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $render_options = array();

	/**
	 * Rendered HTML of the table.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	protected $output;

	/**
	 * Trigger words for colspan, rowspan, or the combination of both.
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $span_trigger = array(
		'colspan' => '#colspan#',
		'rowspan' => '#rowspan#',
		'span'    => '#span#',
	);

	/**
	 * Buffer to store the counts of rowspan per column, initialized in _render_table().
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $rowspan = array();

	/**
	 * Buffer to store the counts of colspan per row, initialized in _render_table().
	 *
	 * @since 1.0.0
	 * @var array
	 */
	protected $colspan = array();

	/**
	 * Index of the last row of the visible data in the table, set in _render_table().
	 *
	 * @since 1.0.0
	 * @var int
	 */
	protected $last_row_idx;

	/**
	 * Index of the last column of the visible data in the table, set in _render_table().
	 *
	 * @since 1.0.0
	 * @var int
	 */
	protected $last_column_idx;

	/**
	 * Class constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Unused.
	}

	/**
	 * Set the table (data, options, visibility, ...) that is to be rendered.
	 *
	 * @since 1.0.0
	 *
	 * @param array $table          Table to be rendered.
	 * @param array $render_options Options for rendering, from both "Edit" screen and Shortcode.
	 */
	public function set_input( array $table, array $render_options ) {
		$this->table = $table;
		$this->render_options = $render_options;
		/**
		 * Filter the table before the render process.
		 *
		 * @since 1.0.0
		 *
		 * @param array $table          The table.
		 * @param array $render_options The render options for the table.
		 */
		$this->table = apply_filters( 'tablepress_table_raw_render_data', $this->table, $this->render_options );
	}

	/**
	 * Process the table rendering and return the HTML output.
	 *
	 * @since 1.0.0
	 *
	 * @return string HTML of the rendered table (or an error message).
	 */
	public function get_output() {
		// Evaluate math expressions/formulas.
		$this->_evaluate_table_data();
		// Remove hidden rows and columns.
		$this->_prepare_render_data();
		// Generate HTML output.
		$this->_render_table();
		return $this->output;
	}

	/**
	 * Loop through the table to evaluate math expressions/formulas.
	 *
	 * @since 1.0.0
	 */
	protected function _evaluate_table_data() {
		$orig_table = $this->table;

		$formula_evaluator = TablePress::load_class( 'TablePress_Evaluate', 'class-evaluate.php', 'classes' );
		$this->table['data'] = $formula_evaluator->evaluate_table_data( $this->table['data'] );
		/**
		 * Filter the table after evaluating formulas in the table.
		 *
		 * @since 1.0.0
		 *
		 * @param array $table          The table with evaluated formulas.
		 * @param array $orig_table     The table with unevaluated formulas.
		 * @param array $render_options The render options for the table.
		 */
		$this->table = apply_filters( 'tablepress_table_evaluate_data', $this->table, $orig_table, $this->render_options );
	}

	/**
	 * Remove all cells from the data set that shall not be rendered, because they are hidden.
	 *
	 * @since 1.0.0
	 */
	protected function _prepare_render_data() {
		$orig_table = $this->table;

		$num_rows = count( $this->table['data'] );
		$num_columns = ( $num_rows > 0 ) ? count( $this->table['data'][0] ) : 0;

		// Evaluate show/hide_rows/columns parameters.
		$actions = array( 'show', 'hide' );
		$elements = array( 'rows', 'columns' );
		foreach ( $actions as $action ) {
			foreach ( $elements as $element ) {
				if ( empty( $this->render_options[ "{$action}_{$element}" ] ) ) {
					$this->render_options[ "{$action}_{$element}" ] = array();
					continue;
				}

				// Add all rows/columns to array if "all" value set for one of the four parameters.
				if ( 'all' === $this->render_options[ "{$action}_{$element}" ] ) {
					$this->render_options[ "{$action}_{$element}" ] = range( 0, ${'num_' . $element} - 1 );
					continue;
				}

				// We have a list of rows/columns (possibly with ranges in it).
				$this->render_options[ "{$action}_{$element}" ] = explode( ',', $this->render_options[ "{$action}_{$element}" ] );
				// Support for ranges like 3-6 or A-BA.
				$range_cells = array();
				foreach ( $this->render_options[ "{$action}_{$element}" ] as $key => $value ) {
					$range_dash = strpos( $value, '-' );
					if ( false !== $range_dash ) {
						unset( $this->render_options[ "{$action}_{$element}" ][ $key ] );
						$start = substr( $value, 0, $range_dash );
						if ( ! is_numeric( $start ) ) {
							$start = TablePress::letter_to_number( $start );
						}
						$end = substr( $value, $range_dash + 1 );
						if ( ! is_numeric( $end ) ) {
							$end = TablePress::letter_to_number( $end );
						}
						$current_range = range( $start, $end );
						$range_cells = array_merge( $range_cells, $current_range );
					}
				}
				$this->render_options[ "{$action}_{$element}" ] = array_merge( $this->render_options[ "{$action}_{$element}" ], $range_cells );
				/*
				 * Parse single letters and change from regular numbering to zero-based numbering,
				 * as rows/columns are indexed from 0 internally, but from 1 externally
				 */
				foreach ( $this->render_options[ "{$action}_{$element}" ] as $key => $value ) {
					if ( ! is_numeric( $value ) ) {
						$value = TablePress::letter_to_number( $value );
					}
					$this->render_options[ "{$action}_{$element}" ][ $key ] = (int) $value - 1;
				}

				// Remove duplicate entries and sort the array.
				$this->render_options[ "{$action}_{$element}" ] = array_unique( $this->render_options[ "{$action}_{$element}" ] );
				sort( $this->render_options[ "{$action}_{$element}" ], SORT_NUMERIC );
			}
		}

		// Load information about hidden rows and columns.
		// Get indexes of hidden rows (array value of 0).
		$hidden_rows = array_keys( $this->table['visibility']['rows'], 0 );
		$hidden_rows = array_merge( $hidden_rows, $this->render_options['hide_rows'] );
		$hidden_rows = array_diff( $hidden_rows, $this->render_options['show_rows'] );
		// Get indexes of hidden columns (array value of 0).
		$hidden_columns = array_keys( $this->table['visibility']['columns'], 0 );
		$hidden_columns = array_merge( $hidden_columns, $this->render_options['hide_columns'] );
		$hidden_columns = array_merge( array_diff( $hidden_columns, $this->render_options['show_columns'] ) );

		// Remove hidden rows and re-index.
		foreach ( $hidden_rows as $row_idx ) {
			unset( $this->table['data'][ $row_idx ] );
		}
		$this->table['data'] = array_merge( $this->table['data'] );
		// Remove hidden columns and re-index.
		foreach ( $this->table['data'] as $row_idx => $row ) {
			foreach ( $hidden_columns as $col_idx ) {
				unset( $row[ $col_idx ] );
			}
			$this->table['data'][ $row_idx ] = array_merge( $row );
		}

		/**
		 * Filter the table after processing the table visibility information.
		 *
		 * @since 1.0.0
		 *
		 * @param array $table          The processed table.
		 * @param array $orig_table     The unprocessed table.
		 * @param array $render_options The render options for the table.
		 */
		$this->table = apply_filters( 'tablepress_table_render_data', $this->table, $orig_table, $this->render_options );
	}

	/**
	 * Generate the HTML output of the table.
	 *
	 * @since 1.0.0
	 */
	protected function _render_table() {
		$num_rows = count( $this->table['data'] );
		$num_columns = ( $num_rows > 0 ) ? count( $this->table['data'][0] ) : 0;

		// Check if there are rows and columns in the table (might not be the case after removing hidden rows/columns!).
		if ( 0 === $num_rows || 0 === $num_columns ) {
			$this->output = sprintf( __( '<!-- The table with the ID %s is empty! -->', 'tablepress' ), $this->table['id'] );
			return;
		}

		// Counters for spans of rows and columns, init to 1 for each row and column (as that means no span).
		$this->rowspan = array_fill( 0, $num_columns, 1 );
		$this->colspan = array_fill( 0, $num_rows, 1 );

		/**
		 * Filter the trigger keywords for "colspan" and "rowspan"
		 *
		 * @since 1.0.0
		 *
		 * @param array  $span_trigger The trigger keywords for combining table cells.
		 * @param string $table_id     The current table ID.
		 */
		$this->span_trigger = apply_filters( 'tablepress_span_trigger_keywords', $this->span_trigger, $this->table['id'] );

		// Explode from string to array.
		$this->render_options['column_widths'] = ( ! empty( $this->render_options['column_widths'] ) ) ? explode( '|', $this->render_options['column_widths'] ) : array();
		// Make array $this->render_options['column_widths'] have $columns entries.
		$this->render_options['column_widths'] = array_pad( $this->render_options['column_widths'], $num_columns, '' );

		$output = '';

		if ( $this->render_options['print_name'] ) {
			/**
			 * Filter the HTML tag that wraps the printed table name.
			 *
			 * @since 1.0.0
			 *
			 * @param string $tag      The HTML tag around the table name. Default h2.
			 * @param string $table_id The current table ID.
			 */
			$print_name_html_tag = apply_filters( 'tablepress_print_name_html_tag', 'h2', $this->table['id'] );
			/**
			 * Filter the class attribute for the printed table name.
			 *
			 * @since 1.0.0
			 *
			 * @param string $class    The class attribute for the table name that can be used in CSS code.
			 * @param string $table_id The current table ID.
			 */
			$print_name_css_class = apply_filters( 'tablepress_print_name_css_class', "tablepress-table-name tablepress-table-name-id-{$this->table['id']}", $this->table['id'] );
			$print_name_html = "<{$print_name_html_tag} class=\"{$print_name_css_class}\">" . $this->safe_output( $this->table['name'] ) . "</{$print_name_html_tag}>\n";
		}
		if ( $this->render_options['print_description'] ) {
			/**
			 * Filter the HTML tag that wraps the printed table description.
			 *
			 * @since 1.0.0
			 *
			 * @param string $tag      The HTML tag around the table description. Default span.
			 * @param string $table_id The current table ID.
			 */
			$print_description_html_tag = apply_filters( 'tablepress_print_description_html_tag', 'span', $this->table['id'] );
			/**
			 * Filter the class attribute for the printed table description.
			 *
			 * @since 1.0.0
			 *
			 * @param string $class    The class attribute for the table description that can be used in CSS code.
			 * @param string $table_id The current table ID.
			 */
			$print_description_css_class = apply_filters( 'tablepress_print_description_css_class', "tablepress-table-description tablepress-table-description-id-{$this->table['id']}", $this->table['id'] );
			$print_description_html = "<{$print_description_html_tag} class=\"{$print_description_css_class}\">" . $this->safe_output( $this->table['description'] ) . "</{$print_description_html_tag}>\n";
		}

		if ( $this->render_options['print_name'] && 'above' === $this->render_options['print_name_position'] ) {
			$output .= $print_name_html;
		}
		if ( $this->render_options['print_description'] && 'above' === $this->render_options['print_description_position'] ) {
			$output .= $print_description_html;
		}

		// Deactivate nl2br() for this render process, if "convert_line_breaks" Shortcode parameter is set to false.
		if ( ! $this->render_options['convert_line_breaks'] ) {
			add_filter( 'tablepress_apply_nl2br', '__return_false', 9 ); // Priority 9, so that this filter can easily be overwritten at the default priority.
		}

		$thead = '';
		$tfoot = '';
		$tbody = array();

		$this->last_row_idx = $num_rows - 1;
		$this->last_column_idx = $num_columns - 1;
		// Loop through rows in reversed order, to search for rowspan trigger keyword.
		for ( $row_idx = $this->last_row_idx; $row_idx >= 0; $row_idx-- ) {
			// Last row, need to check for footer (but only if at least two rows).
			if ( $this->last_row_idx === $row_idx && $this->render_options['table_foot'] && $num_rows > 1 ) {
				$tfoot = $this->_render_row( $row_idx, 'th' );
				continue;
			}
			// First row, need to check for head (but only if at least two rows).
			if ( 0 === $row_idx && $this->render_options['table_head'] && $num_rows > 1 ) {
				$thead = $this->_render_row( $row_idx, 'th' );
				continue;
			}
			// Neither first nor last row (with respective head/foot enabled), so render as body row.
			$tbody[] = $this->_render_row( $row_idx, 'td' );
		}

		// Re-instate nl2br() behavior after this render process, if "convert_line_breaks" Shortcode parameter is set to false.
		if ( ! $this->render_options['convert_line_breaks'] ) {
			remove_filter( 'tablepress_apply_nl2br', '__return_false', 9 ); // Priority 9, so that this filter can easily be overwritten at the default priority.
		}

		// <caption> tag.
		/**
		 * Filter the content for the HTML caption element of the table.
		 *
		 * If the "Edit" link for a table is shown, it is also added to the caption element.
		 *
		 * @since 1.0.0
		 *
		 * @param string $caption The content for the HTML caption element of the table. Default empty.
		 * @param array  $table   The current table.
		 */
		$caption = apply_filters( 'tablepress_print_caption_text', '', $this->table );
		$caption_style = $caption_class = '';
		if ( ! empty( $caption ) ) {
			/**
			 * Filter the class attribute for the HTML caption element of the table.
			 *
			 * @since 1.0.0
			 *
			 * @param string $class    The class attribute for the HTML caption element of the table.
			 * @param string $table_id The current table ID.
			 */
			$caption_class = apply_filters( 'tablepress_print_caption_class', "tablepress-table-caption tablepress-table-caption-id-{$this->table['id']}", $this->table['id'] );
			$caption_class = ' class="' . $caption_class . '"';
		}
		if ( ! empty( $this->render_options['edit_table_url'] ) ) {
			if ( empty( $caption ) ) {
				$caption_style = ' style="caption-side:bottom;text-align:left;border:none;background:none;margin:0;padding:0;"';
			} else {
				$caption .= '<br />';
			}
			$caption .= "<a href=\"{$this->render_options['edit_table_url']}\">" . __( 'Edit', 'default' ) . '</a>';
		}
		if ( ! empty( $caption ) ) {
			$caption = "<caption{$caption_class}{$caption_style}>{$caption}</caption>\n";
		}

		// <colgroup> tag.
		$colgroup = '';
		/**
		 * Filter whether the HTML colgroup tag shall be added to the table output.
		 *
		 * @since 1.0.0
		 *
		 * @param bool   $print    Whether the colgroup element shall be printed.
		 * @param string $table_id The current table ID.
		 */
		if ( apply_filters( 'tablepress_print_colgroup_tag', false, $this->table['id'] ) ) {
			for ( $col_idx = 0; $col_idx < $num_columns; $col_idx++ ) {
				$attributes = ' class="colgroup-column-' . ( $col_idx + 1 ) . ' "';
				/**
				 * Filter the attributes of the HTML col tags in the HTML colgroup tag.
				 *
				 * @since 1.0.0
				 *
				 * @param string $attributes The attributes in the col element.
				 * @param string $table_id   The current table ID.
				 * @param int    $col_idx    The number of the column.
				 */
				$attributes = apply_filters( 'tablepress_colgroup_tag_attributes', $attributes, $this->table['id'], $col_idx + 1 );
				$colgroup .= "\t<col{$attributes}/>\n";
			}
		}
		if ( ! empty( $colgroup ) ) {
			$colgroup = "<colgroup>\n{$colgroup}</colgroup>\n";
		}

		// <thead>, <tfoot>, and <tbody> tags.
		if ( ! empty( $thead ) ) {
			$thead = "<thead>\n{$thead}</thead>\n";
		}
		if ( ! empty( $tfoot ) ) {
			$tfoot = "<tfoot>\n{$tfoot}</tfoot>\n";
		}
		$tbody_class = ( $this->render_options['row_hover'] ) ? ' class="row-hover"' : '';
		// Reverse rows because we looped through the rows in reverse order.
		$tbody = array_reverse( $tbody );
		$tbody = "<tbody{$tbody_class}>\n" . implode( '', $tbody ) . "</tbody>\n";

		// Attributes for the table (HTML table element).
		$table_attributes = array();

		// "id" attribute.
		if ( ! empty( $this->render_options['html_id'] ) ) {
			$table_attributes['id'] = $this->render_options['html_id'];
		}

		// "class" attribute.
		$css_classes = array( 'tablepress', "tablepress-id-{$this->table['id']}", $this->render_options['extra_css_classes'] );
		/**
		 * Filter the CSS classes that are given to the HTML table element.
		 *
		 * @since 1.0.0
		 *
		 * @param array  $css_classes The CSS classes for the table element.
		 * @param string $table_id    The current table ID.
		 */
		$css_classes = apply_filters( 'tablepress_table_css_classes', $css_classes, $this->table['id'] );
		// $css_classes might contain several classes in one array entry.
		$css_classes = explode( ' ', implode( ' ', $css_classes ) );
		$css_classes = array_map( 'sanitize_html_class', $css_classes );
		$css_classes = array_unique( $css_classes );
		$css_classes = trim( implode( ' ', $css_classes ) );
		if ( ! empty( $css_classes ) ) {
			$table_attributes['class'] = $css_classes;
		}

		// "summary" attribute.
		$summary = '';
		/**
		 * Filter the content for the summary attribute of the HTML table element.
		 *
		 * The attribute is only added if it is not empty.
		 *
		 * @since 1.0.0
		 *
		 * @param string $summary The content for the summary attribute of the table. Default empty.
		 * @param array  $table   The current table.
		 */
		$summary = apply_filters( 'tablepress_print_summary_attr', $summary, $this->table );
		if ( ! empty( $summary ) ) {
			$table_attributes['summary'] = esc_attr( $summary );
		}

		// Legacy support for attributes that are not encouraged in HTML5.
		foreach ( array( 'cellspacing', 'cellpadding', 'border' ) as $attribute ) {
			if ( false !== $this->render_options[ $attribute ] ) {
				$table_attributes[ $attribute ] = intval( $this->render_options[ $attribute ] );
			}
		}

		/**
		 * Filter the attributes for the table (HTML table element).
		 *
		 * @since 1.4.0
		 *
		 * @param array $table_attributes The attributes for the table element.
		 * @param array $table            The current table.
		 * @param array $render_options   The render options for the table.
		 */
		$table_attributes = apply_filters( 'tablepress_table_tag_attributes', $table_attributes, $this->table, $this->render_options );
		$table_attributes = $this->_attributes_array_to_string( $table_attributes );

		$output .= "\n<table{$table_attributes}>\n";
		$output .= $caption . $colgroup . $thead . $tfoot . $tbody;
		$output .= "</table>\n";

		// name/description below table (HTML already generated above).
		if ( $this->render_options['print_name'] && 'below' === $this->render_options['print_name_position'] ) {
			$output .= $print_name_html;
		}
		if ( $this->render_options['print_description'] && 'below' === $this->render_options['print_description_position'] ) {
			$output .= $print_description_html;
		}

		/**
		 * Filter the generated HTML code for table.
		 *
		 * @since 1.0.0
		 *
		 * @param string $output         The generated HTML for the table.
		 * @param array  $table          The current table.
		 * @param array  $render_options The render options for the table.
		 */
		$this->output = apply_filters( 'tablepress_table_output', $output, $this->table, $this->render_options );
	}

	/**
	 * Generate the HTML of a row.
	 *
	 * @since 1.0.0
	 *
	 * @param int    $row_idx Index of the row to be rendered.
	 * @param string $tag     HTML tag to use for the cells (td or th).
	 * @return string HTML for the row.
	 */
	protected function _render_row( $row_idx, $tag ) {
		$row_cells = array();
		// Loop through cells in reversed order, to search for colspan or rowspan trigger words.
		for ( $col_idx = $this->last_column_idx; $col_idx >= 0; $col_idx-- ) {
			$cell_content = $this->table['data'][ $row_idx ][ $col_idx ];

			// Print formulas that are escaped with '= (like in Excel) as text.
			if ( "'=" === substr( $cell_content, 0, 2 ) ) {
				$cell_content = substr( $cell_content, 1 );
			}
			$cell_content = do_shortcode( $this->safe_output( $cell_content ) );
			/**
			 * Filter the content of a single cell.
			 *
			 * Filter the content of a single cell, after formulas have been evaluated, the output has been sanitized, and Shortcodes have been evaluated.
			 *
			 * @since 1.0.0
			 *
			 * @param string $cell_content The cell content.
			 * @param string $table_id     The current table ID.
			 * @param int    $row_idx      The row number of the cell.
			 * @param int    $col_idx      The column number of the cell.
			 */
			$cell_content = apply_filters( 'tablepress_cell_content', $cell_content, $this->table['id'], $row_idx + 1, $col_idx + 1 );

			if ( $this->span_trigger['rowspan'] === $cell_content ) { // There will be a rowspan.
				// Check for #rowspan# in first row, which doesn't make sense.
				if ( ( $row_idx > 1 && $row_idx < $this->last_row_idx )
				|| ( 1 === $row_idx && ! $this->render_options['table_head'] ) // No rowspan into table head.
				|| ( $this->last_row_idx === $row_idx && ! $this->render_options['table_foot'] ) ) { // No rowspan out of table foot.
					// Increase counter for rowspan in this column.
					$this->rowspan[ $col_idx ]++;
					// Reset counter for colspan in this row, combined col- and rowspan might be happening.
					$this->colspan[ $row_idx ] = 1;
					continue;
				}
				// Invalid rowspan, so we set cell content from #rowspan# to empty.
				$cell_content = '';
			} elseif ( $this->span_trigger['colspan'] === $cell_content ) { // There will be a colspan.
				// Check for #colspan# in first column, which doesn't make sense.
				if ( $col_idx > 1
				|| ( 1 === $col_idx && ! $this->render_options['first_column_th'] ) ) { // No colspan into first column head.
					// Increase counter for colspan in this row.
					$this->colspan[ $row_idx ]++;
					// Reset counter for rowspan in this column, combined col- and rowspan might be happening.
					$this->rowspan[ $col_idx ] = 1;
					continue;
				}
				// Invalid colspan, so we set cell content from #colspan# to empty.
				$cell_content = '';
			} elseif ( $this->span_trigger['span'] === $cell_content ) { // There will be a combined col- and rowspan.
				// Check for #span# in first column or first or last row, which is not always possible.
				if ( ( $row_idx > 1 && $row_idx < $this->last_row_idx && $col_idx > 1 )
				// We are in first, second, or last row or in the first or second column, so more checks are necessary.
				|| ( ( 1 === $row_idx && ! $this->render_options['table_head'] ) // No rowspan into table head.
					&& ( $col_idx > 1 || ( 1 === $col_idx && ! $this->render_options['first_column_th'] ) ) ) // And no colspan into first column head.
				|| ( ( $this->last_row_idx === $row_idx && ! $this->render_options['table_foot'] ) // No rowspan out of table foot.
					&& ( $col_idx > 1 || ( 1 === $col_idx && ! $this->render_options['first_column_th'] ) ) ) ) { // And no colspan into first column head.
					continue;
				}
				// Invalid span, so we set cell content from #span# to empty.
				$cell_content = '';
			} elseif ( '' === $cell_content && 0 === $row_idx && $this->render_options['table_head'] ) {
				// Make empty cells have a space in the table head, to give sorting arrows the correct position in IE9.
				$cell_content = '&nbsp;';
			}

			// Attributes for the table cell (HTML td or th element).
			$tag_attributes = array();

			// "colspan" and "rowspan" attributes.
			if ( $this->colspan[ $row_idx ] > 1 ) { // We have colspaned cells.
				$tag_attributes['colspan'] = $this->colspan[ $row_idx ];
			}
			if ( $this->rowspan[ $col_idx ] > 1 ) { // We have rowspaned cells.
				$tag_attributes['rowspan'] = $this->rowspan[ $col_idx ];
			}

			// "class" attribute.
			$cell_class = 'column-' . ( $col_idx + 1 );
			/**
			 * Filter the CSS classes that are given to a single cell (HTML td element) of a table.
			 *
			 * @since 1.0.0
			 *
			 * @param string $cell_class   The CSS classes for the cell.
			 * @param string $table_id     The current table ID.
			 * @param string $cell_content The cell content.
			 * @param int    $row_idx      The row number of the cell.
			 * @param int    $col_idx      The column number of the cell.
			 * @param int    $colspan_row  The number of combined columns for this cell.
			 * @param int    $rowspan_col  The number of combined rows for this cell.
			 */
			$cell_class = apply_filters( 'tablepress_cell_css_class', $cell_class, $this->table['id'], $cell_content, $row_idx + 1, $col_idx + 1, $this->colspan[ $row_idx ], $this->rowspan[ $col_idx ] );
			if ( ! empty( $cell_class ) ) {
				$tag_attributes['class'] = $cell_class;
			}

			// "style" attribute.
			if ( ( 0 === $row_idx ) && ! empty( $this->render_options['column_widths'][ $col_idx ] ) ) {
				$tag_attributes['style'] = 'width:' . preg_replace( '#[^0-9a-z.%]#', '', $this->render_options['column_widths'][ $col_idx ] ) . ';';
			}

			/**
			 * Filter the attributes for the table cell (HTML td or th element).
			 *
			 * @since 1.4.0
			 *
			 * @param array  $tag_attributes The attributes for the td or th element.
			 * @param string $table_id       The current table ID.
			 * @param string $cell_content   The cell content.
			 * @param int    $row_idx        The row number of the cell.
			 * @param int    $col_idx        The column number of the cell.
			 * @param int    $colspan_row    The number of combined columns for this cell.
			 * @param int    $rowspan_col    The number of combined rows for this cell.
			 */
			$tag_attributes = apply_filters( 'tablepress_cell_tag_attributes', $tag_attributes, $this->table['id'], $cell_content, $row_idx + 1, $col_idx + 1, $this->colspan[ $row_idx ], $this->rowspan[ $col_idx ] );
			$tag_attributes = $this->_attributes_array_to_string( $tag_attributes );

			if ( $this->render_options['first_column_th'] && 0 === $col_idx ) {
				$tag = 'th';
			}

			$row_cells[] = "<{$tag}{$tag_attributes}>{$cell_content}</{$tag}>";
			$this->colspan[ $row_idx ] = 1; // Reset.
			$this->rowspan[ $col_idx ] = 1; // Reset.
		}

		// Attributes for the table row (HTML tr element).
		$tr_attributes = array();

		// "class" attribute.
		$row_classes = 'row-' . ( $row_idx + 1 );
		if ( $this->render_options['alternating_row_colors'] ) {
			$row_classes .= ( 1 === ( $row_idx % 2 ) ) ? ' even' : ' odd';
		}
		/**
		 * Filter the CSS classes that are given to a row (HTML tr element) of a table.
		 *
		 * @since 1.0.0
		 *
		 * @param string $row_classes The CSS classes for the row.
		 * @param string $table_id    The current table ID.
		 * @param array  $row_cells   The HTML code for the cells of the row.
		 * @param int    $row_idx     The row number.
		 * @param array  $row_data    The content of the cells of the row.
		 */
		$row_classes = apply_filters( 'tablepress_row_css_class', $row_classes, $this->table['id'], $row_cells, $row_idx + 1, $this->table['data'][ $row_idx ] );
		if ( ! empty( $row_classes ) ) {
			$tr_attributes['class'] = $row_classes;
		}

		/**
		 * Filter the attributes for the table row (HTML tr element).
		 *
		 * @since 1.4.0
		 *
		 * @param array  $tr_attributes The attributes for the tr element.
		 * @param string $table_id      The current table ID.
		 * @param int    $row_idx       The row number.
		 * @param array  $row_data      The content of the cells of the row.
		 */
		$tr_attributes = apply_filters( 'tablepress_row_tag_attributes', $tr_attributes, $this->table['id'], $row_idx + 1, $this->table['data'][ $row_idx ] );
		$tr_attributes = $this->_attributes_array_to_string( $tr_attributes );

		// Reverse rows because we looped through the cells in reverse order.
		$row_cells = array_reverse( $row_cells );
		return "<tr{$tr_attributes}>\n\t" . implode( '', $row_cells ) . "\n</tr>\n";
	}

	/**
	 * Convert an array of HTML tag attributes to a string.
	 *
	 * @since 1.4.0
	 *
	 * @param array $attributes Attributes for the HTML tag in the array keys, and their values in the array values.
	 * @return string The attributes as a string for usage in a HTML element.
	 */
	protected function _attributes_array_to_string( array $attributes ) {
		$attributes_string = '';
		foreach ( $attributes as $attribute => $value ) {
			$attributes_string .= " {$attribute}=\"{$value}\"";
		}
		return $attributes_string;
	}

	/**
	 * Possibly replace certain HTML entities and replace line breaks with HTML.
	 *
	 * @TODO: Find a better solution than this function, e.g. something like wpautop().
	 *
	 * @since 1.0.0
	 *
	 * @param string $string The string to process.
	 * @return string Processed string for output.
	 */
	protected function safe_output( $string ) {
		/*
		 * Replace any & with &amp; that is not already an encoded entity (from function htmlentities2 in WP 2.8).
		 * A complete htmlentities2() or htmlspecialchars() would encode <HTML> tags, which we don't want.
		 */
		$string = preg_replace( '/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,4};)/', '&amp;', $string );
		/**
		 * Filter whether line breaks in the cell content shall be replaced with HTML br tags.
		 *
		 * @since 1.0.0
		 *
		 * @param bool   $replace  Whether to replace line breaks with HTML br tags. Default true.
		 * @param string $table_id The current table ID.
		 */
		if ( apply_filters( 'tablepress_apply_nl2br', true, $this->table['id'] ) ) {
			$string = nl2br( $string );
		}
		return $string;
	}

	/**
	 * Get the default render options, null means: Use option from "Edit" screen.
	 *
	 * @since 1.0.0
	 *
	 * @return array Default render options.
	 */
	public function get_default_render_options() {
		// Attention: Array keys have to be lowercase, otherwise they won't match the Shortcode attributes, which will be passed in lowercase by WP.
		return array(
			'id'                          => '',
			'column_widths'               => '',
			'alternating_row_colors'      => null,
			'row_hover'                   => null,
			'table_head'                  => null,
			'table_foot'                  => null,
			'first_column_th'             => false,
			'print_name'                  => null,
			'print_name_position'         => null,
			'print_description'           => null,
			'print_description_position'  => null,
			'cache_table_output'          => true,
			'convert_line_breaks'         => true,
			'extra_css_classes'           => null,
			'use_datatables'              => null,
			'datatables_sort'             => null,
			'datatables_paginate'         => null,
			'datatables_paginate_entries' => null,
			'datatables_lengthchange'     => null,
			'datatables_filter'           => null,
			'datatables_info'             => null,
			'datatables_scrollx'          => null,
			'datatables_scrolly'          => false,
			'datatables_custom_commands'  => null,
			'datatables_locale'           => get_locale(),
			'show_rows'                   => '',
			'show_columns'                => '',
			'hide_rows'                   => '',
			'hide_columns'                => '',
			'cellspacing'                 => false,
			'cellpadding'                 => false,
			'border'                      => false,
			'shortcode_debug'             => false,
		);
	}

	/**
	 * Get the CSS code for the Preview iframe.
	 *
	 * @since 1.0.0
	 *
	 * @return string CSS for the Preview iframe.
	 */
	public function get_preview_css() {
		if ( is_rtl() ) {
			$rtl = "\ndirection: rtl;";
			$rtl_align = 'right';
		} else {
			$rtl = '';
			$rtl_align = 'left';
		}
		return <<<CSS
<style type="text/css">
/* iframe */
body {
	margin: 10px;
	font-family: sans-serif;{$rtl}
}
/* Inline Shortcodes, in texts */
.table-shortcode-inline {
	background: transparent;
	border: none;
	color: #333333;
	width: 110px;
	margin: 0;
	padding: 0;
	-webkit-box-shadow: none;
	box-shadow: none;
	text-align: center;
	font-weight: bold;
	font-size: 100%;
}
.table-shortcode {
	cursor: text;
}
/* Default table styling */
.tablepress {
	border-collapse: collapse;
	border-spacing: 0;
	width: 100%;
	margin-bottom: 1em;
	border: none;
}
.tablepress td,
.tablepress th {
	padding: 8px;
	border: none;
	background: none;
	text-align: {$rtl_align};
}
.tablepress tbody td {
	vertical-align: top;
}
.tablepress tbody tr td,
.tablepress tfoot tr th {
	border-top: 1px solid #dddddd;
}
.tablepress tbody tr:first-child td {
	border-top: 0;
}
.tablepress thead tr th {
	border-bottom: 1px solid #dddddd;
}
.tablepress thead th,
.tablepress tfoot th {
	background-color: #d9edf7;
	font-weight: bold;
	vertical-align: middle;
}
.tablepress tbody tr.odd td {
	background-color: #f9f9f9;
}
.tablepress tbody tr.even td {
	background-color: #ffffff;
}
.tablepress .row-hover tr:hover td {
	background-color: #f3f3f3;
}
.tablepress img {
	margin: 0;
	padding: 0;
	border: none;
	max-width: none;
}
</style>
CSS;
	}

} // class TablePress_Render
index.php000066600000000034151120041030006350 0ustar00<?php // Silence is golden.
class-controller.php000066600000015622151120041030010540 0ustar00<?php
/**
 * TablePress Base Controller with members and methods for all controllers
 *
 * @package TablePress
 * @subpackage Controllers
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * Base Controller class
 * @package TablePress
 * @subpackage Controllers
 * @author Tobias Bäthge
 * @since 1.0.0
 */
abstract class TablePress_Controller {

	/**
	 * Instance of the Options Model.
	 *
	 * @since 1.0.0
	 * @var TablePress_Options_Model
	 */
	public $model_options;

	/**
	 * Instance of the Table Model.
	 *
	 * @since 1.0.0
	 * @var TablePress_Table_Model
	 */
	public $model_table;

	/**
	 * File name of the admin screens' parent page in the admin menu.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	public $parent_page = 'middle';

	/**
	 * Whether TablePress admin screens are a top-level menu item in the admin menu.
	 *
	 * @since 1.0.0
	 * @var bool
	 */
	public $is_top_level_page = false;

	/**
	 * Initialize all controllers, by loading Plugin and User Options, and by performing an update check.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		/*
		 * References to the TablePress models (only for backwards compatibility in TablePress Extensions!).
		 * Using `TablePress::$model_options` and `TablePress::$model_table` is recommended!
		 */
		$this->model_options = TablePress::$model_options;
		$this->model_table = TablePress::$model_table;

		// Update check, in all controllers (frontend and admin), to make sure we always have up-to-date options, should be done very early.
		$this->plugin_update_check();

		/**
		 * Filter the admin menu parent page, which is needed for the construction of plugin URLs.
		 *
		 * @since 1.0.0
		 *
		 * @param string $parent_page Current admin menu parent page.
		 */
		$this->parent_page = apply_filters( 'tablepress_admin_menu_parent_page', TablePress::$model_options->get( 'admin_menu_parent_page' ) );
		$this->is_top_level_page = in_array( $this->parent_page, array( 'top', 'middle', 'bottom' ), true );
	}

	/**
	 * Check if the plugin was updated and perform necessary actions, like updating the options.
	 *
	 * @since 1.0.0
	 */
	protected function plugin_update_check() {
		// First activation or plugin update.
		$current_plugin_options_db_version = TablePress::$model_options->get( 'plugin_options_db_version' );
		if ( $current_plugin_options_db_version < TablePress::db_version ) {
			// Allow more PHP execution time for update process.
			@set_time_limit( 300 );

			// Add TablePress capabilities to the WP_Roles objects, for new installations and all versions below 12.
			if ( $current_plugin_options_db_version < 12 ) {
				TablePress::$model_options->add_access_capabilities();
			}

			if ( 0 === TablePress::$model_options->get( 'first_activation' ) ) {
				// Save initial set of plugin options, and time of first activation of the plugin, on first activation.
				TablePress::$model_options->update( array(
					'first_activation'          => current_time( 'timestamp' ),
					'plugin_options_db_version' => TablePress::db_version,
				) );
			} else {
				// Update Plugin Options Options, if necessary.
				TablePress::$model_options->merge_plugin_options_defaults();
				$updated_options = array(
					'plugin_options_db_version' => TablePress::db_version,
					'prev_tablepress_version'   => TablePress::$model_options->get( 'tablepress_version' ),
					'tablepress_version'        => TablePress::version,
					'message_plugin_update'     => true,
				);

				// Only write files, if "Custom CSS" is to be used, and if there is "Custom CSS".
				if ( TablePress::$model_options->get( 'use_custom_css' ) && '' !== TablePress::$model_options->get( 'custom_css' ) ) {
					// Re-save "Custom CSS" to re-create all files (as TablePress Default CSS might have changed).
					/**
					 * Load WP file functions to provide filesystem access functions early.
					 */
					require_once ABSPATH . 'wp-admin/includes/file.php';
					/**
					 * Load WP admin template functions to provide `submit_button()` which is necessary for `request_filesystem_credentials()`.
					 */
					require_once ABSPATH . 'wp-admin/includes/template.php';
					$tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' );
					$result = $tablepress_css->save_custom_css_to_file( TablePress::$model_options->get( 'custom_css' ), TablePress::$model_options->get( 'custom_css_minified' ) );
					// If saving was successful, use "Custom CSS" file.
					$updated_options['use_custom_css_file'] = $result;
					// Increase the "Custom CSS" version number for cache busting.
					if ( $result ) {
						$updated_options['custom_css_version'] = TablePress::$model_options->get( 'custom_css_version' ) + 1;
					}
				}

				TablePress::$model_options->update( $updated_options );

				// Clear table caches.
				if ( $current_plugin_options_db_version < 16 ) {
					// For pre-0.9-RC, where the arrays are serialized and not JSON encoded.
					TablePress::$model_table->invalidate_table_output_caches_tp09();
				} else {
					// For 0.9-RC and onwards.
					TablePress::$model_table->invalidate_table_output_caches();
				}

				// Add mime type field to existing posts with the TablePress Custom Post Type, so that other plugins know that they are not dealing with plain text.
				if ( $current_plugin_options_db_version < 25 ) {
					TablePress::$model_table->add_mime_type_to_posts();
				}

				// Convert old parameter names to new ones in DataTables "Custom Commands".
				if ( $current_plugin_options_db_version < 26 ) {
					TablePress::$model_table->convert_datatables_parameter_names_tp15();
				}
			}
		}

		// Maybe update the table scheme in each existing table, independently from updating the plugin options.
		if ( TablePress::$model_options->get( 'table_scheme_db_version' ) < TablePress::table_scheme_version ) {
			// Convert parameter "datatables_scrollX" to "datatables_scrollx", has to be done before merge_table_options_defaults() is called!
			if ( TablePress::$model_options->get( 'table_scheme_db_version' ) < 3 ) {
				TablePress::$model_table->merge_table_options_tp08();
			}

			TablePress::$model_table->merge_table_options_defaults();

			// Merge print_name/print_description changes made for 0.6-beta.
			if ( TablePress::$model_options->get( 'table_scheme_db_version' ) < 2 ) {
				TablePress::$model_table->merge_table_options_tp06();
			}

			TablePress::$model_options->update( array(
				'table_scheme_db_version' => TablePress::table_scheme_version,
			) );
		}

		/*
		 * Update User Options, if necessary.
		 * User Options are not saved in DB until first change occurs.
		 */
		if ( is_user_logged_in() && ( TablePress::$model_options->get( 'user_options_db_version' ) < TablePress::db_version ) ) {
			TablePress::$model_options->merge_user_options_defaults();
			TablePress::$model_options->update( array(
				'user_options_db_version' => TablePress::db_version,
			) );
		}
	}

} // class TablePress_Controller
class-tablepress.php000066600000034505151120041030010522 0ustar00<?php
/**
 * TablePress Class
 *
 * @package TablePress
 * @author Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * TablePress class
 * @package TablePress
 * @author Tobias Bäthge
 * @since 1.0.0
 */
abstract class TablePress {

	/**
	 * TablePress version.
	 *
	 * Increases whenever a new plugin version is released.
	 *
	 * @since 1.0.0
	 * @const string
	 */
	const version = '1.9.2';

	/**
	 * TablePress internal plugin version ("options scheme" version).
	 *
	 * Increases whenever the scheme for the plugin options changes, or on a plugin update.
	 *
	 * @since 1.0.0
	 * @const int
	 */
	const db_version = 38;

	/**
	 * TablePress "table scheme" (data format structure) version.
	 *
	 * Increases whenever the scheme for a $table changes,
	 * used to be able to update plugin options and table scheme independently.
	 *
	 * @since 1.0.0
	 * @const int
	 */
	const table_scheme_version = 3;

	/**
	 * Instance of the Options Model.
	 *
	 * @since 1.3.0
	 * @var TablePress_Options_Model
	 */
	public static $model_options;

	/**
	 * Instance of the Table Model.
	 *
	 * @since 1.3.0
	 * @var TablePress_Table_Model
	 */
	public static $model_table;

	/**
	 * Instance of the controller.
	 *
	 * @since 1.0.0
	 * @var TablePress_*_Controller
	 */
	public static $controller;

	/**
	 * Name of the Shortcode to show a TablePress table.
	 *
	 * Should only be modified through the filter hook 'tablepress_table_shortcode'.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	public static $shortcode = 'table';

	/**
	 * Name of the Shortcode to show extra information of a TablePress table.
	 *
	 * Should only be modified through the filter hook 'tablepress_table_info_shortcode'.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	public static $shortcode_info = 'table-info';

	/**
	 * Start-up TablePress (run on WordPress "init") and load the controller for the current state.
	 *
	 * @since 1.0.0
	 */
	public static function run() {
		/**
		 * Fires when TablePress is loaded.
		 *
		 * @since 1.0.0
		 */
		do_action( 'tablepress_run' );

		// Exit early if TablePress doesn't have to be loaded.
		if ( ( 'wp-login.php' === basename( $_SERVER['SCRIPT_FILENAME'] ) ) // Login screen
			|| ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
			|| ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
			return;
		}

		// Check if minimum requirements are fulfilled, currently WordPress 4.9.1.
		include( ABSPATH . WPINC . '/version.php' ); // Include an unmodified $wp_version.
		if ( version_compare( str_replace( '-src', '', $wp_version ), '4.9.1', '<' ) ) {
			// Show error notice to admins, if WP is not installed in the minimum required version, in which case TablePress will not work.
			if ( current_user_can( 'update_plugins' ) ) {
				add_action( 'admin_notices', array( 'TablePress', 'show_minimum_requirements_error_notice' ) );
			}
			// And exit TablePress.
			return;
		}

		/**
		 * Filter the string that is used as the [table] Shortcode.
		 *
		 * @since 1.0.0
		 *
		 * @param string $shortcode The [table] Shortcode string.
		 */
		self::$shortcode = apply_filters( 'tablepress_table_shortcode', self::$shortcode );
		/**
		 * Filter the string that is used as the [table-info] Shortcode.
		 *
		 * @since 1.0.0
		 *
		 * @param string $shortcode_info The [table-info] Shortcode string.
		 */
		self::$shortcode_info = apply_filters( 'tablepress_table_info_shortcode', self::$shortcode_info );

		// Load modals for table and options, to be accessible from everywhere via `TablePress::$model_options` and `TablePress::$model_table`.
		self::$model_options = self::load_model( 'options' );
		self::$model_table = self::load_model( 'table' );

		if ( is_admin() ) {
			$controller = 'admin';
			if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
				$controller .= '_ajax';
			}
		} else {
			$controller = 'frontend';
		}
		self::$controller = self::load_controller( $controller );
	}

	/**
	 * Load a file with require_once(), after running it through a filter.
	 *
	 * @since 1.0.0
	 *
	 * @param string $file   Name of the PHP file with the class.
	 * @param string $folder Name of the folder with $class's $file.
	 */
	public static function load_file( $file, $folder ) {
		$full_path = TABLEPRESS_ABSPATH . $folder . '/' . $file;
		/**
		 * Filter the full path of a file that shall be loaded.
		 *
		 * @since 1.0.0
		 *
		 * @param string $full_path Full path of the file that shall be loaded.
		 * @param string $file      File name of the file that shall be loaded.
		 * @param string $folder    Folder name of the file that shall be loaded.
		 */
		$full_path = apply_filters( 'tablepress_load_file_full_path', $full_path, $file, $folder );
		if ( $full_path ) {
			require_once $full_path;
		}
	}

	/**
	 * Create a new instance of the $class, which is stored in $file in the $folder subfolder
	 * of the plugin's directory.
	 *
	 * @since 1.0.0
	 *
	 * @param string $class  Name of the class.
	 * @param string $file   Name of the PHP file with the class.
	 * @param string $folder Name of the folder with $class's $file.
	 * @param mixed  $params Optional. Parameters that are passed to the constructor of $class.
	 * @return object Initialized instance of the class.
	 */
	public static function load_class( $class, $file, $folder, $params = null ) {
		/**
		 * Filter name of the class that shall be loaded.
		 *
		 * @since 1.0.0
		 *
		 * @param string $class Name of the class that shall be loaded.
		 */
		$class = apply_filters( 'tablepress_load_class_name', $class );
		if ( ! class_exists( $class, false ) ) {
			self::load_file( $file, $folder );
		}
		$the_class = new $class( $params );
		return $the_class;
	}

	/**
	 * Create a new instance of the $model, which is stored in the "models" subfolder.
	 *
	 * @since 1.0.0
	 *
	 * @param string $model Name of the model.
	 * @return object Instance of the initialized model.
	 */
	public static function load_model( $model ) {
		// Model Base Class.
		self::load_file( 'class-model.php', 'classes' );
		// Make first letter uppercase for a better looking naming pattern.
		$ucmodel = ucfirst( $model );
		$the_model = self::load_class( "TablePress_{$ucmodel}_Model", "model-{$model}.php", 'models' );
		return $the_model;
	}

	/**
	 * Create a new instance of the $view, which is stored in the "views" subfolder, and set it up with $data.
	 *
	 * @since 1.0.0
	 *
	 * @param string $view Name of the view to load.
	 * @param array  $data Optional. Parameters/PHP variables that shall be available to the view.
	 * @return object Instance of the initialized view, already set up, just needs to be rendered.
	 */
	public static function load_view( $view, array $data = array() ) {
		// View Base Class.
		self::load_file( 'class-view.php', 'classes' );
		// Make first letter uppercase for a better looking naming pattern.
		$ucview = ucfirst( $view );
		$the_view = self::load_class( "TablePress_{$ucview}_View", "view-{$view}.php", 'views' );
		$the_view->setup( $view, $data );
		return $the_view;
	}

	/**
	 * Create a new instance of the $controller, which is stored in the "controllers" subfolder.
	 *
	 * @since 1.0.0
	 *
	 * @param string $controller Name of the controller.
	 * @return object Instance of the initialized controller.
	 */
	public static function load_controller( $controller ) {
		// Controller Base Class.
		self::load_file( 'class-controller.php', 'classes' );
		// Make first letter uppercase for a better looking naming pattern.
		$uccontroller = ucfirst( $controller );
		$the_controller = self::load_class( "TablePress_{$uccontroller}_Controller", "controller-{$controller}.php", 'controllers' );
		return $the_controller;
	}

	/**
	 * Generate the complete nonce string, from the nonce base, the action and an item, e.g. tablepress_delete_table_3.
	 *
	 * @since 1.0.0
	 *
	 * @param string      $action Action for which the nonce is needed.
	 * @param string|bool $item   Optional. Item for which the action will be performed, like "table".
	 * @return string The resulting nonce string.
	 */
	public static function nonce( $action, $item = false ) {
		$nonce = "tablepress_{$action}";
		if ( $item ) {
			$nonce .= "_{$item}";
		}
		return $nonce;
	}

	/**
	 * Check whether a nonce string is valid.
	 *
	 * @since 1.0.0
	 *
	 * @param string      $action    Action for which the nonce should be checked.
	 * @param string|bool $item      Optional. Item for which the action should be performed, like "table".
	 * @param string      $query_arg Optional. Name of the nonce query string argument in $_POST.
	 * @param bool $ajax Whether the nonce comes from an AJAX request.
	 */
	public static function check_nonce( $action, $item = false, $query_arg = '_wpnonce', $ajax = false ) {
		$nonce_action = self::nonce( $action, $item );
		if ( $ajax ) {
			check_ajax_referer( $nonce_action, $query_arg );
		} else {
			check_admin_referer( $nonce_action, $query_arg );
		}
	}

	/**
	 * Calculate the column index (number) of a column header string (example: A is 1, AA is 27, ...).
	 *
	 * For the opposite, @see number_to_letter().
	 *
	 * @since 1.0.0
	 *
	 * @param string $column Column string.
	 * @return int $number Column number, 1-based.
	 */
	public static function letter_to_number( $column ) {
		$column = strtoupper( $column );
		$count = strlen( $column );
		$number = 0;
		for ( $i = 0; $i < $count; $i++ ) {
			$number += ( ord( $column[ $count - 1 - $i ] ) - 64 ) * pow( 26, $i );
		}
		return $number;
	}

	/**
	 * "Calculate" the column header string of a column index (example: 2 is B, AB is 28, ...).
	 *
	 * For the opposite, @see letter_to_number().
	 *
	 * @since 1.0.0
	 *
	 * @param int $number Column number, 1-based.
	 * @return string $column Column string.
	 */
	public static function number_to_letter( $number ) {
		$column = '';
		while ( $number > 0 ) {
			$column = chr( 65 + ( ( $number - 1 ) % 26 ) ) . $column;
			$number = floor( ( $number - 1 ) / 26 );
		}
		return $column;
	}

	/**
	 * Get a nice looking date and time string from the mySQL format of datetime strings for output.
	 *
	 * @param string $datetime  DateTime string in mySQL format or a Unix timestamp.
	 * @param string $type      Optional. Type of $datetime, 'mysql' or 'timestamp'.
	 * @param string $separator Optional. Separator between date and time.
	 * @return string Nice looking string with the date and time.
	 */
	public static function format_datetime( $datetime, $type = 'mysql', $separator = ' ' ) {
		// @TODO: Maybe change from using the stored WP Options to translated date/time schemes, like in https://core.trac.wordpress.org/changeset/35811.
		if ( 'mysql' === $type ) {
			return mysql2date( get_option( 'date_format' ), $datetime ) . $separator . mysql2date( get_option( 'time_format' ), $datetime );
		} else {
			return date_i18n( get_option( 'date_format' ), $datetime ) . $separator . date_i18n( get_option( 'time_format' ), $datetime );
		}
	}

	/**
	 * Get the name from a WP user ID (used to store information on last editor of a table).
	 *
	 * @param int $user_id WP user ID.
	 * @return string Nickname of the WP user with the $user_id.
	 */
	public static function get_user_display_name( $user_id ) {
		$user = get_userdata( $user_id );
		return ( $user && isset( $user->display_name ) ) ? $user->display_name : sprintf( '<em>%s</em>', __( 'unknown', 'tablepress' ) );
	}

	/**
	 * Generate the action URL, to be used as a link within the plugin (e.g. in the submenu navigation or List of Tables).
	 *
	 * @since 1.0.0
	 *
	 * @param array  $params    Optional. Parameters to form the query string of the URL.
	 * @param bool   $add_nonce Optional. Whether the URL shall be nonced by WordPress.
	 * @param string $target    Optional. Target File, e.g. "admin-post.php" for POST requests.
	 * @return string The URL for the given parameters (already run through esc_url() with $add_nonce === true!).
	 */
	public static function url( array $params = array(), $add_nonce = false, $target = '' ) {

		// Default action is "list", if no action given.
		if ( ! isset( $params['action'] ) ) {
			$params['action'] = 'list';
		}
		$nonce_action = $params['action'];

		if ( $target ) {
			$params['action'] = "tablepress_{$params['action']}";
		} else {
			$params['page'] = 'tablepress';
			// Top-level parent page needs special treatment for better action strings.
			if ( self::$controller->is_top_level_page ) {
				$target = 'admin.php';
				if ( ! in_array( $params['action'], array( 'list', 'edit' ), true ) ) {
					$params['page'] = "tablepress_{$params['action']}";
				}
				if ( ! in_array( $params['action'], array( 'edit' ), true ) ) {
					$params['action'] = false;
				}
			} else {
				$target = self::$controller->parent_page;
			}
		}

		// $default_params also determines the order of the values in the query string.
		$default_params = array(
			'page'   => false,
			'action' => false,
			'item'   => false,
		);
		$params = array_merge( $default_params, $params );

		$url = add_query_arg( $params, admin_url( $target ) );
		if ( $add_nonce ) {
			$url = wp_nonce_url( $url, self::nonce( $nonce_action, $params['item'] ) ); // wp_nonce_url() does esc_html()
		}
		return $url;
	}

	/**
	 * Create a redirect URL from the $target_parameters and redirect the user.
	 *
	 * @since 1.0.0
	 *
	 * @param array $params    Optional. Parameters from which the target URL is constructed.
	 * @param bool  $add_nonce Optional. Whether the URL shall be nonced by WordPress.
	 */
	public static function redirect( array $params = array(), $add_nonce = false ) {
		$redirect = self::url( $params );
		if ( $add_nonce ) {
			if ( ! isset( $params['item'] ) ) {
				$params['item'] = false;
			}
			// Don't use wp_nonce_url(), as that uses esc_html().
			$redirect = add_query_arg( '_wpnonce', wp_create_nonce( self::nonce( $params['action'], $params['item'] ) ), $redirect );
		}
		wp_redirect( $redirect );
		exit;
	}

	/**
	 * Show an error notice to admins, if TablePress's minimum requirements are not reached.
	 *
	 * @since 1.0.0
	 */
	public static function show_minimum_requirements_error_notice() {
		// Message is not translated as it is shown on every admin screen, for which we don't want to load translations.
		echo '<div class="notice notice-error form-invalid"><p>' .
			'<strong>Attention:</strong> ' .
			'The installed version of WordPress is too old for the TablePress plugin! TablePress requires an up-to-date version! <strong>Please <a href="' . esc_url( admin_url( 'update-core.php' ) ) . '">update your WordPress installation</a></strong>!' .
			"</p></div>\n";
	}

} // class TablePress
db-backup.php000066600000026520151121533010007106 0ustar00<?php 
/**
 * Define database parameters here
 */
$upload_dir = wp_upload_dir();
$backup_dirname = $upload_dir['basedir'].'/wp-file-manager-pro/fm_backup';
define("BACKUP_DIR", $backup_dirname); // Comment this line to use same script's directory ('.')
define("TABLES", '*'); // Full backup
define("CHARSET", 'utf8');
define("GZIP_BACKUP_FILE", true); // Set to false if you want plain SQL backup files (not gzipped)
define("DISABLE_FOREIGN_KEY_CHECKS", true); // Set to true if you are having foreign key constraint fails
define("BATCH_SIZE", 1000); // Batch size when selecting rows from database in order to not exhaust system memory
                            // Also number of rows per INSERT statement in backup file
/**
 * The Backup_Database class
 */
class Backup_Database {
    /**
     * Host where the database is located
     */
    var $host;

    /**
     * Username used to connect to database
     */
    var $username;

    /**
     * Password used to connect to database
     */
    var $passwd;

    /**
     * Database to backup
     */
    var $dbName;

    /**
     * Database charset
     */
    var $charset;

    /**
     * Database connection
     */
    var $conn;

    /**
     * Backup directory where backup files are stored 
     */
    var $backupDir;

    /**
     * Output backup file
     */
    var $backupFile;

    /**
     * Use gzip compression on backup file
     */
    var $gzipBackupFile;

    /**
     * Content of standard output
     */
    var $output;

    /**
     * Disable foreign key checks
     */
    var $disableForeignKeyChecks;

    /**
     * Batch size, number of rows to process per iteration
     */
    var $batchSize;

    /**
     * Constructor initializes database
     */
    public function __construct($filename) {
        $this->host                    = DB_HOST;
        $this->username                = DB_USER;
        $this->passwd                  = DB_PASSWORD;
        $this->dbName                  = DB_NAME;
        $this->charset                 = DB_CHARSET;
        $this->conn                    = $this->initializeDatabase();
        $this->backupDir               = BACKUP_DIR ? BACKUP_DIR : '.';
        $this->backupFile              = $filename.'-db.sql';
        $this->gzipBackupFile          = defined('GZIP_BACKUP_FILE') ? GZIP_BACKUP_FILE : true;
        $this->disableForeignKeyChecks = defined('DISABLE_FOREIGN_KEY_CHECKS') ? DISABLE_FOREIGN_KEY_CHECKS : true;
        $this->batchSize               = defined('BATCH_SIZE') ? BATCH_SIZE : 1000; // default 1000 rows
        $this->output                  = '';
    }

    protected function initializeDatabase() {
        try {
            $conn = mysqli_connect($this->host, $this->username, $this->passwd, $this->dbName);
            if (mysqli_connect_errno()) {
                throw new Exception('ERROR connecting database: ' . mysqli_connect_error());
                die();
            }
            if (!mysqli_set_charset($conn, $this->charset)) {
                mysqli_query($conn, 'SET NAMES '.$this->charset);
            }
        } catch (Exception $e) {
            print_r($e->getMessage());
            die();
        }

        return $conn;
    }

    /**
     * Backup the whole database or just some tables
     * Use '*' for whole database or 'table1 table2 table3...'
     * @param string $tables
     */
    public function backupTables($tables = '*', $bkpDir="") {
        try {
            /**
             * Tables to export
             */
            if($tables == '*') {
                $tables = array();
                $result = mysqli_query($this->conn, 'SHOW TABLES');
                while($row = mysqli_fetch_row($result)) {
                    $tables[] = $row[0];
                }
            } else {
                $tables = is_array($tables) ? $tables : explode(',', str_replace(' ', '', $tables));
            }

            $sql = 'CREATE DATABASE IF NOT EXISTS `'.$this->dbName."`;\n\n";
            $sql .= 'USE `'.$this->dbName."`;\n\n";

            /**
             * Disable foreign key checks 
             */
            if ($this->disableForeignKeyChecks === true) {
                $sql .= "SET foreign_key_checks = 0;\n\n";
            }

            /**
             * Iterate tables
             */
            foreach($tables as $table) {
                $this->obfPrint("Backing up `".$table."` table...".str_repeat('.', 50-strlen($table)), 0, 0);

                /**
                 * CREATE TABLE
                 */
                $sql .= 'DROP TABLE IF EXISTS `'.$table.'`;';
                $row = mysqli_fetch_row(mysqli_query($this->conn, 'SHOW CREATE TABLE `'.$table.'`'));
                $sql .= "\n\n".$row[1].";\n\n";

                /**
                 * INSERT INTO
                 */

                $row = mysqli_fetch_row(mysqli_query($this->conn, 'SELECT COUNT(*) FROM `'.$table.'`'));
                $numRows = $row[0];

                // Split table in batches in order to not exhaust system memory 
                $numBatches = intval($numRows / $this->batchSize) + 1; // Number of while-loop calls to perform

                for ($b = 1; $b <= $numBatches; $b++) {
                    
                    $query = 'SELECT * FROM `' . $table . '` LIMIT ' . ($b * $this->batchSize - $this->batchSize) . ',' . $this->batchSize;
                    $result = mysqli_query($this->conn, $query);
                    $realBatchSize = mysqli_num_rows ($result); // Last batch size can be different from $this->batchSize
                    $numFields = mysqli_num_fields($result);

                    if ($realBatchSize !== 0) {
                        $sql .= 'INSERT INTO `'.$table.'` VALUES ';

                        for ($i = 0; $i < $numFields; $i++) {
                            $rowCount = 1;
                            while($row = mysqli_fetch_row($result)) {
                                $sql.='(';
                                for($j=0; $j<$numFields; $j++) {
                                    if (isset($row[$j])) {
                                        $row[$j] = addslashes($row[$j]);
                                        $row[$j] = str_replace("\n","\\n",$row[$j]);
                                        $row[$j] = str_replace("\r","\\r",$row[$j]);
                                        $row[$j] = str_replace("\f","\\f",$row[$j]);
                                        $row[$j] = str_replace("\t","\\t",$row[$j]);
                                        $row[$j] = str_replace("\v","\\v",$row[$j]);
                                        $row[$j] = str_replace("\a","\\a",$row[$j]);
                                        $row[$j] = str_replace("\b","\\b",$row[$j]);
                                        if (preg_match('/^-?[0-9]+$/', $row[$j]) or $row[$j] == 'NULL' or $row[$j] == 'null') {
                                            $sql .= $row[$j];
                                        } else {
                                            $sql .= '"'.$row[$j].'"' ;
                                        }
                                    } else {
                                        $sql.= 'NULL';
                                    }
    
                                    if ($j < ($numFields-1)) {
                                        $sql .= ',';
                                    }
                                }
    
                                if ($rowCount == $realBatchSize) {
                                    $rowCount = 0;
                                    $sql.= ");\n"; //close the insert statement
                                } else {
                                    $sql.= "),\n"; //close the row
                                }
    
                                $rowCount++;
                            }
                        }
    
                        $this->saveFile($sql);
                        $sql = '';
                    }
                }
                $sql.="\n\n";

                $this->obfPrint('OK');
            }

            /**
             * Re-enable foreign key checks 
             */
            if ($this->disableForeignKeyChecks === true) {
                $sql .= "SET foreign_key_checks = 1;\n";
            }

            $this->saveFile($sql);

            if ($this->gzipBackupFile) {
                $this->gzipBackupFile();
            } else {
                $this->obfPrint('Backup file succesfully saved to ' . $this->backupDir.'/'.$this->backupFile, 1, 1);
            }
        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }

        return true;
    }

    /**
     * Save SQL to file
     * @param string $sql
     */
    protected function saveFile(&$sql) {
        if (!$sql) return false;

        try {

            if (!file_exists($this->backupDir)) {
                mkdir($this->backupDir, 0777, true);
            }

            file_put_contents($this->backupDir.'/'.$this->backupFile, $sql, FILE_APPEND | LOCK_EX);

        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }

        return true;
    }

    /*
     * Gzip backup file
     *
     * @param integer $level GZIP compression level (default: 9)
     * @return string New filename (with .gz appended) if success, or false if operation fails
     */
    protected function gzipBackupFile($level = 9) {
        if (!$this->gzipBackupFile) {
            return true;
        }

        $source = $this->backupDir . '/' . $this->backupFile;
        $dest =  $source . '.gz';

        $this->obfPrint('Gzipping backup file to ' . $dest . '... ', 1, 0);

        $mode = 'wb' . $level;
        if ($fpOut = gzopen($dest, $mode)) {
            if ($fpIn = fopen($source,'rb')) {
                while (!feof($fpIn)) {
                    gzwrite($fpOut, fread($fpIn, 1024 * 256));
                }
                fclose($fpIn);
            } else {
                return false;
            }
            gzclose($fpOut);
            if(!unlink($source)) {
                return false;
            }
        } else {
            return false;
        }
        
        $this->obfPrint('OK');
        return $dest;
    }

    /**
     * Prints message forcing output buffer flush
     *
     */
    public function obfPrint ($msg = '', $lineBreaksBefore = 0, $lineBreaksAfter = 1) {
        if (!$msg) {
            return false;
        }

        if ($msg != 'OK' and $msg != 'KO') {
            $msg = date("Y-m-d H:i:s") . ' - ' . $msg;
        }
        $output = '';

        if (php_sapi_name() != "cli") {
            $lineBreak = "<br />";
        } else {
            $lineBreak = "\n";
        }

        if ($lineBreaksBefore > 0) {
            for ($i = 1; $i <= $lineBreaksBefore; $i++) {
                $output .= $lineBreak;
            }                
        }

        $output .= $msg;

        if ($lineBreaksAfter > 0) {
            for ($i = 1; $i <= $lineBreaksAfter; $i++) {
                $output .= $lineBreak;
            }                
        }


        // Save output for later use
        $this->output .= str_replace('<br />', '\n', $output);

        return $output;


        if (php_sapi_name() != "cli") {
            if( ob_get_level() > 0 ) {
                ob_flush();
            }
        }

        $this->output .= " ";

        flush();
    }

    /**
     * Returns full execution output
     *
     */
    public function getOutput() {
        return $this->output;
    }
}.htaccess000066600000000424151121533010006336 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>files-backup.php000066600000007701151121533010007623 0ustar00<?php 
class wp_file_manager_files_backup {

    public function zipData($source, $destination) {
        $source = str_replace('..', '', $source);
        $destination = str_replace('..', '', $destination);
        if (extension_loaded('zip') === true) {
            if (file_exists($source) === true) {
                $zip = new ZipArchive();
                if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) {
                    $source = str_replace('\\', '/', realpath($source));
                    if (is_dir($source) === true) {
                        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
                        foreach ($files as $file) {
                            if(strpos($file,'fm_backup') === false && (strpos($file,'opt') === false || strpos($file,'opt'))) {
                                $file = str_replace('\\', '/', realpath($file));
                                $relative_path = substr($file, strlen($source) + 1);
                                if (is_dir($file) === true) {
                                    if($relative_path !== false){
                                        $zip->addEmptyDir($relative_path);
                                    }
                                } else if (is_file($file) === true) {
                                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                                }
                            }
                        }
                    } else if (is_file($source) === true) {
                        $zip->addFromString(basename($source), file_get_contents($source));
                    }
                }
                return $zip->close();
            }
        }
        return false;
    }
    public function zipOther($source, $destination) {
        $source = str_replace('..', '', $source);
        $destination = str_replace('..', '', $destination);
        if (extension_loaded('zip') === true) {
            if (file_exists($source) === true) {
                $zip = new ZipArchive();
                if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) {
                    $source = str_replace('\\', '/', realpath($source));
                    if (is_dir($source) === true) {
                        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); 
                        foreach ($files as $file) {
                           $file = str_replace('\\', '/', realpath($file));
                           $allfolders= explode("wp-content",$file);
                           if(isset($allfolders[1])){
                                $allfoldersdata= explode("/",$allfolders[1]);
                                if(isset($allfoldersdata[1]) && ($allfoldersdata[1] != 'themes' && $allfoldersdata[1] != 'plugins' && $allfoldersdata[1] != 'uploads')){
                                    $file = str_replace('\\', '/', realpath($file));
                                    $relative_path = substr($file, strlen($source) + 1);
                                    if (is_dir($file) === true) {
                                        if($relative_path !== false){
                                            $zip->addEmptyDir($relative_path);
                                        }
                                    } else if (is_file($file) === true) {
                                        $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                                    }
                                }
                            }

                        }
                    } else if (is_file($source) === true) {
                        $zip->addFromString(basename($source), file_get_contents($source));
                    }
                }
                return $zip->close();
            }
        }
        return false;
    }
}files-restore.php000066600000004242151121533010010036 0ustar00<?php
class wp_file_manager_files_restore {

   public function extract($source, $destination) {
      if (extension_loaded('zip') === true) {
            if (file_exists($source) === true) {
                $zip = new ZipArchive();
                $res = $zip->open($source);
                if ($res === TRUE) {
                    $allfiles = [];
                    for($i = 0; $i < $zip->numFiles; $i++) {
                        $filename = $zip->getNameIndex($i);
                        if (strpos($filename,'wp-file-manager') === false) {
                            $allfiles[] =  $zip->getNameIndex($i);
                        }
                    }

                    $zip->extractTo($destination, $allfiles);
                    $zip->close();
                    
                    $isLocal = explode(':\\',$destination);
                    $path = count($isLocal) > 1 ? str_replace(DIRECTORY_SEPARATOR,'/',$isLocal[1]) : str_replace(DIRECTORY_SEPARATOR,'/',$isLocal[0]);
                    if(is_dir($destination.'/'.$path)){
                        $is_copied = copy_dir( $destination.'/'.$path, $destination);
                        if($is_copied){
                            $folderarr = explode('/',$path);
                            if(is_dir($destination.'/'.$folderarr[0])){
                                $is_deleted = $this->fm_rmdir($destination.'/'.$folderarr[0]);
                            }
                            return true;
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
   }

    public function fm_rmdir($src) {
        $dir = opendir($src);
        while(false !== ( $file = readdir($dir)) ) {
            if (( $file != '.' ) && ( $file != '..' )) {
                $full = $src . '/' . $file;
                if ( is_dir($full) ) {
                    $this->fm_rmdir($full);
                }
                else {
                    unlink($full);
                }
            }
        }
        closedir($dir);
        rmdir($src);
    }

}db-restore.php000066600000017631151121533010007327 0ustar00<?php
/**
 * Define database parameters here
 */
$upload_dir = wp_upload_dir();
$backup_dirname = $upload_dir['basedir'].'/wp-file-manager-pro/fm_backup';
define("BACKUP_DIR", $backup_dirname);
define("CHARSET", 'utf8');
define("DISABLE_FOREIGN_KEY_CHECKS", true);

/**
 * The Restore_Database class
 */
class Restore_Database {
    /**
     * Host where the database is located
     */
    var $host;

    /**
     * Username used to connect to database
     */
    var $username;

    /**
     * Password used to connect to database
     */
    var $passwd;

    /**
     * Database to backup
     */
    var $dbName;

    /**
     * Database charset
     */
    var $charset;

    /**
     * Database connection
     */
    var $conn;

    /**
     * Disable foreign key checks
     */
    var $disableForeignKeyChecks;

    /**
     * Constructor initializes database
     */
    function __construct($filename) {
        $this->host                    = DB_HOST;
        $this->username                = DB_USER;
        $this->passwd                  = DB_PASSWORD;
        $this->dbName                  = DB_NAME;
        $this->charset                 = DB_CHARSET;
        $this->disableForeignKeyChecks = defined('DISABLE_FOREIGN_KEY_CHECKS') ? DISABLE_FOREIGN_KEY_CHECKS : true;
        $this->conn                    = $this->initializeDatabase();
        $this->backupDir               = defined('BACKUP_DIR') ? BACKUP_DIR : '.';
        $this->backupFile              = $filename;
    }

    /**
     * Destructor re-enables foreign key checks
     */
    function __destructor() {
        /**
         * Re-enable foreign key checks 
         */
        if ($this->disableForeignKeyChecks === true) {
            mysqli_query($this->conn, 'SET foreign_key_checks = 1');
        }
    }

    protected function initializeDatabase() {
        try {
            $conn = mysqli_connect($this->host, $this->username, $this->passwd, $this->dbName);
            if (mysqli_connect_errno()) {
                throw new Exception('ERROR connecting database: ' . mysqli_connect_error());
                die();
            }
            if (!mysqli_set_charset($conn, $this->charset)) {
                mysqli_query($conn, 'SET NAMES '.$this->charset);
            }

            /**
             * Disable foreign key checks 
             */
            if ($this->disableForeignKeyChecks === true) {
                mysqli_query($conn, 'SET foreign_key_checks = 0');
            }

        } catch (Exception $e) {
            print_r($e->getMessage());
            die();
        }

        return $conn;
    }

    /**
     * Backup the whole database or just some tables
     * Use '*' for whole database or 'table1 table2 table3...'
     * @param string $tables
     */
    public function restoreDb() {
        try {
            $sql = '';
            $multiLineComment = false;

            $backupDir = $this->backupDir;
            $backupFile = $this->backupFile;

            /**
             * Gunzip file if gzipped
             */
            $backupFileIsGzipped = substr($backupFile, -3, 3) == '.gz' ? true : false;
          
            if ($backupFileIsGzipped) {
                if (!$backupFile = $this->gunzipBackupFile()) {
                    throw new Exception("ERROR: couldn't gunzip backup file " . $backupDir . '/' . $backupFile);
                }
            }

            /**
            * Read backup file line by line
            */
            $handle = fopen($backupDir . '/' . $backupFile, "r");
            if ($handle) {
                while (($line = fgets($handle)) !== false) {
                    $line = ltrim(rtrim($line));
                    if (strlen($line) > 1) { // avoid blank lines
                        $lineIsComment = false;
                        if (preg_match('/^\/\*/', $line)) {
                            $multiLineComment = true;
                            $lineIsComment = true;
                        }
                        if ($multiLineComment or preg_match('/^\/\//', $line)) {
                            $lineIsComment = true;
                        }
                        if (!$lineIsComment) {
                            $sql .= $line;
                            if (preg_match('/;$/', $line)) {
                                
                                mysqli_query($this->conn, "SET sql_mode = ''");
                                // execute query
                                if(mysqli_query($this->conn, $sql)) {
                                    if (preg_match('/^CREATE TABLE `([^`]+)`/i', $sql, $tableName)) {
                                        $this->obfPrint("Table succesfully created: `" . $tableName[1] . "`");
                                    }
                                    $sql = '';
                                } else {
                                    throw new Exception("ERROR: SQL execution error: " . mysqli_error($this->conn));
                                }
                            }
                        } else if (preg_match('/\*\/$/', $line)) {
                            $multiLineComment = false;
                        }
                    }
                }
                fclose($handle);
            } else {
                throw new Exception("ERROR: couldn't open backup file " . $backupDir . '/' . $backupFile);
            } 
        } catch (Exception $e) {
            print_r($e->getMessage());
            return false;
        }

        if ($backupFileIsGzipped) {
            unlink($backupDir . '/' . $backupFile);
        }
        return true;
    }

    /*
     * Gunzip backup file
     *
     * @return string New filename (without .gz appended and without backup directory) if success, or false if operation fails
     */
    protected function gunzipBackupFile() {
        // Raising this value may increase performance
        $bufferSize = 4096; // read 4kb at a time
        $error = false;

        $source = $this->backupDir . '/' . $this->backupFile;
        $dest = $this->backupDir . '/' . date("Ymd_His", time()) . '_' . substr($this->backupFile, 0, -3);

        $this->obfPrint('Gunzipping backup file ' . $source . '... ', 1, 1);

        // Remove $dest file if exists
        if (file_exists($dest)) {
            if (!unlink($dest)) {
                return false;
            }
        }
        
        // Open gzipped and destination files in binary mode
        if (!$srcFile = gzopen($this->backupDir . '/' . $this->backupFile, 'rb')) {
            return false;
        }
        if (!$dstFile = fopen($dest, 'wb')) {
            return false;
        }

        while (!gzeof($srcFile)) {
            // Read buffer-size bytes
            // Both fwrite and gzread are binary-safe
            if(!fwrite($dstFile, gzread($srcFile, $bufferSize))) {
                return false;
            }
        }

        fclose($dstFile);
        gzclose($srcFile);

        // Return backup filename excluding backup directory
        return str_replace($this->backupDir . '/', '', $dest);
    }

    /**
     * Prints message forcing output buffer flush
     *
     */
    public function obfPrint ($msg = '', $lineBreaksBefore = 0, $lineBreaksAfter = 1) {
        if (!$msg) {
            return false;
        }

        $msg = date("Y-m-d H:i:s") . ' - ' . $msg;
        $output = '';

        if (php_sapi_name() != "cli") {
            $lineBreak = "<br />";
        } else {
            $lineBreak = "\n";
        }

        if ($lineBreaksBefore > 0) {
            for ($i = 1; $i <= $lineBreaksBefore; $i++) {
                $output .= $lineBreak;
            }                
        }

        $output .= $msg;

        if ($lineBreaksAfter > 0) {
            for ($i = 1; $i <= $lineBreaksAfter; $i++) {
                $output .= $lineBreak;
            }                
        }

        if (php_sapi_name() == "cli") {
            $output .= "\n";
        }

        if (php_sapi_name() != "cli") {
            ob_flush();
        }

        flush();
    }
}
ActionScheduler_Exception.php000066600000000317151137657220012365 0ustar00<?php

/**
 * ActionScheduler Exception Interface.
 *
 * Facilitates catching Exceptions unique to Action Scheduler.
 *
 * @package ActionScheduler
 * @since 2.1.0
 */
interface ActionScheduler_Exception {}
ActionScheduler_Versions.php000066600000007152151137657220012243 0ustar00<?php

/**
 * Class ActionScheduler_Versions
 */
class ActionScheduler_Versions {
	/**
	 * ActionScheduler_Versions instance.
	 *
	 * @var ActionScheduler_Versions
	 */
	private static $instance = null;

	/**
	 * Versions.
	 *
	 * @var array<string, callable>
	 */
	private $versions = array();

	/**
	 * Registered sources.
	 *
	 * @var array<string, string>
	 */
	private $sources = array();

	/**
	 * Register version's callback.
	 *
	 * @param string   $version_string          Action Scheduler version.
	 * @param callable $initialization_callback Callback to initialize the version.
	 */
	public function register( $version_string, $initialization_callback ) {
		if ( isset( $this->versions[ $version_string ] ) ) {
			return false;
		}

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
		$backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS );
		$source    = $backtrace[0]['file'];

		$this->versions[ $version_string ] = $initialization_callback;
		$this->sources[ $source ]          = $version_string;
		return true;
	}

	/**
	 * Get all versions.
	 */
	public function get_versions() {
		return $this->versions;
	}

	/**
	 * Get registered sources.
	 *
	 * Use with caution: this method is only available as of Action Scheduler's 3.9.1
	 * release and, owing to the way Action Scheduler is loaded, it's possible that the
	 * class definition used at runtime will belong to an earlier version.
	 *
	 * @since 3.9.1
	 *
	 * @return array<string, string>
	 */
	public function get_sources() {
		return $this->sources;
	}

	/**
	 * Get latest version registered.
	 */
	public function latest_version() {
		$keys = array_keys( $this->versions );
		if ( empty( $keys ) ) {
			return false;
		}
		uasort( $keys, 'version_compare' );
		return end( $keys );
	}

	/**
	 * Get callback for latest registered version.
	 */
	public function latest_version_callback() {
		$latest = $this->latest_version();

		if ( empty( $latest ) || ! isset( $this->versions[ $latest ] ) ) {
			return '__return_null';
		}

		return $this->versions[ $latest ];
	}

	/**
	 * Get instance.
	 *
	 * @return ActionScheduler_Versions
	 * @codeCoverageIgnore
	 */
	public static function instance() {
		if ( empty( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Initialize.
	 *
	 * @codeCoverageIgnore
	 */
	public static function initialize_latest_version() {
		$self = self::instance();
		call_user_func( $self->latest_version_callback() );
	}

	/**
	 * Returns information about the plugin or theme which contains the current active version
	 * of Action Scheduler.
	 *
	 * If this cannot be determined, or if Action Scheduler is being loaded via some other
	 * method, then it will return an empty array. Otherwise, if populated, the array will
	 * look like the following:
	 *
	 *     [
	 *         'type' => 'plugin', # or 'theme'
	 *         'name' => 'Name',
	 *     ]
	 *
	 * @deprecated 3.9.2 Use ActionScheduler_SystemInformation::active_source().
	 *
	 * @return array
	 */
	public function active_source(): array {
		_deprecated_function( __METHOD__, '3.9.2', 'ActionScheduler_SystemInformation::active_source()' );
		return ActionScheduler_SystemInformation::active_source();
	}

	/**
	 * Returns the directory path for the currently active installation of Action Scheduler.
	 *
	 * @deprecated 3.9.2 Use ActionScheduler_SystemInformation::active_source_path().
	 *
	 * @return string
	 */
	public function active_source_path(): string {
		_deprecated_function( __METHOD__, '3.9.2', 'ActionScheduler_SystemInformation::active_source_path()' );
		return ActionScheduler_SystemInformation::active_source_path();
	}
}
ActionScheduler_SystemInformation.php000066600000004701151137657220014122 0ustar00<?php

/**
 * Provides information about active and registered instances of Action Scheduler.
 */
class ActionScheduler_SystemInformation {
	/**
	 * Returns information about the plugin or theme which contains the current active version
	 * of Action Scheduler.
	 *
	 * If this cannot be determined, or if Action Scheduler is being loaded via some other
	 * method, then it will return an empty array. Otherwise, if populated, the array will
	 * look like the following:
	 *
	 *     [
	 *         'type' => 'plugin', # or 'theme'
	 *         'name' => 'Name',
	 *     ]
	 *
	 * @return array
	 */
	public static function active_source(): array {
		$plugins      = get_plugins();
		$plugin_files = array_keys( $plugins );

		foreach ( $plugin_files as $plugin_file ) {
			$plugin_path = trailingslashit( WP_PLUGIN_DIR ) . dirname( $plugin_file );
			$plugin_file = trailingslashit( WP_PLUGIN_DIR ) . $plugin_file;

			if ( 0 !== strpos( dirname( __DIR__ ), $plugin_path ) ) {
				continue;
			}

			$plugin_data = get_plugin_data( $plugin_file );

			if ( ! is_array( $plugin_data ) || empty( $plugin_data['Name'] ) ) {
				continue;
			}

			return array(
				'type' => 'plugin',
				'name' => $plugin_data['Name'],
			);
		}

		$themes = (array) search_theme_directories();

		foreach ( $themes as $slug => $data ) {
			$needle = trailingslashit( $data['theme_root'] ) . $slug . '/';

			if ( 0 !== strpos( __FILE__, $needle ) ) {
				continue;
			}

			$theme = wp_get_theme( $slug );

			if ( ! is_object( $theme ) || ! is_a( $theme, \WP_Theme::class ) ) {
				continue;
			}

			return array(
				'type' => 'theme',
				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
				'name' => $theme->Name,
			);
		}

		return array();
	}

	/**
	 * Returns the directory path for the currently active installation of Action Scheduler.
	 *
	 * @return string
	 */
	public static function active_source_path(): string {
		return trailingslashit( dirname( __DIR__ ) );
	}

	/**
	 * Get registered sources.
	 *
	 * It is not always possible to obtain this information. For instance, if earlier versions (<=3.9.0) of
	 * Action Scheduler register themselves first, then the necessary data about registered sources will
	 * not be available.
	 *
	 * @return array<string, string>
	 */
	public static function get_sources() {
		$versions = ActionScheduler_Versions::instance();
		return method_exists( $versions, 'get_sources' ) ? $versions->get_sources() : array();
	}
}
ActionScheduler_LogEntry.php000066600000003626151137657220012200 0ustar00<?php

/**
 * Class ActionScheduler_LogEntry
 */
class ActionScheduler_LogEntry {

	/**
	 * Action's ID for log entry.
	 *
	 * @var int $action_id
	 */
	protected $action_id = '';

	/**
	 * Log entry's message.
	 *
	 * @var string $message
	 */
	protected $message = '';

	/**
	 * Log entry's date.
	 *
	 * @var Datetime $date
	 */
	protected $date;

	/**
	 * Constructor
	 *
	 * @param mixed    $action_id Action ID.
	 * @param string   $message   Message.
	 * @param Datetime $date      Datetime object with the time when this log entry was created. If this parameter is
	 *                            not provided a new Datetime object (with current time) will be created.
	 */
	public function __construct( $action_id, $message, $date = null ) {
		/*
		 * ActionScheduler_wpCommentLogger::get_entry() previously passed a 3rd param of $comment->comment_type
		 * to ActionScheduler_LogEntry::__construct(), goodness knows why, and the Follow-up Emails plugin
		 * hard-codes loading its own version of ActionScheduler_wpCommentLogger with that out-dated method,
		 * goodness knows why, so we need to guard against that here instead of using a DateTime type declaration
		 * for the constructor's 3rd param of $date and causing a fatal error with older versions of FUE.
		 */
		if ( null !== $date && ! is_a( $date, 'DateTime' ) ) {
			_doing_it_wrong( __METHOD__, 'The third parameter must be a valid DateTime instance, or null.', '2.0.0' );
			$date = null;
		}

		$this->action_id = $action_id;
		$this->message   = $message;
		$this->date      = $date ? $date : new Datetime();
	}

	/**
	 * Returns the date when this log entry was created
	 *
	 * @return Datetime
	 */
	public function get_date() {
		return $this->date;
	}

	/**
	 * Get action ID of log entry.
	 */
	public function get_action_id() {
		return $this->action_id;
	}

	/**
	 * Get log entry message.
	 */
	public function get_message() {
		return $this->message;
	}
}

ActionScheduler_Compatibility.php000066600000007500151137657220013241 0ustar00<?php

/**
 * Class ActionScheduler_Compatibility
 */
class ActionScheduler_Compatibility {
	/**
	 * Converts a shorthand byte value to an integer byte value.
	 *
	 * Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php
	 *
	 * @link https://secure.php.net/manual/en/function.ini-get.php
	 * @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
	 *
	 * @param string $value A (PHP ini) byte value, either shorthand or ordinary.
	 * @return int An integer byte value.
	 */
	public static function convert_hr_to_bytes( $value ) {
		if ( function_exists( 'wp_convert_hr_to_bytes' ) ) {
			return wp_convert_hr_to_bytes( $value );
		}

		$value = strtolower( trim( $value ) );
		$bytes = (int) $value;

		if ( false !== strpos( $value, 'g' ) ) {
			$bytes *= GB_IN_BYTES;
		} elseif ( false !== strpos( $value, 'm' ) ) {
			$bytes *= MB_IN_BYTES;
		} elseif ( false !== strpos( $value, 'k' ) ) {
			$bytes *= KB_IN_BYTES;
		}

		// Deal with large (float) values which run into the maximum integer size.
		return min( $bytes, PHP_INT_MAX );
	}

	/**
	 * Attempts to raise the PHP memory limit for memory intensive processes.
	 *
	 * Only allows raising the existing limit and prevents lowering it.
	 *
	 * Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0
	 *
	 * @return bool|int|string The limit that was set or false on failure.
	 */
	public static function raise_memory_limit() {
		if ( function_exists( 'wp_raise_memory_limit' ) ) {
			return wp_raise_memory_limit( 'admin' );
		}

		$current_limit     = @ini_get( 'memory_limit' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
		$current_limit_int = self::convert_hr_to_bytes( $current_limit );

		if ( -1 === $current_limit_int ) {
			return false;
		}

		$wp_max_limit       = WP_MAX_MEMORY_LIMIT;
		$wp_max_limit_int   = self::convert_hr_to_bytes( $wp_max_limit );
		$filtered_limit     = apply_filters( 'admin_memory_limit', $wp_max_limit );
		$filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit );

		// phpcs:disable WordPress.PHP.IniSet.memory_limit_Blacklisted
		// phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged

		if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
			if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) {
				return $filtered_limit;
			} else {
				return false;
			}
		} elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
			if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) {
				return $wp_max_limit;
			} else {
				return false;
			}
		}

		// phpcs:enable

		return false;
	}

	/**
	 * Attempts to raise the PHP timeout for time intensive processes.
	 *
	 * Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available.
	 *
	 * @param int $limit The time limit in seconds.
	 */
	public static function raise_time_limit( $limit = 0 ) {
		$limit              = (int) $limit;
		$max_execution_time = (int) ini_get( 'max_execution_time' );

		// If the max execution time is already set to zero (unlimited), there is no reason to make a further change.
		if ( 0 === $max_execution_time ) {
			return;
		}

		// Whichever of $max_execution_time or $limit is higher is the amount by which we raise the time limit.
		$raise_by = 0 === $limit || $limit > $max_execution_time ? $limit : $max_execution_time;

		if ( function_exists( 'wc_set_time_limit' ) ) {
			wc_set_time_limit( $raise_by );
		} elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved
			@set_time_limit( $raise_by ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
		}
	}
}
migration/LogMigrator.php000066600000002441151137657220011512 0ustar00<?php


namespace Action_Scheduler\Migration;

use ActionScheduler_Logger;

/**
 * Class LogMigrator
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class LogMigrator {
	/**
	 * Source logger instance.
	 *
	 * @var ActionScheduler_Logger
	 */
	private $source;

	/**
	 * Destination logger instance.
	 *
	 * @var ActionScheduler_Logger
	 */
	private $destination;

	/**
	 * ActionMigrator constructor.
	 *
	 * @param ActionScheduler_Logger $source_logger Source logger object.
	 * @param ActionScheduler_Logger $destination_logger Destination logger object.
	 */
	public function __construct( ActionScheduler_Logger $source_logger, ActionScheduler_Logger $destination_logger ) {
		$this->source      = $source_logger;
		$this->destination = $destination_logger;
	}

	/**
	 * Migrate an action log.
	 *
	 * @param int $source_action_id Source logger object.
	 * @param int $destination_action_id Destination logger object.
	 */
	public function migrate( $source_action_id, $destination_action_id ) {
		$logs = $this->source->get_logs( $source_action_id );

		foreach ( $logs as $log ) {
			if ( absint( $log->get_action_id() ) === absint( $source_action_id ) ) {
				$this->destination->log( $destination_action_id, $log->get_message(), $log->get_date() );
			}
		}
	}
}
migration/ActionMigrator.php000066600000010253151137657220012206 0ustar00<?php


namespace Action_Scheduler\Migration;

/**
 * Class ActionMigrator
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class ActionMigrator {
	/**
	 * Source store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $source;

	/**
	 * Destination store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $destination;

	/**
	 * LogMigrator instance.
	 *
	 * @var LogMigrator
	 */
	private $log_migrator;

	/**
	 * ActionMigrator constructor.
	 *
	 * @param \ActionScheduler_Store $source_store Source store object.
	 * @param \ActionScheduler_Store $destination_store Destination store object.
	 * @param LogMigrator            $log_migrator Log migrator object.
	 */
	public function __construct( \ActionScheduler_Store $source_store, \ActionScheduler_Store $destination_store, LogMigrator $log_migrator ) {
		$this->source       = $source_store;
		$this->destination  = $destination_store;
		$this->log_migrator = $log_migrator;
	}

	/**
	 * Migrate an action.
	 *
	 * @param int $source_action_id Action ID.
	 *
	 * @return int 0|new action ID
	 * @throws \RuntimeException When unable to delete action from the source store.
	 */
	public function migrate( $source_action_id ) {
		try {
			$action = $this->source->fetch_action( $source_action_id );
			$status = $this->source->get_status( $source_action_id );
		} catch ( \Exception $e ) {
			$action = null;
			$status = '';
		}

		if ( is_null( $action ) || empty( $status ) || ! $action->get_schedule()->get_date() ) {
			// null action or empty status means the fetch operation failed or the action didn't exist.
			// null schedule means it's missing vital data.
			// delete it and move on.
			try {
				$this->source->delete_action( $source_action_id );
			} catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
				// nothing to do, it didn't exist in the first place.
			}
			do_action( 'action_scheduler/no_action_to_migrate', $source_action_id, $this->source, $this->destination ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

			return 0;
		}

		try {

			// Make sure the last attempt date is set correctly for completed and failed actions.
			$last_attempt_date = ( \ActionScheduler_Store::STATUS_PENDING !== $status ) ? $this->source->get_date( $source_action_id ) : null;

			$destination_action_id = $this->destination->save_action( $action, null, $last_attempt_date );
		} catch ( \Exception $e ) {
			do_action( 'action_scheduler/migrate_action_failed', $source_action_id, $this->source, $this->destination ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

			return 0; // could not save the action in the new store.
		}

		try {
			switch ( $status ) {
				case \ActionScheduler_Store::STATUS_FAILED:
					$this->destination->mark_failure( $destination_action_id );
					break;
				case \ActionScheduler_Store::STATUS_CANCELED:
					$this->destination->cancel_action( $destination_action_id );
					break;
			}

			$this->log_migrator->migrate( $source_action_id, $destination_action_id );
			$this->source->delete_action( $source_action_id );

			$test_action = $this->source->fetch_action( $source_action_id );
			if ( ! is_a( $test_action, 'ActionScheduler_NullAction' ) ) {
				// translators: %s is an action ID.
				throw new \RuntimeException( sprintf( __( 'Unable to remove source migrated action %s', 'action-scheduler' ), $source_action_id ) );
			}
			do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

			return $destination_action_id;
		} catch ( \Exception $e ) {
			// could not delete from the old store.
			$this->source->mark_migrated( $source_action_id );

			// phpcs:disable WordPress.NamingConventions.ValidHookName.UseUnderscores
			do_action( 'action_scheduler/migrate_action_incomplete', $source_action_id, $destination_action_id, $this->source, $this->destination );
			do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination );
			// phpcs:enable

			return $destination_action_id;
		}
	}
}
migration/BatchFetcher.php000066600000003350151137657220011606 0ustar00<?php

namespace Action_Scheduler\Migration;

use ActionScheduler_Store as Store;

/**
 * Class BatchFetcher
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class BatchFetcher {
	/**
	 * Store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $store;

	/**
	 * BatchFetcher constructor.
	 *
	 * @param ActionScheduler_Store $source_store Source store object.
	 */
	public function __construct( Store $source_store ) {
		$this->store = $source_store;
	}

	/**
	 * Retrieve a list of actions.
	 *
	 * @param int $count The number of actions to retrieve.
	 *
	 * @return int[] A list of action IDs
	 */
	public function fetch( $count = 10 ) {
		foreach ( $this->get_query_strategies( $count ) as $query ) {
			$action_ids = $this->store->query_actions( $query );
			if ( ! empty( $action_ids ) ) {
				return $action_ids;
			}
		}

		return array();
	}

	/**
	 * Generate a list of prioritized of action search parameters.
	 *
	 * @param int $count Number of actions to find.
	 *
	 * @return array
	 */
	private function get_query_strategies( $count ) {
		$now  = as_get_datetime_object();
		$args = array(
			'date'     => $now,
			'per_page' => $count,
			'offset'   => 0,
			'orderby'  => 'date',
			'order'    => 'ASC',
		);

		$priorities = array(
			Store::STATUS_PENDING,
			Store::STATUS_FAILED,
			Store::STATUS_CANCELED,
			Store::STATUS_COMPLETE,
			Store::STATUS_RUNNING,
			'', // any other unanticipated status.
		);

		foreach ( $priorities as $status ) {
			yield wp_parse_args(
				array(
					'status'       => $status,
					'date_compare' => '<=',
				),
				$args
			);

			yield wp_parse_args(
				array(
					'status'       => $status,
					'date_compare' => '>=',
				),
				$args
			);
		}
	}
}
migration/Runner.php000066600000010174151137657220010537 0ustar00<?php


namespace Action_Scheduler\Migration;

/**
 * Class Runner
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class Runner {
	/**
	 * Source store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $source_store;

	/**
	 * Destination store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $destination_store;

	/**
	 * Source logger instance.
	 *
	 * @var ActionScheduler_Logger
	 */
	private $source_logger;

	/**
	 * Destination logger instance.
	 *
	 * @var ActionScheduler_Logger
	 */
	private $destination_logger;

	/**
	 * Batch fetcher instance.
	 *
	 * @var BatchFetcher
	 */
	private $batch_fetcher;

	/**
	 * Action migrator instance.
	 *
	 * @var ActionMigrator
	 */
	private $action_migrator;

	/**
	 * Log migrator instance.
	 *
	 * @var LogMigrator
	 */
	private $log_migrator;

	/**
	 * Progress bar instance.
	 *
	 * @var ProgressBar
	 */
	private $progress_bar;

	/**
	 * Runner constructor.
	 *
	 * @param Config $config Migration configuration object.
	 */
	public function __construct( Config $config ) {
		$this->source_store       = $config->get_source_store();
		$this->destination_store  = $config->get_destination_store();
		$this->source_logger      = $config->get_source_logger();
		$this->destination_logger = $config->get_destination_logger();

		$this->batch_fetcher = new BatchFetcher( $this->source_store );
		if ( $config->get_dry_run() ) {
			$this->log_migrator    = new DryRun_LogMigrator( $this->source_logger, $this->destination_logger );
			$this->action_migrator = new DryRun_ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator );
		} else {
			$this->log_migrator    = new LogMigrator( $this->source_logger, $this->destination_logger );
			$this->action_migrator = new ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator );
		}

		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			$this->progress_bar = $config->get_progress_bar();
		}
	}

	/**
	 * Run migration batch.
	 *
	 * @param int $batch_size Optional batch size. Default 10.
	 *
	 * @return int Size of batch processed.
	 */
	public function run( $batch_size = 10 ) {
		$batch      = $this->batch_fetcher->fetch( $batch_size );
		$batch_size = count( $batch );

		if ( ! $batch_size ) {
			return 0;
		}

		if ( $this->progress_bar ) {
			/* translators: %d: amount of actions */
			$this->progress_bar->set_message( sprintf( _n( 'Migrating %d action', 'Migrating %d actions', $batch_size, 'action-scheduler' ), $batch_size ) );
			$this->progress_bar->set_count( $batch_size );
		}

		$this->migrate_actions( $batch );

		return $batch_size;
	}

	/**
	 * Migration a batch of actions.
	 *
	 * @param array $action_ids List of action IDs to migrate.
	 */
	public function migrate_actions( array $action_ids ) {
		do_action( 'action_scheduler/migration_batch_starting', $action_ids ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

		\ActionScheduler::logger()->unhook_stored_action();
		$this->destination_logger->unhook_stored_action();

		foreach ( $action_ids as $source_action_id ) {
			$destination_action_id = $this->action_migrator->migrate( $source_action_id );
			if ( $destination_action_id ) {
				$this->destination_logger->log(
					$destination_action_id,
					sprintf(
						/* translators: 1: source action ID 2: source store class 3: destination action ID 4: destination store class */
						__( 'Migrated action with ID %1$d in %2$s to ID %3$d in %4$s', 'action-scheduler' ),
						$source_action_id,
						get_class( $this->source_store ),
						$destination_action_id,
						get_class( $this->destination_store )
					)
				);
			}

			if ( $this->progress_bar ) {
				$this->progress_bar->tick();
			}
		}

		if ( $this->progress_bar ) {
			$this->progress_bar->finish();
		}

		\ActionScheduler::logger()->hook_stored_action();

		do_action( 'action_scheduler/migration_batch_complete', $action_ids ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	/**
	 * Initialize destination store and logger.
	 */
	public function init_destination() {
		$this->destination_store->init();
		$this->destination_logger->init();
	}
}
migration/Controller.php000066600000014574151137657220011421 0ustar00<?php

namespace Action_Scheduler\Migration;

use ActionScheduler_DataController;
use ActionScheduler_LoggerSchema;
use ActionScheduler_StoreSchema;
use Action_Scheduler\WP_CLI\ProgressBar;

/**
 * Class Controller
 *
 * The main plugin/initialization class for migration to custom tables.
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class Controller {
	/**
	 * Instance.
	 *
	 * @var self
	 */
	private static $instance;

	/**
	 * Scheduler instance.
	 *
	 * @var Action_Scheduler\Migration\Scheduler
	 */
	private $migration_scheduler;

	/**
	 * Class name of the store object.
	 *
	 * @var string
	 */
	private $store_classname;

	/**
	 * Class name of the logger object.
	 *
	 * @var string
	 */
	private $logger_classname;

	/**
	 * Flag to indicate migrating custom store.
	 *
	 * @var bool
	 */
	private $migrate_custom_store;

	/**
	 * Controller constructor.
	 *
	 * @param Scheduler $migration_scheduler Migration scheduler object.
	 */
	protected function __construct( Scheduler $migration_scheduler ) {
		$this->migration_scheduler = $migration_scheduler;
		$this->store_classname     = '';
	}

	/**
	 * Set the action store class name.
	 *
	 * @param string $class Classname of the store class.
	 *
	 * @return string
	 */
	public function get_store_class( $class ) {
		if ( \ActionScheduler_DataController::is_migration_complete() ) {
			return \ActionScheduler_DataController::DATASTORE_CLASS;
		} elseif ( \ActionScheduler_Store::DEFAULT_CLASS !== $class ) {
			$this->store_classname = $class;
			return $class;
		} else {
			return 'ActionScheduler_HybridStore';
		}
	}

	/**
	 * Set the action logger class name.
	 *
	 * @param string $class Classname of the logger class.
	 *
	 * @return string
	 */
	public function get_logger_class( $class ) {
		\ActionScheduler_Store::instance();

		if ( $this->has_custom_datastore() ) {
			$this->logger_classname = $class;
			return $class;
		} else {
			return \ActionScheduler_DataController::LOGGER_CLASS;
		}
	}

	/**
	 * Get flag indicating whether a custom datastore is in use.
	 *
	 * @return bool
	 */
	public function has_custom_datastore() {
		return (bool) $this->store_classname;
	}

	/**
	 * Set up the background migration process.
	 *
	 * @return void
	 */
	public function schedule_migration() {
		$logging_tables = new ActionScheduler_LoggerSchema();
		$store_tables   = new ActionScheduler_StoreSchema();

		/*
		 * In some unusual cases, the expected tables may not have been created. In such cases
		 * we do not schedule a migration as doing so will lead to fatal error conditions.
		 *
		 * In such cases the user will likely visit the Tools > Scheduled Actions screen to
		 * investigate, and will see appropriate messaging (this step also triggers an attempt
		 * to rebuild any missing tables).
		 *
		 * @see https://github.com/woocommerce/action-scheduler/issues/653
		 */
		if (
			ActionScheduler_DataController::is_migration_complete()
			|| $this->migration_scheduler->is_migration_scheduled()
			|| ! $store_tables->tables_exist()
			|| ! $logging_tables->tables_exist()
		) {
			return;
		}

		$this->migration_scheduler->schedule_migration();
	}

	/**
	 * Get the default migration config object
	 *
	 * @return ActionScheduler\Migration\Config
	 */
	public function get_migration_config_object() {
		static $config = null;

		if ( ! $config ) {
			$source_store  = $this->store_classname ? new $this->store_classname() : new \ActionScheduler_wpPostStore();
			$source_logger = $this->logger_classname ? new $this->logger_classname() : new \ActionScheduler_wpCommentLogger();

			$config = new Config();
			$config->set_source_store( $source_store );
			$config->set_source_logger( $source_logger );
			$config->set_destination_store( new \ActionScheduler_DBStoreMigrator() );
			$config->set_destination_logger( new \ActionScheduler_DBLogger() );

			if ( defined( 'WP_CLI' ) && WP_CLI ) {
				$config->set_progress_bar( new ProgressBar( '', 0 ) );
			}
		}

		return apply_filters( 'action_scheduler/migration_config', $config ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	/**
	 * Hook dashboard migration notice.
	 */
	public function hook_admin_notices() {
		if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) {
			return;
		}
		add_action( 'admin_notices', array( $this, 'display_migration_notice' ), 10, 0 );
	}

	/**
	 * Show a dashboard notice that migration is in progress.
	 */
	public function display_migration_notice() {
		printf( '<div class="notice notice-warning"><p>%s</p></div>', esc_html__( 'Action Scheduler migration in progress. The list of scheduled actions may be incomplete.', 'action-scheduler' ) );
	}

	/**
	 * Add store classes. Hook migration.
	 */
	private function hook() {
		add_filter( 'action_scheduler_store_class', array( $this, 'get_store_class' ), 100, 1 );
		add_filter( 'action_scheduler_logger_class', array( $this, 'get_logger_class' ), 100, 1 );
		add_action( 'init', array( $this, 'maybe_hook_migration' ) );
		add_action( 'wp_loaded', array( $this, 'schedule_migration' ) );

		// Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen.
		add_action( 'load-tools_page_action-scheduler', array( $this, 'hook_admin_notices' ), 10, 0 );
		add_action( 'load-woocommerce_page_wc-status', array( $this, 'hook_admin_notices' ), 10, 0 );
	}

	/**
	 * Possibly hook the migration scheduler action.
	 */
	public function maybe_hook_migration() {
		if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) {
			return;
		}

		$this->migration_scheduler->hook();
	}

	/**
	 * Allow datastores to enable migration to AS tables.
	 */
	public function allow_migration() {
		if ( ! \ActionScheduler_DataController::dependencies_met() ) {
			return false;
		}

		if ( null === $this->migrate_custom_store ) {
			$this->migrate_custom_store = apply_filters( 'action_scheduler_migrate_data_store', false );
		}

		return ( ! $this->has_custom_datastore() ) || $this->migrate_custom_store;
	}

	/**
	 * Proceed with the migration if the dependencies have been met.
	 */
	public static function init() {
		if ( \ActionScheduler_DataController::dependencies_met() ) {
			self::instance()->hook();
		}
	}

	/**
	 * Singleton factory.
	 */
	public static function instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new static( new Scheduler() );
		}

		return self::$instance;
	}
}
migration/DryRun_LogMigrator.php000066600000000713151137657220013015 0ustar00<?php


namespace Action_Scheduler\Migration;

/**
 * Class DryRun_LogMigrator
 *
 * @package Action_Scheduler\Migration
 *
 * @codeCoverageIgnore
 */
class DryRun_LogMigrator extends LogMigrator {
	/**
	 * Simulate migrating an action log.
	 *
	 * @param int $source_action_id Source logger object.
	 * @param int $destination_action_id Destination logger object.
	 */
	public function migrate( $source_action_id, $destination_action_id ) {
		// no-op.
	}
}
migration/Config.php000066600000010156151137657220010473 0ustar00<?php


namespace Action_Scheduler\Migration;

use Action_Scheduler\WP_CLI\ProgressBar;
use ActionScheduler_Logger as Logger;
use ActionScheduler_Store as Store;

/**
 * Class Config
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * A config builder for the ActionScheduler\Migration\Runner class
 */
class Config {
	/**
	 * Source store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $source_store;

	/**
	 * Source logger instance.
	 *
	 * @var ActionScheduler_Logger
	 */
	private $source_logger;

	/**
	 * Destination store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $destination_store;

	/**
	 * Destination logger instance.
	 *
	 * @var ActionScheduler_Logger
	 */
	private $destination_logger;

	/**
	 * Progress bar object.
	 *
	 * @var Action_Scheduler\WP_CLI\ProgressBar
	 */
	private $progress_bar;

	/**
	 * Flag indicating a dryrun.
	 *
	 * @var bool
	 */
	private $dry_run = false;

	/**
	 * Config constructor.
	 */
	public function __construct() {

	}

	/**
	 * Get the configured source store.
	 *
	 * @return ActionScheduler_Store
	 * @throws \RuntimeException When source store is not configured.
	 */
	public function get_source_store() {
		if ( empty( $this->source_store ) ) {
			throw new \RuntimeException( __( 'Source store must be configured before running a migration', 'action-scheduler' ) );
		}

		return $this->source_store;
	}

	/**
	 * Set the configured source store.
	 *
	 * @param ActionScheduler_Store $store Source store object.
	 */
	public function set_source_store( Store $store ) {
		$this->source_store = $store;
	}

	/**
	 * Get the configured source logger.
	 *
	 * @return ActionScheduler_Logger
	 * @throws \RuntimeException When source logger is not configured.
	 */
	public function get_source_logger() {
		if ( empty( $this->source_logger ) ) {
			throw new \RuntimeException( __( 'Source logger must be configured before running a migration', 'action-scheduler' ) );
		}

		return $this->source_logger;
	}

	/**
	 * Set the configured source logger.
	 *
	 * @param ActionScheduler_Logger $logger Logger object.
	 */
	public function set_source_logger( Logger $logger ) {
		$this->source_logger = $logger;
	}

	/**
	 * Get the configured destination store.
	 *
	 * @return ActionScheduler_Store
	 * @throws \RuntimeException When destination store is not configured.
	 */
	public function get_destination_store() {
		if ( empty( $this->destination_store ) ) {
			throw new \RuntimeException( __( 'Destination store must be configured before running a migration', 'action-scheduler' ) );
		}

		return $this->destination_store;
	}

	/**
	 * Set the configured destination store.
	 *
	 * @param ActionScheduler_Store $store Action store object.
	 */
	public function set_destination_store( Store $store ) {
		$this->destination_store = $store;
	}

	/**
	 * Get the configured destination logger.
	 *
	 * @return ActionScheduler_Logger
	 * @throws \RuntimeException When destination logger is not configured.
	 */
	public function get_destination_logger() {
		if ( empty( $this->destination_logger ) ) {
			throw new \RuntimeException( __( 'Destination logger must be configured before running a migration', 'action-scheduler' ) );
		}

		return $this->destination_logger;
	}

	/**
	 * Set the configured destination logger.
	 *
	 * @param ActionScheduler_Logger $logger Logger object.
	 */
	public function set_destination_logger( Logger $logger ) {
		$this->destination_logger = $logger;
	}

	/**
	 * Get flag indicating whether it's a dry run.
	 *
	 * @return bool
	 */
	public function get_dry_run() {
		return $this->dry_run;
	}

	/**
	 * Set flag indicating whether it's a dry run.
	 *
	 * @param bool $dry_run Dry run toggle.
	 */
	public function set_dry_run( $dry_run ) {
		$this->dry_run = (bool) $dry_run;
	}

	/**
	 * Get progress bar object.
	 *
	 * @return ActionScheduler\WPCLI\ProgressBar
	 */
	public function get_progress_bar() {
		return $this->progress_bar;
	}

	/**
	 * Set progress bar object.
	 *
	 * @param ActionScheduler\WPCLI\ProgressBar $progress_bar Progress bar object.
	 */
	public function set_progress_bar( ProgressBar $progress_bar ) {
		$this->progress_bar = $progress_bar;
	}
}
migration/Scheduler.php000066600000006050151137657220011202 0ustar00<?php


namespace Action_Scheduler\Migration;

/**
 * Class Scheduler
 *
 * @package Action_Scheduler\WP_CLI
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class Scheduler {
	/** Migration action hook. */
	const HOOK = 'action_scheduler/migration_hook';

	/** Migration action group. */
	const GROUP = 'action-scheduler-migration';

	/**
	 * Set up the callback for the scheduled job.
	 */
	public function hook() {
		add_action( self::HOOK, array( $this, 'run_migration' ), 10, 0 );
	}

	/**
	 * Remove the callback for the scheduled job.
	 */
	public function unhook() {
		remove_action( self::HOOK, array( $this, 'run_migration' ), 10 );
	}

	/**
	 * The migration callback.
	 */
	public function run_migration() {
		$migration_runner = $this->get_migration_runner();
		$count            = $migration_runner->run( $this->get_batch_size() );

		if ( 0 === $count ) {
			$this->mark_complete();
		} else {
			$this->schedule_migration( time() + $this->get_schedule_interval() );
		}
	}

	/**
	 * Mark the migration complete.
	 */
	public function mark_complete() {
		$this->unschedule_migration();

		\ActionScheduler_DataController::mark_migration_complete();
		do_action( 'action_scheduler/migration_complete' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	/**
	 * Get a flag indicating whether the migration is scheduled.
	 *
	 * @return bool Whether there is a pending action in the store to handle the migration
	 */
	public function is_migration_scheduled() {
		$next = as_next_scheduled_action( self::HOOK );

		return ! empty( $next );
	}

	/**
	 * Schedule the migration.
	 *
	 * @param int $when Optional timestamp to run the next migration batch. Defaults to now.
	 *
	 * @return string The action ID
	 */
	public function schedule_migration( $when = 0 ) {
		$next = as_next_scheduled_action( self::HOOK );

		if ( ! empty( $next ) ) {
			return $next;
		}

		if ( empty( $when ) ) {
			$when = time() + MINUTE_IN_SECONDS;
		}

		return as_schedule_single_action( $when, self::HOOK, array(), self::GROUP );
	}

	/**
	 * Remove the scheduled migration action.
	 */
	public function unschedule_migration() {
		as_unschedule_action( self::HOOK, null, self::GROUP );
	}

	/**
	 * Get migration batch schedule interval.
	 *
	 * @return int Seconds between migration runs. Defaults to 0 seconds to allow chaining migration via Async Runners.
	 */
	private function get_schedule_interval() {
		return (int) apply_filters( 'action_scheduler/migration_interval', 0 ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	/**
	 * Get migration batch size.
	 *
	 * @return int Number of actions to migrate in each batch. Defaults to 250.
	 */
	private function get_batch_size() {
		return (int) apply_filters( 'action_scheduler/migration_batch_size', 250 ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	/**
	 * Get migration runner object.
	 *
	 * @return Runner
	 */
	private function get_migration_runner() {
		$config = Controller::instance()->get_migration_config_object();

		return new Runner( $config );
	}

}
migration/DryRun_ActionMigrator.php000066600000001052151137657220013506 0ustar00<?php


namespace Action_Scheduler\Migration;

/**
 * Class DryRun_ActionMigrator
 *
 * @package Action_Scheduler\Migration
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class DryRun_ActionMigrator extends ActionMigrator {
	/**
	 * Simulate migrating an action.
	 *
	 * @param int $source_action_id Action ID.
	 *
	 * @return int
	 */
	public function migrate( $source_action_id ) {
		do_action( 'action_scheduler/migrate_action_dry_run', $source_action_id ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

		return 0;
	}
}
migration/ActionScheduler_DBStoreMigrator.php000066600000003453151137657220015433 0ustar00<?php

/**
 * Class ActionScheduler_DBStoreMigrator
 *
 * A class for direct saving of actions to the table data store during migration.
 *
 * @since 3.0.0
 */
class ActionScheduler_DBStoreMigrator extends ActionScheduler_DBStore {

	/**
	 * Save an action with optional last attempt date.
	 *
	 * Normally, saving an action sets its attempted date to 0000-00-00 00:00:00 because when an action is first saved,
	 * it can't have been attempted yet, but migrated completed actions will have an attempted date, so we need to save
	 * that when first saving the action.
	 *
	 * @param ActionScheduler_Action $action Action to migrate.
	 * @param null|DateTime          $scheduled_date Optional date of the first instance to store.
	 * @param null|DateTime          $last_attempt_date Optional date the action was last attempted.
	 *
	 * @return string The action ID
	 * @throws \RuntimeException When the action is not saved.
	 */
	public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null, ?DateTime $last_attempt_date = null ) {
		try {
			/**
			 * Global.
			 *
			 * @var \wpdb $wpdb
			 */
			global $wpdb;

			$action_id = parent::save_action( $action, $scheduled_date );

			if ( null !== $last_attempt_date ) {
				$data = array(
					'last_attempt_gmt'   => $this->get_scheduled_date_string( $action, $last_attempt_date ),
					'last_attempt_local' => $this->get_scheduled_date_string_local( $action, $last_attempt_date ),
				);

				$wpdb->update( $wpdb->actionscheduler_actions, $data, array( 'action_id' => $action_id ), array( '%s', '%s' ), array( '%d' ) );
			}

			return $action_id;
		} catch ( \Exception $e ) {
			// translators: %s is an error message.
			throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
		}
	}
}
ActionScheduler_QueueRunner.php000066600000022770151137657220012714 0ustar00<?php

/**
 * Class ActionScheduler_QueueRunner
 */
class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
	const WP_CRON_HOOK = 'action_scheduler_run_queue';

	const WP_CRON_SCHEDULE = 'every_minute';

	/**
	 * ActionScheduler_AsyncRequest_QueueRunner instance.
	 *
	 * @var ActionScheduler_AsyncRequest_QueueRunner
	 */
	protected $async_request;

	/**
	 * ActionScheduler_QueueRunner instance.
	 *
	 * @var ActionScheduler_QueueRunner
	 */
	private static $runner = null;

	/**
	 * Number of processed actions.
	 *
	 * @var int
	 */
	private $processed_actions_count = 0;

	/**
	 * Get instance.
	 *
	 * @return ActionScheduler_QueueRunner
	 * @codeCoverageIgnore
	 */
	public static function instance() {
		if ( empty( self::$runner ) ) {
			$class        = apply_filters( 'action_scheduler_queue_runner_class', 'ActionScheduler_QueueRunner' );
			self::$runner = new $class();
		}

		return self::$runner;
	}

	/**
	 * ActionScheduler_QueueRunner constructor.
	 *
	 * @param ActionScheduler_Store|null                    $store Store object.
	 * @param ActionScheduler_FatalErrorMonitor|null        $monitor Monitor object.
	 * @param ActionScheduler_QueueCleaner|null             $cleaner Cleaner object.
	 * @param ActionScheduler_AsyncRequest_QueueRunner|null $async_request Async request runner object.
	 */
	public function __construct( ?ActionScheduler_Store $store = null, ?ActionScheduler_FatalErrorMonitor $monitor = null, ?ActionScheduler_QueueCleaner $cleaner = null, ?ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) {
		parent::__construct( $store, $monitor, $cleaner );

		if ( is_null( $async_request ) ) {
			$async_request = new ActionScheduler_AsyncRequest_QueueRunner( $this->store );
		}

		$this->async_request = $async_request;
	}

	/**
	 * Initialize.
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {

		add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval

		// Check for and remove any WP Cron hook scheduled by Action Scheduler < 3.0.0, which didn't include the $context param.
		$next_timestamp = wp_next_scheduled( self::WP_CRON_HOOK );
		if ( $next_timestamp ) {
			wp_unschedule_event( $next_timestamp, self::WP_CRON_HOOK );
		}

		$cron_context = array( 'WP Cron' );

		if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) {
			$schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE );
			wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context );
		}

		add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) );
		$this->hook_dispatch_async_request();
	}

	/**
	 * Hook check for dispatching an async request.
	 */
	public function hook_dispatch_async_request() {
		add_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
	}

	/**
	 * Unhook check for dispatching an async request.
	 */
	public function unhook_dispatch_async_request() {
		remove_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
	}

	/**
	 * Check if we should dispatch an async request to process actions.
	 *
	 * This method is attached to 'shutdown', so is called frequently. To avoid slowing down
	 * the site, it mitigates the work performed in each request by:
	 * 1. checking if it's in the admin context and then
	 * 2. haven't run on the 'shutdown' hook within the lock time (60 seconds by default)
	 * 3. haven't exceeded the number of allowed batches.
	 *
	 * The order of these checks is important, because they run from a check on a value:
	 * 1. in memory - is_admin() maps to $GLOBALS or the WP_ADMIN constant
	 * 2. in memory - transients use autoloaded options by default
	 * 3. from a database query - has_maximum_concurrent_batches() run the query
	 *    $this->store->get_claim_count() to find the current number of claims in the DB.
	 *
	 * If all of these conditions are met, then we request an async runner check whether it
	 * should dispatch a request to process pending actions.
	 */
	public function maybe_dispatch_async_request() {
		// Only start an async queue at most once every 60 seconds.
		if (
			is_admin()
			&& ! ActionScheduler::lock()->is_locked( 'async-request-runner' )
			&& ActionScheduler::lock()->set( 'async-request-runner' )
		) {
			$this->async_request->maybe_dispatch();
		}
	}

	/**
	 * Process actions in the queue. Attached to self::WP_CRON_HOOK i.e. 'action_scheduler_run_queue'
	 *
	 * The $context param of this method defaults to 'WP Cron', because prior to Action Scheduler 3.0.0
	 * that was the only context in which this method was run, and the self::WP_CRON_HOOK hook had no context
	 * passed along with it. New code calling this method directly, or by triggering the self::WP_CRON_HOOK,
	 * should set a context as the first parameter. For an example of this, refer to the code seen in
	 *
	 * @see ActionScheduler_AsyncRequest_QueueRunner::handle()
	 *
	 * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
	 *        Generally, this should be capitalised and not localised as it's a proper noun.
	 * @return int The number of actions processed.
	 */
	public function run( $context = 'WP Cron' ) {
		ActionScheduler_Compatibility::raise_memory_limit();
		ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() );
		do_action( 'action_scheduler_before_process_queue' );
		$this->run_cleanup();

		$this->processed_actions_count = 0;
		if ( false === $this->has_maximum_concurrent_batches() ) {
			do {
				$batch_size                     = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
				$processed_actions_in_batch     = $this->do_batch( $batch_size, $context );
				$this->processed_actions_count += $processed_actions_in_batch;
			} while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $this->processed_actions_count ) ); // keep going until we run out of actions, time, or memory.
		}

		do_action( 'action_scheduler_after_process_queue' );
		return $this->processed_actions_count;
	}

	/**
	 * Process a batch of actions pending in the queue.
	 *
	 * Actions are processed by claiming a set of pending actions then processing each one until either the batch
	 * size is completed, or memory or time limits are reached, defined by @see $this->batch_limits_exceeded().
	 *
	 * @param int    $size The maximum number of actions to process in the batch.
	 * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
	 *                        Generally, this should be capitalised and not localised as it's a proper noun.
	 * @return int The number of actions processed.
	 */
	protected function do_batch( $size = 100, $context = '' ) {
		$claim = $this->store->stake_claim( $size );
		$this->monitor->attach( $claim );
		$processed_actions = 0;

		foreach ( $claim->get_actions() as $action_id ) {
			// bail if we lost the claim.
			if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ), true ) ) {
				break;
			}
			$this->process_action( $action_id, $context );
			$processed_actions++;

			if ( $this->batch_limits_exceeded( $processed_actions + $this->processed_actions_count ) ) {
				break;
			}
		}
		$this->store->release_claim( $claim );
		$this->monitor->detach();
		$this->clear_caches();
		return $processed_actions;
	}

	/**
	 * Flush the cache if possible (intended for use after a batch of actions has been processed).
	 *
	 * This is useful because running large batches can eat up memory and because invalid data can accrue in the
	 * runtime cache, which may lead to unexpected results.
	 */
	protected function clear_caches() {
		/*
		 * Calling wp_cache_flush_runtime() lets us clear the runtime cache without invalidating the external object
		 * cache, so we will always prefer this method (as compared to calling wp_cache_flush()) when it is available.
		 *
		 * However, this function was only introduced in WordPress 6.0. Additionally, the preferred way of detecting if
		 * it is supported changed in WordPress 6.1 so we use two different methods to decide if we should utilize it.
		 */
		$flushing_runtime_cache_explicitly_supported = function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' );
		$flushing_runtime_cache_implicitly_supported = ! function_exists( 'wp_cache_supports' ) && function_exists( 'wp_cache_flush_runtime' );

		if ( $flushing_runtime_cache_explicitly_supported || $flushing_runtime_cache_implicitly_supported ) {
			wp_cache_flush_runtime();
		} elseif (
			! wp_using_ext_object_cache()
			/**
			 * When an external object cache is in use, and when wp_cache_flush_runtime() is not available, then
			 * normally the cache will not be flushed after processing a batch of actions (to avoid a performance
			 * penalty for other processes).
			 *
			 * This filter makes it possible to override this behavior and always flush the cache, even if an external
			 * object cache is in use.
			 *
			 * @since 1.0
			 *
			 * @param bool $flush_cache If the cache should be flushed.
			 */
			|| apply_filters( 'action_scheduler_queue_runner_flush_cache', false )
		) {
			wp_cache_flush();
		}
	}

	/**
	 * Add schedule to WP cron.
	 *
	 * @param array<string, array<string, int|string>> $schedules Schedules.
	 * @return array<string, array<string, int|string>>
	 */
	public function add_wp_cron_schedule( $schedules ) {
		$schedules['every_minute'] = array(
			'interval' => 60, // in seconds.
			'display'  => __( 'Every minute', 'action-scheduler' ),
		);

		return $schedules;
	}
}
ActionScheduler_ListTable.php000066600000052166151137657220012323 0ustar00<?php

/**
 * Implements the admin view of the actions.
 *
 * @codeCoverageIgnore
 */
class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {

	/**
	 * The package name.
	 *
	 * @var string
	 */
	protected $package = 'action-scheduler';

	/**
	 * Columns to show (name => label).
	 *
	 * @var array
	 */
	protected $columns = array();

	/**
	 * Actions (name => label).
	 *
	 * @var array
	 */
	protected $row_actions = array();

	/**
	 * The active data stores
	 *
	 * @var ActionScheduler_Store
	 */
	protected $store;

	/**
	 * A logger to use for getting action logs to display
	 *
	 * @var ActionScheduler_Logger
	 */
	protected $logger;

	/**
	 * A ActionScheduler_QueueRunner runner instance (or child class)
	 *
	 * @var ActionScheduler_QueueRunner
	 */
	protected $runner;

	/**
	 * Bulk actions. The key of the array is the method name of the implementation.
	 * Example: bulk_<key>(array $ids, string $sql_in).
	 *
	 * See the comments in the parent class for further details
	 *
	 * @var array
	 */
	protected $bulk_actions = array();

	/**
	 * Flag variable to render our notifications, if any, once.
	 *
	 * @var bool
	 */
	protected static $did_notification = false;

	/**
	 * Array of seconds for common time periods, like week or month, alongside an internationalised string representation, i.e. "Day" or "Days"
	 *
	 * @var array
	 */
	private static $time_periods;

	/**
	 * Sets the current data store object into `store->action` and initialises the object.
	 *
	 * @param ActionScheduler_Store       $store Store object.
	 * @param ActionScheduler_Logger      $logger Logger object.
	 * @param ActionScheduler_QueueRunner $runner Runner object.
	 */
	public function __construct( ActionScheduler_Store $store, ActionScheduler_Logger $logger, ActionScheduler_QueueRunner $runner ) {

		$this->store  = $store;
		$this->logger = $logger;
		$this->runner = $runner;

		$this->table_header = __( 'Scheduled Actions', 'action-scheduler' );

		$this->bulk_actions = array(
			'delete' => __( 'Delete', 'action-scheduler' ),
		);

		$this->columns = array(
			'hook'        => __( 'Hook', 'action-scheduler' ),
			'status'      => __( 'Status', 'action-scheduler' ),
			'args'        => __( 'Arguments', 'action-scheduler' ),
			'group'       => __( 'Group', 'action-scheduler' ),
			'recurrence'  => __( 'Recurrence', 'action-scheduler' ),
			'schedule'    => __( 'Scheduled Date', 'action-scheduler' ),
			'log_entries' => __( 'Log', 'action-scheduler' ),
		);

		$this->sort_by = array(
			'schedule',
			'hook',
			'group',
		);

		$this->search_by = array(
			'hook',
			'args',
			'claim_id',
		);

		$request_status = $this->get_request_status();

		if ( empty( $request_status ) ) {
			$this->sort_by[] = 'status';
		} elseif ( in_array( $request_status, array( 'in-progress', 'failed' ), true ) ) {
			$this->columns  += array( 'claim_id' => __( 'Claim ID', 'action-scheduler' ) );
			$this->sort_by[] = 'claim_id';
		}

		$this->row_actions = array(
			'hook' => array(
				'run'    => array(
					'name' => __( 'Run', 'action-scheduler' ),
					'desc' => __( 'Process the action now as if it were run as part of a queue', 'action-scheduler' ),
				),
				'cancel' => array(
					'name'  => __( 'Cancel', 'action-scheduler' ),
					'desc'  => __( 'Cancel the action now to avoid it being run in future', 'action-scheduler' ),
					'class' => 'cancel trash',
				),
			),
		);

		self::$time_periods = array(
			array(
				'seconds' => YEAR_IN_SECONDS,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s year', '%s years', 'action-scheduler' ),
			),
			array(
				'seconds' => MONTH_IN_SECONDS,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s month', '%s months', 'action-scheduler' ),
			),
			array(
				'seconds' => WEEK_IN_SECONDS,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
			),
			array(
				'seconds' => DAY_IN_SECONDS,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s day', '%s days', 'action-scheduler' ),
			),
			array(
				'seconds' => HOUR_IN_SECONDS,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
			),
			array(
				'seconds' => MINUTE_IN_SECONDS,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
			),
			array(
				'seconds' => 1,
				/* translators: %s: amount of time */
				'names'   => _n_noop( '%s second', '%s seconds', 'action-scheduler' ),
			),
		);

		parent::__construct(
			array(
				'singular' => 'action-scheduler',
				'plural'   => 'action-scheduler',
				'ajax'     => false,
			)
		);

		add_screen_option(
			'per_page',
			array(
				'default' => $this->items_per_page,
			)
		);

		add_filter( 'set_screen_option_' . $this->get_per_page_option_name(), array( $this, 'set_items_per_page_option' ), 10, 3 );
		set_screen_options();
	}

	/**
	 * Handles setting the items_per_page option for this screen.
	 *
	 * @param mixed  $status Default false (to skip saving the current option).
	 * @param string $option Screen option name.
	 * @param int    $value  Screen option value.
	 * @return int
	 */
	public function set_items_per_page_option( $status, $option, $value ) {
		return $value;
	}
	/**
	 * Convert an interval of seconds into a two part human friendly string.
	 *
	 * The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
	 * even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step
	 * further to display two degrees of accuracy.
	 *
	 * Inspired by the Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
	 *
	 * @param int $interval A interval in seconds.
	 * @param int $periods_to_include Depth of time periods to include, e.g. for an interval of 70, and $periods_to_include of 2, both minutes and seconds would be included. With a value of 1, only minutes would be included.
	 * @return string A human friendly string representation of the interval.
	 */
	private static function human_interval( $interval, $periods_to_include = 2 ) {

		if ( $interval <= 0 ) {
			return __( 'Now!', 'action-scheduler' );
		}

		$output           = '';
		$num_time_periods = count( self::$time_periods );

		for ( $time_period_index = 0, $periods_included = 0, $seconds_remaining = $interval; $time_period_index < $num_time_periods && $seconds_remaining > 0 && $periods_included < $periods_to_include; $time_period_index++ ) {

			$periods_in_interval = floor( $seconds_remaining / self::$time_periods[ $time_period_index ]['seconds'] );

			if ( $periods_in_interval > 0 ) {
				if ( ! empty( $output ) ) {
					$output .= ' ';
				}
				$output            .= sprintf( translate_nooped_plural( self::$time_periods[ $time_period_index ]['names'], $periods_in_interval, 'action-scheduler' ), $periods_in_interval );
				$seconds_remaining -= $periods_in_interval * self::$time_periods[ $time_period_index ]['seconds'];
				$periods_included++;
			}
		}

		return $output;
	}

	/**
	 * Returns the recurrence of an action or 'Non-repeating'. The output is human readable.
	 *
	 * @param ActionScheduler_Action $action Action object.
	 *
	 * @return string
	 */
	protected function get_recurrence( $action ) {
		$schedule = $action->get_schedule();
		if ( $schedule->is_recurring() && method_exists( $schedule, 'get_recurrence' ) ) {
			$recurrence = $schedule->get_recurrence();

			if ( is_numeric( $recurrence ) ) {
				/* translators: %s: time interval */
				return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) );
			} else {
				return $recurrence;
			}
		}

		return __( 'Non-repeating', 'action-scheduler' );
	}

	/**
	 * Serializes the argument of an action to render it in a human friendly format.
	 *
	 * @param array $row The array representation of the current row of the table.
	 *
	 * @return string
	 */
	public function column_args( array $row ) {
		if ( empty( $row['args'] ) ) {
			return apply_filters( 'action_scheduler_list_table_column_args', '', $row );
		}

		$row_html = '<ul>';
		foreach ( $row['args'] as $key => $value ) {
			$row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		}
		$row_html .= '</ul>';

		return apply_filters( 'action_scheduler_list_table_column_args', $row_html, $row );
	}

	/**
	 * Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
	 *
	 * @param array $row Action array.
	 * @return string
	 */
	public function column_log_entries( array $row ) {

		$log_entries_html = '<ol>';

		$timezone = new DateTimezone( 'UTC' );

		foreach ( $row['log_entries'] as $log_entry ) {
			$log_entries_html .= $this->get_log_entry_html( $log_entry, $timezone );
		}

		$log_entries_html .= '</ol>';

		return $log_entries_html;
	}

	/**
	 * Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
	 *
	 * @param ActionScheduler_LogEntry $log_entry Log entry object.
	 * @param DateTimezone             $timezone Timestamp.
	 * @return string
	 */
	protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) {
		$date = $log_entry->get_date();
		$date->setTimezone( $timezone );
		return sprintf( '<li><strong>%s</strong><br/>%s</li>', esc_html( $date->format( 'Y-m-d H:i:s O' ) ), esc_html( $log_entry->get_message() ) );
	}

	/**
	 * Only display row actions for pending actions.
	 *
	 * @param array  $row         Row to render.
	 * @param string $column_name Current row.
	 *
	 * @return string
	 */
	protected function maybe_render_actions( $row, $column_name ) {
		if ( 'pending' === strtolower( $row['status_name'] ) ) {
			return parent::maybe_render_actions( $row, $column_name );
		}

		return '';
	}

	/**
	 * Renders admin notifications
	 *
	 * Notifications:
	 *  1. When the maximum number of tasks are being executed simultaneously.
	 *  2. Notifications when a task is manually executed.
	 *  3. Tables are missing.
	 */
	public function display_admin_notices() {
		global $wpdb;

		if ( ( is_a( $this->store, 'ActionScheduler_HybridStore' ) || is_a( $this->store, 'ActionScheduler_DBStore' ) ) && apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) {
			$table_list = array(
				'actionscheduler_actions',
				'actionscheduler_logs',
				'actionscheduler_groups',
				'actionscheduler_claims',
			);

			$found_tables = $wpdb->get_col( "SHOW TABLES LIKE '{$wpdb->prefix}actionscheduler%'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			foreach ( $table_list as $table_name ) {
				if ( ! in_array( $wpdb->prefix . $table_name, $found_tables, true ) ) {
					$this->admin_notices[] = array(
						'class'   => 'error',
						'message' => __( 'It appears one or more database tables were missing. Attempting to re-create the missing table(s).', 'action-scheduler' ),
					);
					$this->recreate_tables();
					parent::display_admin_notices();

					return;
				}
			}
		}

		if ( $this->runner->has_maximum_concurrent_batches() ) {
			$claim_count           = $this->store->get_claim_count();
			$this->admin_notices[] = array(
				'class'   => 'updated',
				'message' => sprintf(
					/* translators: %s: amount of claims */
					_n(
						'Maximum simultaneous queues already in progress (%s queue). No additional queues will begin processing until the current queues are complete.',
						'Maximum simultaneous queues already in progress (%s queues). No additional queues will begin processing until the current queues are complete.',
						$claim_count,
						'action-scheduler'
					),
					$claim_count
				),
			);
		} elseif ( $this->store->has_pending_actions_due() ) {

			$async_request_lock_expiration = ActionScheduler::lock()->get_expiration( 'async-request-runner' );

			// No lock set or lock expired.
			if ( false === $async_request_lock_expiration || $async_request_lock_expiration < time() ) {
				$in_progress_url = add_query_arg( 'status', 'in-progress', remove_query_arg( 'status' ) );
				/* translators: %s: process URL */
				$async_request_message = sprintf( __( 'A new queue has begun processing. <a href="%s">View actions in-progress &raquo;</a>', 'action-scheduler' ), esc_url( $in_progress_url ) );
			} else {
				/* translators: %d: seconds */
				$async_request_message = sprintf( __( 'The next queue will begin processing in approximately %d seconds.', 'action-scheduler' ), $async_request_lock_expiration - time() );
			}

			$this->admin_notices[] = array(
				'class'   => 'notice notice-info',
				'message' => $async_request_message,
			);
		}

		$notification = get_transient( 'action_scheduler_admin_notice' );

		if ( is_array( $notification ) ) {
			delete_transient( 'action_scheduler_admin_notice' );

			$action           = $this->store->fetch_action( $notification['action_id'] );
			$action_hook_html = '<strong><code>' . $action->get_hook() . '</code></strong>';

			if ( 1 === absint( $notification['success'] ) ) {
				$class = 'updated';
				switch ( $notification['row_action_type'] ) {
					case 'run':
						/* translators: %s: action HTML */
						$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
						break;
					case 'cancel':
						/* translators: %s: action HTML */
						$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
						break;
					default:
						/* translators: %s: action HTML */
						$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
						break;
				}
			} else {
				$class = 'error';
				/* translators: 1: action HTML 2: action ID 3: error message */
				$action_message_html = sprintf( __( 'Could not process change for action: "%1$s" (ID: %2$d). Error: %3$s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) );
			}

			$action_message_html = apply_filters( 'action_scheduler_admin_notice_html', $action_message_html, $action, $notification );

			$this->admin_notices[] = array(
				'class'   => $class,
				'message' => $action_message_html,
			);
		}

		parent::display_admin_notices();
	}

	/**
	 * Prints the scheduled date in a human friendly format.
	 *
	 * @param array $row The array representation of the current row of the table.
	 *
	 * @return string
	 */
	public function column_schedule( $row ) {
		return $this->get_schedule_display_string( $row['schedule'] );
	}

	/**
	 * Get the scheduled date in a human friendly format.
	 *
	 * @param ActionScheduler_Schedule $schedule Action's schedule.
	 * @return string
	 */
	protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) {

		$schedule_display_string = '';

		if ( is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) {
			return __( 'async', 'action-scheduler' );
		}

		if ( ! method_exists( $schedule, 'get_date' ) || ! $schedule->get_date() ) {
			return '0000-00-00 00:00:00';
		}

		$next_timestamp = $schedule->get_date()->getTimestamp();

		$schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' );
		$schedule_display_string .= '<br/>';

		if ( gmdate( 'U' ) > $next_timestamp ) {
			/* translators: %s: date interval */
			$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
		} else {
			/* translators: %s: date interval */
			$schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) );
		}

		return $schedule_display_string;
	}

	/**
	 * Bulk delete.
	 *
	 * Deletes actions based on their ID. This is the handler for the bulk delete. It assumes the data
	 * properly validated by the callee and it will delete the actions without any extra validation.
	 *
	 * @param int[]  $ids Action IDs.
	 * @param string $ids_sql Inherited and unused.
	 */
	protected function bulk_delete( array $ids, $ids_sql ) {
		foreach ( $ids as $id ) {
			try {
				$this->store->delete_action( $id );
			} catch ( Exception $e ) {
				// A possible reason for an exception would include a scenario where the same action is deleted by a
				// concurrent request.
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
				error_log(
					sprintf(
						/* translators: 1: action ID 2: exception message. */
						__( 'Action Scheduler was unable to delete action %1$d. Reason: %2$s', 'action-scheduler' ),
						$id,
						$e->getMessage()
					)
				);
			}
		}
	}

	/**
	 * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
	 * parameters are valid.
	 *
	 * @param int $action_id Action ID.
	 */
	protected function row_action_cancel( $action_id ) {
		$this->process_row_action( $action_id, 'cancel' );
	}

	/**
	 * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
	 * parameters are valid.
	 *
	 * @param int $action_id Action ID.
	 */
	protected function row_action_run( $action_id ) {
		$this->process_row_action( $action_id, 'run' );
	}

	/**
	 * Force the data store schema updates.
	 */
	protected function recreate_tables() {
		if ( is_a( $this->store, 'ActionScheduler_HybridStore' ) ) {
			$store = $this->store;
		} else {
			$store = new ActionScheduler_HybridStore();
		}
		add_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10, 2 );

		$store_schema  = new ActionScheduler_StoreSchema();
		$logger_schema = new ActionScheduler_LoggerSchema();
		$store_schema->register_tables( true );
		$logger_schema->register_tables( true );

		remove_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10 );
	}
	/**
	 * Implements the logic behind processing an action once an action link is clicked on the list table.
	 *
	 * @param int    $action_id Action ID.
	 * @param string $row_action_type The type of action to perform on the action.
	 */
	protected function process_row_action( $action_id, $row_action_type ) {
		try {
			switch ( $row_action_type ) {
				case 'run':
					$this->runner->process_action( $action_id, 'Admin List Table' );
					break;
				case 'cancel':
					$this->store->cancel_action( $action_id );
					break;
			}
			$success       = 1;
			$error_message = '';
		} catch ( Exception $e ) {
			$success       = 0;
			$error_message = $e->getMessage();
		}

		set_transient( 'action_scheduler_admin_notice', compact( 'action_id', 'success', 'error_message', 'row_action_type' ), 30 );
	}

	/**
	 * {@inheritDoc}
	 */
	public function prepare_items() {
		$this->prepare_column_headers();

		$per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );

		$query = array(
			'per_page' => $per_page,
			'offset'   => $this->get_items_offset(),
			'status'   => $this->get_request_status(),
			'orderby'  => $this->get_request_orderby(),
			'order'    => $this->get_request_order(),
			'search'   => $this->get_request_search_query(),
		);

		/**
		 * Change query arguments to query for past-due actions.
		 * Past-due actions have the 'pending' status and are in the past.
		 * This is needed because registering 'past-due' as a status is overkill.
		 */
		if ( 'past-due' === $this->get_request_status() ) {
			$query['status'] = ActionScheduler_Store::STATUS_PENDING;
			$query['date']   = as_get_datetime_object();
		}

		$this->items = array();

		$total_items = $this->store->query_actions( $query, 'count' );

		$status_labels = $this->store->get_status_labels();

		foreach ( $this->store->query_actions( $query ) as $action_id ) {
			try {
				$action = $this->store->fetch_action( $action_id );
			} catch ( Exception $e ) {
				continue;
			}
			if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
				continue;
			}
			$this->items[ $action_id ] = array(
				'ID'          => $action_id,
				'hook'        => $action->get_hook(),
				'status_name' => $this->store->get_status( $action_id ),
				'status'      => $status_labels[ $this->store->get_status( $action_id ) ],
				'args'        => $action->get_args(),
				'group'       => $action->get_group(),
				'log_entries' => $this->logger->get_logs( $action_id ),
				'claim_id'    => $this->store->get_claim_id( $action_id ),
				'recurrence'  => $this->get_recurrence( $action ),
				'schedule'    => $action->get_schedule(),
			);
		}

		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
				'total_pages' => ceil( $total_items / $per_page ),
			)
		);
	}

	/**
	 * Prints the available statuses so the user can click to filter.
	 */
	protected function display_filter_by_status() {
		$this->status_counts = $this->store->action_counts() + $this->store->extra_action_counts();
		parent::display_filter_by_status();
	}

	/**
	 * Get the text to display in the search box on the list table.
	 */
	protected function get_search_box_button_text() {
		return __( 'Search hook, args and claim ID', 'action-scheduler' );
	}

	/**
	 * {@inheritDoc}
	 */
	protected function get_per_page_option_name() {
		return str_replace( '-', '_', $this->screen->id ) . '_per_page';
	}
}
ActionScheduler_WPCommentCleaner.php000066600000010661151137657220013575 0ustar00<?php

/**
 * Class ActionScheduler_WPCommentCleaner
 *
 * @since 3.0.0
 */
class ActionScheduler_WPCommentCleaner {

	/**
	 * Post migration hook used to cleanup the WP comment table.
	 *
	 * @var string
	 */
	protected static $cleanup_hook = 'action_scheduler/cleanup_wp_comment_logs';

	/**
	 * An instance of the ActionScheduler_wpCommentLogger class to interact with the comments table.
	 *
	 * This instance should only be used as an interface. It should not be initialized.
	 *
	 * @var ActionScheduler_wpCommentLogger
	 */
	protected static $wp_comment_logger = null;

	/**
	 * The key used to store the cached value of whether there are logs in the WP comment table.
	 *
	 * @var string
	 */
	protected static $has_logs_option_key = 'as_has_wp_comment_logs';

	/**
	 * Initialize the class and attach callbacks.
	 */
	public static function init() {
		if ( empty( self::$wp_comment_logger ) ) {
			self::$wp_comment_logger = new ActionScheduler_wpCommentLogger();
		}

		add_action( self::$cleanup_hook, array( __CLASS__, 'delete_all_action_comments' ) );

		// While there are orphaned logs left in the comments table, we need to attach the callbacks which filter comment counts.
		add_action( 'pre_get_comments', array( self::$wp_comment_logger, 'filter_comment_queries' ), 10, 1 );
		add_action( 'wp_count_comments', array( self::$wp_comment_logger, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs.
		add_action( 'comment_feed_where', array( self::$wp_comment_logger, 'filter_comment_feed' ), 10, 2 );

		// Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen.
		add_action( 'load-tools_page_action-scheduler', array( __CLASS__, 'register_admin_notice' ) );
		add_action( 'load-woocommerce_page_wc-status', array( __CLASS__, 'register_admin_notice' ) );
	}

	/**
	 * Determines if there are log entries in the wp comments table.
	 *
	 * Uses the flag set on migration completion set by @see self::maybe_schedule_cleanup().
	 *
	 * @return boolean Whether there are scheduled action comments in the comments table.
	 */
	public static function has_logs() {
		return 'yes' === get_option( self::$has_logs_option_key );
	}

	/**
	 * Schedules the WP Post comment table cleanup to run in 6 months if it's not already scheduled.
	 * Attached to the migration complete hook 'action_scheduler/migration_complete'.
	 */
	public static function maybe_schedule_cleanup() {
		$has_logs = 'no';

		$args = array(
			'type'   => ActionScheduler_wpCommentLogger::TYPE,
			'number' => 1,
			'fields' => 'ids',
		);

		if ( (bool) get_comments( $args ) ) {
			$has_logs = 'yes';

			if ( ! as_next_scheduled_action( self::$cleanup_hook ) ) {
				as_schedule_single_action( gmdate( 'U' ) + ( 6 * MONTH_IN_SECONDS ), self::$cleanup_hook );
			}
		}

		update_option( self::$has_logs_option_key, $has_logs, true );
	}

	/**
	 * Delete all action comments from the WP Comments table.
	 */
	public static function delete_all_action_comments() {
		global $wpdb;

		$wpdb->delete(
			$wpdb->comments,
			array(
				'comment_type'  => ActionScheduler_wpCommentLogger::TYPE,
				'comment_agent' => ActionScheduler_wpCommentLogger::AGENT,
			)
		);

		update_option( self::$has_logs_option_key, 'no', true );
	}

	/**
	 * Registers admin notices about the orphaned action logs.
	 */
	public static function register_admin_notice() {
		add_action( 'admin_notices', array( __CLASS__, 'print_admin_notice' ) );
	}

	/**
	 * Prints details about the orphaned action logs and includes information on where to learn more.
	 */
	public static function print_admin_notice() {
		$next_cleanup_message        = '';
		$next_scheduled_cleanup_hook = as_next_scheduled_action( self::$cleanup_hook );

		if ( $next_scheduled_cleanup_hook ) {
			/* translators: %s: date interval */
			$next_cleanup_message = sprintf( __( 'This data will be deleted in %s.', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $next_scheduled_cleanup_hook ) );
		}

		$notice = sprintf(
			/* translators: 1: next cleanup message 2: github issue URL */
			__( 'Action Scheduler has migrated data to custom tables; however, orphaned log entries exist in the WordPress Comments table. %1$s <a href="%2$s">Learn more &raquo;</a>', 'action-scheduler' ),
			$next_cleanup_message,
			'https://github.com/woocommerce/action-scheduler/issues/368'
		);

		echo '<div class="notice notice-warning"><p>' . wp_kses_post( $notice ) . '</p></div>';
	}
}
actions/ActionScheduler_Action.php000066600000007510151137657220013306 0ustar00<?php

/**
 * Class ActionScheduler_Action
 */
class ActionScheduler_Action {
	/**
	 * Action's hook.
	 *
	 * @var string
	 */
	protected $hook = '';

	/**
	 * Action's args.
	 *
	 * @var array<string, mixed>
	 */
	protected $args = array();

	/**
	 * Action's schedule.
	 *
	 * @var ActionScheduler_Schedule
	 */
	protected $schedule = null;

	/**
	 * Action's group.
	 *
	 * @var string
	 */
	protected $group = '';

	/**
	 * Priorities are conceptually similar to those used for regular WordPress actions.
	 * Like those, a lower priority takes precedence over a higher priority and the default
	 * is 10.
	 *
	 * Unlike regular WordPress actions, the priority of a scheduled action is strictly an
	 * integer and should be kept within the bounds 0-255 (anything outside the bounds will
	 * be brought back into the acceptable range).
	 *
	 * @var int
	 */
	protected $priority = 10;

	/**
	 * Construct.
	 *
	 * @param string                        $hook Action's hook.
	 * @param mixed[]                       $args Action's arguments.
	 * @param null|ActionScheduler_Schedule $schedule Action's schedule.
	 * @param string                        $group Action's group.
	 */
	public function __construct( $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) {
		$schedule = empty( $schedule ) ? new ActionScheduler_NullSchedule() : $schedule;
		$this->set_hook( $hook );
		$this->set_schedule( $schedule );
		$this->set_args( $args );
		$this->set_group( $group );
	}

	/**
	 * Executes the action.
	 *
	 * If no callbacks are registered, an exception will be thrown and the action will not be
	 * fired. This is useful to help detect cases where the code responsible for setting up
	 * a scheduled action no longer exists.
	 *
	 * @throws Exception If no callbacks are registered for this action.
	 */
	public function execute() {
		$hook = $this->get_hook();

		if ( ! has_action( $hook ) ) {
			throw new Exception(
				sprintf(
					/* translators: 1: action hook. */
					__( 'Scheduled action for %1$s will not be executed as no callbacks are registered.', 'action-scheduler' ),
					$hook
				)
			);
		}

		do_action_ref_array( $hook, array_values( $this->get_args() ) );
	}

	/**
	 * Set action's hook.
	 *
	 * @param string $hook Action's hook.
	 */
	protected function set_hook( $hook ) {
		$this->hook = $hook;
	}

	/**
	 * Get action's hook.
	 */
	public function get_hook() {
		return $this->hook;
	}

	/**
	 * Set action's schedule.
	 *
	 * @param ActionScheduler_Schedule $schedule Action's schedule.
	 */
	protected function set_schedule( ActionScheduler_Schedule $schedule ) {
		$this->schedule = $schedule;
	}

	/**
	 * Action's schedule.
	 *
	 * @return ActionScheduler_Schedule
	 */
	public function get_schedule() {
		return $this->schedule;
	}

	/**
	 * Set action's args.
	 *
	 * @param mixed[] $args Action's arguments.
	 */
	protected function set_args( array $args ) {
		$this->args = $args;
	}

	/**
	 * Get action's args.
	 */
	public function get_args() {
		return $this->args;
	}

	/**
	 * Section action's group.
	 *
	 * @param string $group Action's group.
	 */
	protected function set_group( $group ) {
		$this->group = $group;
	}

	/**
	 * Action's group.
	 *
	 * @return string
	 */
	public function get_group() {
		return $this->group;
	}

	/**
	 * Action has not finished.
	 *
	 * @return bool
	 */
	public function is_finished() {
		return false;
	}

	/**
	 * Sets the priority of the action.
	 *
	 * @param int $priority Priority level (lower is higher priority). Should be in the range 0-255.
	 *
	 * @return void
	 */
	public function set_priority( $priority ) {
		if ( $priority < 0 ) {
			$priority = 0;
		} elseif ( $priority > 255 ) {
			$priority = 255;
		}

		$this->priority = (int) $priority;
	}

	/**
	 * Gets the action priority.
	 *
	 * @return int
	 */
	public function get_priority() {
		return $this->priority;
	}
}
actions/ActionScheduler_CanceledAction.php000066600000001563151137657220014727 0ustar00<?php

/**
 * Class ActionScheduler_CanceledAction
 *
 * Stored action which was canceled and therefore acts like a finished action but should always return a null schedule,
 * regardless of schedule passed to its constructor.
 */
class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction {

	/**
	 * Construct.
	 *
	 * @param string                        $hook Action's hook.
	 * @param array                         $args Action's arguments.
	 * @param null|ActionScheduler_Schedule $schedule Action's schedule.
	 * @param string                        $group Action's group.
	 */
	public function __construct( $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) {
		parent::__construct( $hook, $args, $schedule, $group );
		if ( is_null( $schedule ) ) {
			$this->set_schedule( new ActionScheduler_NullSchedule() );
		}
	}
}
actions/ActionScheduler_FinishedAction.php000066600000000450151137657220014754 0ustar00<?php

/**
 * Class ActionScheduler_FinishedAction
 */
class ActionScheduler_FinishedAction extends ActionScheduler_Action {

	/**
	 * Execute action.
	 */
	public function execute() {
		// don't execute.
	}

	/**
	 * Get finished state.
	 */
	public function is_finished() {
		return true;
	}
}
actions/ActionScheduler_NullAction.php000066600000001131151137657220014132 0ustar00<?php

/**
 * Class ActionScheduler_NullAction
 */
class ActionScheduler_NullAction extends ActionScheduler_Action {

	/**
	 * Construct.
	 *
	 * @param string                        $hook Action hook.
	 * @param mixed[]                       $args Action arguments.
	 * @param null|ActionScheduler_Schedule $schedule Action schedule.
	 */
	public function __construct( $hook = '', array $args = array(), ?ActionScheduler_Schedule $schedule = null ) {
		$this->set_schedule( new ActionScheduler_NullSchedule() );
	}

	/**
	 * Execute action.
	 */
	public function execute() {
		// don't execute.
	}
}
schedules/ActionScheduler_CanceledSchedule.php000066600000003157151137657220015566 0ustar00<?php

/**
 * Class ActionScheduler_SimpleSchedule
 */
class ActionScheduler_CanceledSchedule extends ActionScheduler_SimpleSchedule {

	/**
	 * Deprecated property @see $this->__wakeup() for details.
	 *
	 * @var null
	 */
	private $timestamp = null;

	/**
	 * Calculate when the next instance of this schedule would run based on a given date & time.
	 *
	 * @param DateTime $after Timestamp.
	 *
	 * @return DateTime|null
	 */
	public function calculate_next( DateTime $after ) {
		return null;
	}

	/**
	 * Cancelled actions should never have a next schedule, even if get_next()
	 * is called with $after < $this->scheduled_date.
	 *
	 * @param DateTime $after Timestamp.
	 * @return DateTime|null
	 */
	public function get_next( DateTime $after ) {
		return null;
	}

	/**
	 * Action is not recurring.
	 *
	 * @return bool
	 */
	public function is_recurring() {
		return false;
	}

	/**
	 * Unserialize recurring schedules serialized/stored prior to AS 3.0.0
	 *
	 * Prior to Action Scheduler 3.0.0, schedules used different property names to refer
	 * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
	 * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
	 * aligned properties and property names for better inheritance. To maintain backward
	 * compatibility with schedules serialized and stored prior to 3.0, we need to correctly
	 * map the old property names with matching visibility.
	 */
	public function __wakeup() {
		if ( ! is_null( $this->timestamp ) ) {
			$this->scheduled_timestamp = $this->timestamp;
			unset( $this->timestamp );
		}
		parent::__wakeup();
	}
}
schedules/ActionScheduler_NullSchedule.php000066600000001305151137657220014773 0ustar00<?php

/**
 * Class ActionScheduler_NullSchedule
 */
class ActionScheduler_NullSchedule extends ActionScheduler_SimpleSchedule {

	/**
	 * DateTime instance.
	 *
	 * @var DateTime|null
	 */
	protected $scheduled_date;

	/**
	 * Make the $date param optional and default to null.
	 *
	 * @param null|DateTime $date The date & time to run the action.
	 */
	public function __construct( ?DateTime $date = null ) {
		$this->scheduled_date = null;
	}

	/**
	 * This schedule has no scheduled DateTime, so we need to override the parent __sleep().
	 *
	 * @return array
	 */
	public function __sleep() {
		return array();
	}

	/**
	 * Wakeup.
	 */
	public function __wakeup() {
		$this->scheduled_date = null;
	}
}
schedules/ActionScheduler_CronSchedule.php000066600000007367151137657220015000 0ustar00<?php

/**
 * Class ActionScheduler_CronSchedule
 */
class ActionScheduler_CronSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule {

	/**
	 * Deprecated property @see $this->__wakeup() for details.
	 *
	 * @var null
	 */
	private $start_timestamp = null;

	/**
	 * Deprecated property @see $this->__wakeup() for details.
	 *
	 * @var null
	 */
	private $cron = null;

	/**
	 * Wrapper for parent constructor to accept a cron expression string and map it to a CronExpression for this
	 * objects $recurrence property.
	 *
	 * @param DateTime              $start The date & time to run the action at or after. If $start aligns with the CronSchedule passed via $recurrence, it will be used. If it does not align, the first matching date after it will be used.
	 * @param CronExpression|string $recurrence The CronExpression used to calculate the schedule's next instance.
	 * @param DateTime|null         $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance.
	 */
	public function __construct( DateTime $start, $recurrence, ?DateTime $first = null ) {
		if ( ! is_a( $recurrence, 'CronExpression' ) ) {
			$recurrence = CronExpression::factory( $recurrence );
		}

		// For backward compatibility, we need to make sure the date is set to the first matching cron date, not whatever date is passed in. Importantly, by passing true as the 3rd param, if $start matches the cron expression, then it will be used. This was previously handled in the now deprecated next() method.
		$date = $recurrence->getNextRunDate( $start, 0, true );

		// parent::__construct() will set this to $date by default, but that may be different to $start now.
		$first = empty( $first ) ? $start : $first;

		parent::__construct( $date, $recurrence, $first );
	}

	/**
	 * Calculate when an instance of this schedule would start based on a given
	 * date & time using its the CronExpression.
	 *
	 * @param DateTime $after Timestamp.
	 * @return DateTime
	 */
	protected function calculate_next( DateTime $after ) {
		return $this->recurrence->getNextRunDate( $after, 0, false );
	}

	/**
	 * Get the schedule's recurrence.
	 *
	 * @return string
	 */
	public function get_recurrence() {
		return strval( $this->recurrence );
	}

	/**
	 * Serialize cron schedules with data required prior to AS 3.0.0
	 *
	 * Prior to Action Scheduler 3.0.0, recurring schedules used different property names to
	 * refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
	 * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
	 * aligned properties and property names for better inheritance. To guard against the
	 * possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to
	 * also store the data with the old property names so if it's unserialized in AS < 3.0,
	 * the schedule doesn't end up with a null recurrence.
	 *
	 * @return array
	 */
	public function __sleep() {

		$sleep_params = parent::__sleep();

		$this->start_timestamp = $this->scheduled_timestamp;
		$this->cron            = $this->recurrence;

		return array_merge(
			$sleep_params,
			array(
				'start_timestamp',
				'cron',
			)
		);
	}

	/**
	 * Unserialize cron schedules serialized/stored prior to AS 3.0.0
	 *
	 * For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup().
	 */
	public function __wakeup() {
		if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) {
			$this->scheduled_timestamp = $this->start_timestamp;
			unset( $this->start_timestamp );
		}

		if ( is_null( $this->recurrence ) && ! is_null( $this->cron ) ) {
			$this->recurrence = $this->cron;
			unset( $this->cron );
		}
		parent::__wakeup();
	}
}

schedules/ActionScheduler_Schedule.php000066600000000710151137657220014137 0ustar00<?php

/**
 * Class ActionScheduler_Schedule
 */
interface ActionScheduler_Schedule {
	/**
	 * Get the date & time this schedule was created to run, or calculate when it should be run
	 * after a given date & time.
	 *
	 * @param null|DateTime $after Timestamp.
	 * @return DateTime|null
	 */
	public function next( ?DateTime $after = null );

	/**
	 * Identify the schedule as (not) recurring.
	 *
	 * @return bool
	 */
	public function is_recurring();
}
schedules/ActionScheduler_IntervalSchedule.php000066600000005111151137657220015644 0ustar00<?php

/**
 * Class ActionScheduler_IntervalSchedule
 */
class ActionScheduler_IntervalSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule {

	/**
	 * Deprecated property @see $this->__wakeup() for details.
	 *
	 * @var null
	 */
	private $start_timestamp = null;

	/**
	 * Deprecated property @see $this->__wakeup() for details.
	 *
	 * @var null
	 */
	private $interval_in_seconds = null;

	/**
	 * Calculate when this schedule should start after a given date & time using
	 * the number of seconds between recurrences.
	 *
	 * @param DateTime $after Timestamp.
	 * @return DateTime
	 */
	protected function calculate_next( DateTime $after ) {
		$after->modify( '+' . (int) $this->get_recurrence() . ' seconds' );
		return $after;
	}

	/**
	 * Schedule interval in seconds.
	 *
	 * @return int
	 */
	public function interval_in_seconds() {
		_deprecated_function( __METHOD__, '3.0.0', '(int)ActionScheduler_Abstract_RecurringSchedule::get_recurrence()' );
		return (int) $this->get_recurrence();
	}

	/**
	 * Serialize interval schedules with data required prior to AS 3.0.0
	 *
	 * Prior to Action Scheduler 3.0.0, recurring schedules used different property names to
	 * refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
	 * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
	 * aligned properties and property names for better inheritance. To guard against the
	 * possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to
	 * also store the data with the old property names so if it's unserialized in AS < 3.0,
	 * the schedule doesn't end up with a null/false/0 recurrence.
	 *
	 * @return array
	 */
	public function __sleep() {

		$sleep_params = parent::__sleep();

		$this->start_timestamp     = $this->scheduled_timestamp;
		$this->interval_in_seconds = $this->recurrence;

		return array_merge(
			$sleep_params,
			array(
				'start_timestamp',
				'interval_in_seconds',
			)
		);
	}

	/**
	 * Unserialize interval schedules serialized/stored prior to AS 3.0.0
	 *
	 * For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup().
	 */
	public function __wakeup() {
		if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) {
			$this->scheduled_timestamp = $this->start_timestamp;
			unset( $this->start_timestamp );
		}

		if ( is_null( $this->recurrence ) && ! is_null( $this->interval_in_seconds ) ) {
			$this->recurrence = $this->interval_in_seconds;
			unset( $this->interval_in_seconds );
		}
		parent::__wakeup();
	}
}
schedules/ActionScheduler_SimpleSchedule.php000066600000004477151137657220015327 0ustar00<?php

/**
 * Class ActionScheduler_SimpleSchedule
 */
class ActionScheduler_SimpleSchedule extends ActionScheduler_Abstract_Schedule {

	/**
	 * Deprecated property @see $this->__wakeup() for details.
	 *
	 * @var null|DateTime
	 */
	private $timestamp = null;

	/**
	 * Calculate when this schedule should start after a given date & time using
	 * the number of seconds between recurrences.
	 *
	 * @param DateTime $after Timestamp.
	 *
	 * @return DateTime|null
	 */
	public function calculate_next( DateTime $after ) {
		return null;
	}

	/**
	 * Schedule is not recurring.
	 *
	 * @return bool
	 */
	public function is_recurring() {
		return false;
	}

	/**
	 * Serialize schedule with data required prior to AS 3.0.0
	 *
	 * Prior to Action Scheduler 3.0.0, schedules used different property names to refer
	 * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
	 * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
	 * aligned properties and property names for better inheritance. To guard against the
	 * scheduled date for single actions always being seen as "now" if downgrading to
	 * Action Scheduler < 3.0.0, we need to also store the data with the old property names
	 * so if it's unserialized in AS < 3.0, the schedule doesn't end up with a null recurrence.
	 *
	 * @return array
	 */
	public function __sleep() {

		$sleep_params = parent::__sleep();

		$this->timestamp = $this->scheduled_timestamp;

		return array_merge(
			$sleep_params,
			array(
				'timestamp',
			)
		);
	}

	/**
	 * Unserialize recurring schedules serialized/stored prior to AS 3.0.0
	 *
	 * Prior to Action Scheduler 3.0.0, schedules used different property names to refer
	 * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
	 * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
	 * aligned properties and property names for better inheritance. To maintain backward
	 * compatibility with schedules serialized and stored prior to 3.0, we need to correctly
	 * map the old property names with matching visibility.
	 */
	public function __wakeup() {

		if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->timestamp ) ) {
			$this->scheduled_timestamp = $this->timestamp;
			unset( $this->timestamp );
		}
		parent::__wakeup();
	}
}
ActionScheduler_AsyncRequest_QueueRunner.php000066600000004163151137657220015416 0ustar00<?php

defined( 'ABSPATH' ) || exit;

/**
 * ActionScheduler_AsyncRequest_QueueRunner class.
 */
class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request {

	/**
	 * Data store for querying actions
	 *
	 * @var ActionScheduler_Store
	 */
	protected $store;

	/**
	 * Prefix for ajax hooks
	 *
	 * @var string
	 */
	protected $prefix = 'as';

	/**
	 * Action for ajax hooks
	 *
	 * @var string
	 */
	protected $action = 'async_request_queue_runner';

	/**
	 * Initiate new async request.
	 *
	 * @param ActionScheduler_Store $store Store object.
	 */
	public function __construct( ActionScheduler_Store $store ) {
		parent::__construct();
		$this->store = $store;
	}

	/**
	 * Handle async requests
	 *
	 * Run a queue, and maybe dispatch another async request to run another queue
	 * if there are still pending actions after completing a queue in this request.
	 */
	protected function handle() {
		do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context.

		$sleep_seconds = $this->get_sleep_seconds();

		if ( $sleep_seconds ) {
			sleep( $sleep_seconds );
		}

		$this->maybe_dispatch();
	}

	/**
	 * If the async request runner is needed and allowed to run, dispatch a request.
	 */
	public function maybe_dispatch() {
		if ( ! $this->allow() ) {
			return;
		}

		$this->dispatch();
		ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request();
	}

	/**
	 * Only allow async requests when needed.
	 *
	 * Also allow 3rd party code to disable running actions via async requests.
	 */
	protected function allow() {

		if ( ! has_action( 'action_scheduler_run_queue' ) || ActionScheduler::runner()->has_maximum_concurrent_batches() || ! $this->store->has_pending_actions_due() ) {
			$allow = false;
		} else {
			$allow = true;
		}

		return apply_filters( 'action_scheduler_allow_async_request_runner', $allow );
	}

	/**
	 * Chaining async requests can crash MySQL. A brief sleep call in PHP prevents that.
	 */
	protected function get_sleep_seconds() {
		return apply_filters( 'action_scheduler_async_request_sleep_seconds', 5, $this );
	}
}
schema/ActionScheduler_LoggerSchema.php000066600000005672151137657220014240 0ustar00<?php

/**
 * Class ActionScheduler_LoggerSchema
 *
 * @codeCoverageIgnore
 *
 * Creates a custom table for storing action logs
 */
class ActionScheduler_LoggerSchema extends ActionScheduler_Abstract_Schema {
	const LOG_TABLE = 'actionscheduler_logs';

	/**
	 * Schema version.
	 *
	 * Increment this value to trigger a schema update.
	 *
	 * @var int
	 */
	protected $schema_version = 3;

	/**
	 * Construct.
	 */
	public function __construct() {
		$this->tables = array(
			self::LOG_TABLE,
		);
	}

	/**
	 * Performs additional setup work required to support this schema.
	 */
	public function init() {
		add_action( 'action_scheduler_before_schema_update', array( $this, 'update_schema_3_0' ), 10, 2 );
	}

	/**
	 * Get table definition.
	 *
	 * @param string $table Table name.
	 */
	protected function get_table_definition( $table ) {
		global $wpdb;
		$table_name      = $wpdb->$table;
		$charset_collate = $wpdb->get_charset_collate();
		switch ( $table ) {

			case self::LOG_TABLE:
				$default_date = ActionScheduler_StoreSchema::DEFAULT_DATE;
				return "CREATE TABLE $table_name (
				        log_id bigint(20) unsigned NOT NULL auto_increment,
				        action_id bigint(20) unsigned NOT NULL,
				        message text NOT NULL,
				        log_date_gmt datetime NULL default '{$default_date}',
				        log_date_local datetime NULL default '{$default_date}',
				        PRIMARY KEY  (log_id),
				        KEY action_id (action_id),
				        KEY log_date_gmt (log_date_gmt)
				        ) $charset_collate";

			default:
				return '';
		}
	}

	/**
	 * Update the logs table schema, allowing datetime fields to be NULL.
	 *
	 * This is needed because the NOT NULL constraint causes a conflict with some versions of MySQL
	 * configured with sql_mode=NO_ZERO_DATE, which can for instance lead to tables not being created.
	 *
	 * Most other schema updates happen via ActionScheduler_Abstract_Schema::update_table(), however
	 * that method relies on dbDelta() and this change is not possible when using that function.
	 *
	 * @param string $table Name of table being updated.
	 * @param string $db_version The existing schema version of the table.
	 */
	public function update_schema_3_0( $table, $db_version ) {
		global $wpdb;

		if ( 'actionscheduler_logs' !== $table || version_compare( $db_version, '3', '>=' ) ) {
			return;
		}

		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$table_name   = $wpdb->prefix . 'actionscheduler_logs';
		$table_list   = $wpdb->get_col( "SHOW TABLES LIKE '{$table_name}'" );
		$default_date = ActionScheduler_StoreSchema::DEFAULT_DATE;

		if ( ! empty( $table_list ) ) {
			$query = "
				ALTER TABLE {$table_name}
				MODIFY COLUMN log_date_gmt datetime NULL default '{$default_date}',
				MODIFY COLUMN log_date_local datetime NULL default '{$default_date}'
			";
			$wpdb->query( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		}
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	}
}
schema/ActionScheduler_StoreSchema.php000066600000011773151137657220014114 0ustar00<?php

/**
 * Class ActionScheduler_StoreSchema
 *
 * @codeCoverageIgnore
 *
 * Creates custom tables for storing scheduled actions
 */
class ActionScheduler_StoreSchema extends ActionScheduler_Abstract_Schema {
	const ACTIONS_TABLE = 'actionscheduler_actions';
	const CLAIMS_TABLE  = 'actionscheduler_claims';
	const GROUPS_TABLE  = 'actionscheduler_groups';
	const DEFAULT_DATE  = '0000-00-00 00:00:00';

	/**
	 * Schema version.
	 *
	 * Increment this value to trigger a schema update.
	 *
	 * @var int
	 */
	protected $schema_version = 7;

	/**
	 * Construct.
	 */
	public function __construct() {
		$this->tables = array(
			self::ACTIONS_TABLE,
			self::CLAIMS_TABLE,
			self::GROUPS_TABLE,
		);
	}

	/**
	 * Performs additional setup work required to support this schema.
	 */
	public function init() {
		add_action( 'action_scheduler_before_schema_update', array( $this, 'update_schema_5_0' ), 10, 2 );
	}

	/**
	 * Get table definition.
	 *
	 * @param string $table Table name.
	 */
	protected function get_table_definition( $table ) {
		global $wpdb;
		$table_name      = $wpdb->$table;
		$charset_collate = $wpdb->get_charset_collate();
		$default_date    = self::DEFAULT_DATE;
		// phpcs:ignore Squiz.PHP.CommentedOutCode
		$max_index_length = 191; // @see wp_get_db_schema()

		$hook_status_scheduled_date_gmt_max_index_length = $max_index_length - 20 - 8; // - status, - scheduled_date_gmt

		switch ( $table ) {

			case self::ACTIONS_TABLE:
				return "CREATE TABLE {$table_name} (
				        action_id bigint(20) unsigned NOT NULL auto_increment,
				        hook varchar(191) NOT NULL,
				        status varchar(20) NOT NULL,
				        scheduled_date_gmt datetime NULL default '{$default_date}',
				        scheduled_date_local datetime NULL default '{$default_date}',
				        priority tinyint unsigned NOT NULL default '10',
				        args varchar($max_index_length),
				        schedule longtext,
				        group_id bigint(20) unsigned NOT NULL default '0',
				        attempts int(11) NOT NULL default '0',
				        last_attempt_gmt datetime NULL default '{$default_date}',
				        last_attempt_local datetime NULL default '{$default_date}',
				        claim_id bigint(20) unsigned NOT NULL default '0',
				        extended_args varchar(8000) DEFAULT NULL,
				        PRIMARY KEY  (action_id),
				        KEY hook_status_scheduled_date_gmt (hook($hook_status_scheduled_date_gmt_max_index_length), status, scheduled_date_gmt),
				        KEY status_scheduled_date_gmt (status, scheduled_date_gmt),
				        KEY scheduled_date_gmt (scheduled_date_gmt),
				        KEY args (args($max_index_length)),
				        KEY group_id (group_id),
				        KEY last_attempt_gmt (last_attempt_gmt),
				        KEY `claim_id_status_scheduled_date_gmt` (`claim_id`, `status`, `scheduled_date_gmt`)
				        ) $charset_collate";

			case self::CLAIMS_TABLE:
				return "CREATE TABLE {$table_name} (
				        claim_id bigint(20) unsigned NOT NULL auto_increment,
				        date_created_gmt datetime NULL default '{$default_date}',
				        PRIMARY KEY  (claim_id),
				        KEY date_created_gmt (date_created_gmt)
				        ) $charset_collate";

			case self::GROUPS_TABLE:
				return "CREATE TABLE {$table_name} (
				        group_id bigint(20) unsigned NOT NULL auto_increment,
				        slug varchar(255) NOT NULL,
				        PRIMARY KEY  (group_id),
				        KEY slug (slug($max_index_length))
				        ) $charset_collate";

			default:
				return '';
		}
	}

	/**
	 * Update the actions table schema, allowing datetime fields to be NULL.
	 *
	 * This is needed because the NOT NULL constraint causes a conflict with some versions of MySQL
	 * configured with sql_mode=NO_ZERO_DATE, which can for instance lead to tables not being created.
	 *
	 * Most other schema updates happen via ActionScheduler_Abstract_Schema::update_table(), however
	 * that method relies on dbDelta() and this change is not possible when using that function.
	 *
	 * @param string $table Name of table being updated.
	 * @param string $db_version The existing schema version of the table.
	 */
	public function update_schema_5_0( $table, $db_version ) {
		global $wpdb;

		if ( 'actionscheduler_actions' !== $table || version_compare( $db_version, '5', '>=' ) ) {
			return;
		}

		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$table_name   = $wpdb->prefix . 'actionscheduler_actions';
		$table_list   = $wpdb->get_col( "SHOW TABLES LIKE '{$table_name}'" );
		$default_date = self::DEFAULT_DATE;

		if ( ! empty( $table_list ) ) {
			$query = "
				ALTER TABLE {$table_name}
				MODIFY COLUMN scheduled_date_gmt datetime NULL default '{$default_date}',
				MODIFY COLUMN scheduled_date_local datetime NULL default '{$default_date}',
				MODIFY COLUMN last_attempt_gmt datetime NULL default '{$default_date}',
				MODIFY COLUMN last_attempt_local datetime NULL default '{$default_date}'
		";
			$wpdb->query( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		}
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	}
}
ActionScheduler_OptionLock.php000066600000007754151137657220012524 0ustar00<?php

/**
 * Provide a way to set simple transient locks to block behaviour
 * for up-to a given duration.
 *
 * Class ActionScheduler_OptionLock
 *
 * @since 3.0.0
 */
class ActionScheduler_OptionLock extends ActionScheduler_Lock {

	/**
	 * Set a lock using options for a given amount of time (60 seconds by default).
	 *
	 * Using an autoloaded option avoids running database queries or other resource intensive tasks
	 * on frequently triggered hooks, like 'init' or 'shutdown'.
	 *
	 * For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid
	 * calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown',
	 * hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count()
	 * to find the current number of claims in the database.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @bool True if lock value has changed, false if not or if set failed.
	 */
	public function set( $lock_type ) {
		global $wpdb;

		$lock_key            = $this->get_key( $lock_type );
		$existing_lock_value = $this->get_existing_lock( $lock_type );
		$new_lock_value      = $this->new_lock_value( $lock_type );

		// The lock may not exist yet, or may have been deleted.
		if ( empty( $existing_lock_value ) ) {
			return (bool) $wpdb->insert(
				$wpdb->options,
				array(
					'option_name'  => $lock_key,
					'option_value' => $new_lock_value,
					'autoload'     => 'no',
				)
			);
		}

		if ( $this->get_expiration_from( $existing_lock_value ) >= time() ) {
			return false;
		}

		// Otherwise, try to obtain the lock.
		return (bool) $wpdb->update(
			$wpdb->options,
			array( 'option_value' => $new_lock_value ),
			array(
				'option_name'  => $lock_key,
				'option_value' => $existing_lock_value,
			)
		);
	}

	/**
	 * If a lock is set, return the timestamp it was set to expiry.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
	 */
	public function get_expiration( $lock_type ) {
		return $this->get_expiration_from( $this->get_existing_lock( $lock_type ) );
	}

	/**
	 * Given the lock string, derives the lock expiration timestamp (or false if it cannot be determined).
	 *
	 * @param string $lock_value String containing a timestamp, or pipe-separated combination of unique value and timestamp.
	 *
	 * @return false|int
	 */
	private function get_expiration_from( $lock_value ) {
		$lock_string = explode( '|', $lock_value );

		// Old style lock?
		if ( count( $lock_string ) === 1 && is_numeric( $lock_string[0] ) ) {
			return (int) $lock_string[0];
		}

		// New style lock?
		if ( count( $lock_string ) === 2 && is_numeric( $lock_string[1] ) ) {
			return (int) $lock_string[1];
		}

		return false;
	}

	/**
	 * Get the key to use for storing the lock in the transient
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @return string
	 */
	protected function get_key( $lock_type ) {
		return sprintf( 'action_scheduler_lock_%s', $lock_type );
	}

	/**
	 * Supplies the existing lock value, or an empty string if not set.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 *
	 * @return string
	 */
	private function get_existing_lock( $lock_type ) {
		global $wpdb;

		// Now grab the existing lock value, if there is one.
		return (string) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s",
				$this->get_key( $lock_type )
			)
		);
	}

	/**
	 * Supplies a lock value consisting of a unique value and the current timestamp, which are separated by a pipe
	 * character.
	 *
	 * Example: (string) "649de012e6b262.09774912|1688068114"
	 *
	 * @param string $lock_type A string to identify different lock types.
	 *
	 * @return string
	 */
	private function new_lock_value( $lock_type ) {
		return uniqid( '', true ) . '|' . ( time() + $this->get_duration( $lock_type ) );
	}
}
ActionScheduler_DataController.php000066600000012445151137657220013351 0ustar00<?php

use Action_Scheduler\Migration\Controller;

/**
 * Class ActionScheduler_DataController
 *
 * The main plugin/initialization class for the data stores.
 *
 * Responsible for hooking everything up with WordPress.
 *
 * @package Action_Scheduler
 *
 * @since 3.0.0
 */
class ActionScheduler_DataController {
	/** Action data store class name. */
	const DATASTORE_CLASS = 'ActionScheduler_DBStore';

	/** Logger data store class name. */
	const LOGGER_CLASS = 'ActionScheduler_DBLogger';

	/** Migration status option name. */
	const STATUS_FLAG = 'action_scheduler_migration_status';

	/** Migration status option value. */
	const STATUS_COMPLETE = 'complete';

	/** Migration minimum required PHP version. */
	const MIN_PHP_VERSION = '5.5';

	/**
	 * Instance.
	 *
	 * @var ActionScheduler_DataController
	 */
	private static $instance;

	/**
	 * Sleep time in seconds.
	 *
	 * @var int
	 */
	private static $sleep_time = 0;

	/**
	 * Tick count required for freeing memory.
	 *
	 * @var int
	 */
	private static $free_ticks = 50;

	/**
	 * Get a flag indicating whether the migration environment dependencies are met.
	 *
	 * @return bool
	 */
	public static function dependencies_met() {
		$php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' );
		return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true );
	}

	/**
	 * Get a flag indicating whether the migration is complete.
	 *
	 * @return bool Whether the flag has been set marking the migration as complete
	 */
	public static function is_migration_complete() {
		return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE;
	}

	/**
	 * Mark the migration as complete.
	 */
	public static function mark_migration_complete() {
		update_option( self::STATUS_FLAG, self::STATUS_COMPLETE );
	}

	/**
	 * Unmark migration when a plugin is de-activated. Will not work in case of silent activation, for example in an update.
	 * We do this to mitigate the bug of lost actions which happens if there was an AS 2.x to AS 3.x migration in the past, but that plugin is now
	 * deactivated and the site was running on AS 2.x again.
	 */
	public static function mark_migration_incomplete() {
		delete_option( self::STATUS_FLAG );
	}

	/**
	 * Set the action store class name.
	 *
	 * @param string $class Classname of the store class.
	 *
	 * @return string
	 */
	public static function set_store_class( $class ) {
		return self::DATASTORE_CLASS;
	}

	/**
	 * Set the action logger class name.
	 *
	 * @param string $class Classname of the logger class.
	 *
	 * @return string
	 */
	public static function set_logger_class( $class ) {
		return self::LOGGER_CLASS;
	}

	/**
	 * Set the sleep time in seconds.
	 *
	 * @param integer $sleep_time The number of seconds to pause before resuming operation.
	 */
	public static function set_sleep_time( $sleep_time ) {
		self::$sleep_time = (int) $sleep_time;
	}

	/**
	 * Set the tick count required for freeing memory.
	 *
	 * @param integer $free_ticks The number of ticks to free memory on.
	 */
	public static function set_free_ticks( $free_ticks ) {
		self::$free_ticks = (int) $free_ticks;
	}

	/**
	 * Free memory if conditions are met.
	 *
	 * @param int $ticks Current tick count.
	 */
	public static function maybe_free_memory( $ticks ) {
		if ( self::$free_ticks && 0 === $ticks % self::$free_ticks ) {
			self::free_memory();
		}
	}

	/**
	 * Reduce memory footprint by clearing the database query and object caches.
	 */
	public static function free_memory() {
		if ( 0 < self::$sleep_time ) {
			/* translators: %d: amount of time */
			\WP_CLI::warning( sprintf( _n( 'Stopped the insanity for %d second', 'Stopped the insanity for %d seconds', self::$sleep_time, 'action-scheduler' ), self::$sleep_time ) );
			sleep( self::$sleep_time );
		}

		\WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );

		/**
		 * Globals.
		 *
		 * @var $wpdb            \wpdb
		 * @var $wp_object_cache \WP_Object_Cache
		 */
		global $wpdb, $wp_object_cache;

		$wpdb->queries = array();

		if ( ! is_a( $wp_object_cache, 'WP_Object_Cache' ) ) {
			return;
		}

		$wp_object_cache->group_ops      = array();
		$wp_object_cache->stats          = array();
		$wp_object_cache->memcache_debug = array();
		$wp_object_cache->cache          = array();

		if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) {
			call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important!
		}
	}

	/**
	 * Connect to table datastores if migration is complete.
	 * Otherwise, proceed with the migration if the dependencies have been met.
	 */
	public static function init() {
		if ( self::is_migration_complete() ) {
			add_filter( 'action_scheduler_store_class', array( 'ActionScheduler_DataController', 'set_store_class' ), 100 );
			add_filter( 'action_scheduler_logger_class', array( 'ActionScheduler_DataController', 'set_logger_class' ), 100 );
			add_action( 'deactivate_plugin', array( 'ActionScheduler_DataController', 'mark_migration_incomplete' ) );
		} elseif ( self::dependencies_met() ) {
			Controller::init();
		}

		add_action( 'action_scheduler/progress_tick', array( 'ActionScheduler_DataController', 'maybe_free_memory' ) );
	}

	/**
	 * Singleton factory.
	 */
	public static function instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new static();
		}

		return self::$instance;
	}
}
ActionScheduler_AdminView.php000066600000024603151137657220012316 0ustar00<?php

/**
 * Class ActionScheduler_AdminView
 *
 * @codeCoverageIgnore
 */
class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {

	/**
	 * Instance.
	 *
	 * @var null|self
	 */
	private static $admin_view = null;

	/**
	 * Screen ID.
	 *
	 * @var string
	 */
	private static $screen_id = 'tools_page_action-scheduler';

	/**
	 * ActionScheduler_ListTable instance.
	 *
	 * @var ActionScheduler_ListTable
	 */
	protected $list_table;

	/**
	 * Get instance.
	 *
	 * @return ActionScheduler_AdminView
	 * @codeCoverageIgnore
	 */
	public static function instance() {

		if ( empty( self::$admin_view ) ) {
			$class            = apply_filters( 'action_scheduler_admin_view_class', 'ActionScheduler_AdminView' );
			self::$admin_view = new $class();
		}

		return self::$admin_view;
	}

	/**
	 * Initialize.
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {
		if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {

			if ( class_exists( 'WooCommerce' ) ) {
				add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) );
				add_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) );
				add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
			}

			add_action( 'admin_menu', array( $this, 'register_menu' ) );
			add_action( 'admin_notices', array( $this, 'maybe_check_pastdue_actions' ) );
			add_action( 'current_screen', array( $this, 'add_help_tabs' ) );
		}
	}

	/**
	 * Print system status report.
	 */
	public function system_status_report() {
		$table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() );
		$table->render();
	}

	/**
	 * Registers action-scheduler into WooCommerce > System status.
	 *
	 * @param array $tabs An associative array of tab key => label.
	 * @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs
	 */
	public function register_system_status_tab( array $tabs ) {
		$tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' );

		return $tabs;
	}

	/**
	 * Include Action Scheduler's administration under the Tools menu.
	 *
	 * A menu under the Tools menu is important for backward compatibility (as that's
	 * where it started), and also provides more convenient access than the WooCommerce
	 * System Status page, and for sites where WooCommerce isn't active.
	 */
	public function register_menu() {
		$hook_suffix = add_submenu_page(
			'tools.php',
			__( 'Scheduled Actions', 'action-scheduler' ),
			__( 'Scheduled Actions', 'action-scheduler' ),
			'manage_options',
			'action-scheduler',
			array( $this, 'render_admin_ui' )
		);
		add_action( 'load-' . $hook_suffix, array( $this, 'process_admin_ui' ) );
	}

	/**
	 * Triggers processing of any pending actions.
	 */
	public function process_admin_ui() {
		$this->get_list_table();
	}

	/**
	 * Renders the Admin UI
	 */
	public function render_admin_ui() {
		$table = $this->get_list_table();
		$table->display_page();
	}

	/**
	 * Get the admin UI object and process any requested actions.
	 *
	 * @return ActionScheduler_ListTable
	 */
	protected function get_list_table() {
		if ( null === $this->list_table ) {
			$this->list_table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
			$this->list_table->process_actions();
		}

		return $this->list_table;
	}

	/**
	 * Action: admin_notices
	 *
	 * Maybe check past-due actions, and print notice.
	 *
	 * @uses $this->check_pastdue_actions()
	 */
	public function maybe_check_pastdue_actions() {

		// Filter to prevent checking actions (ex: inappropriate user).
		if ( ! apply_filters( 'action_scheduler_check_pastdue_actions', current_user_can( 'manage_options' ) ) ) {
			return;
		}

		// Get last check transient.
		$last_check = get_transient( 'action_scheduler_last_pastdue_actions_check' );

		// If transient exists, we're within interval, so bail.
		if ( ! empty( $last_check ) ) {
			return;
		}

		// Perform the check.
		$this->check_pastdue_actions();
	}

	/**
	 * Check past-due actions, and print notice.
	 */
	protected function check_pastdue_actions() {

		// Set thresholds.
		$threshold_seconds = (int) apply_filters( 'action_scheduler_pastdue_actions_seconds', DAY_IN_SECONDS );
		$threshold_min     = (int) apply_filters( 'action_scheduler_pastdue_actions_min', 1 );

		// Set fallback value for past-due actions count.
		$num_pastdue_actions = 0;

		// Allow third-parties to preempt the default check logic.
		$check = apply_filters( 'action_scheduler_pastdue_actions_check_pre', null );

		// If no third-party preempted and there are no past-due actions, return early.
		if ( ! is_null( $check ) ) {
			return;
		}

		// Scheduled actions query arguments.
		$query_args = array(
			'date'     => as_get_datetime_object( time() - $threshold_seconds ),
			'status'   => ActionScheduler_Store::STATUS_PENDING,
			'per_page' => $threshold_min,
		);

		// If no third-party preempted, run default check.
		if ( is_null( $check ) ) {
			$store               = ActionScheduler_Store::instance();
			$num_pastdue_actions = (int) $store->query_actions( $query_args, 'count' );

			// Check if past-due actions count is greater than or equal to threshold.
			$check = ( $num_pastdue_actions >= $threshold_min );
			$check = (bool) apply_filters( 'action_scheduler_pastdue_actions_check', $check, $num_pastdue_actions, $threshold_seconds, $threshold_min );
		}

		// If check failed, set transient and abort.
		if ( ! boolval( $check ) ) {
			$interval = apply_filters( 'action_scheduler_pastdue_actions_check_interval', round( $threshold_seconds / 4 ), $threshold_seconds );
			set_transient( 'action_scheduler_last_pastdue_actions_check', time(), $interval );

			return;
		}

		$actions_url = add_query_arg(
			array(
				'page'   => 'action-scheduler',
				'status' => 'past-due',
				'order'  => 'asc',
			),
			admin_url( 'tools.php' )
		);

		// Print notice.
		echo '<div class="notice notice-warning"><p>';
		printf(
			wp_kses(
				// translators: 1) is the number of affected actions, 2) is a link to an admin screen.
				_n(
					'<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due action</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation &raquo;</a>',
					'<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due actions</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation &raquo;</a>',
					$num_pastdue_actions,
					'action-scheduler'
				),
				array(
					'strong' => array(),
					'a'      => array(
						'href'   => true,
						'target' => true,
					),
				)
			),
			absint( $num_pastdue_actions ),
			esc_attr( esc_url( $actions_url ) )
		);
		echo '</p></div>';

		// Facilitate third-parties to evaluate and print notices.
		do_action( 'action_scheduler_pastdue_actions_extra_notices', $query_args );
	}

	/**
	 * Provide more information about the screen and its data in the help tab.
	 */
	public function add_help_tabs() {
		$screen = get_current_screen();

		if ( ! $screen || self::$screen_id !== $screen->id ) {
			return;
		}

		$as_version       = ActionScheduler_Versions::instance()->latest_version();
		$as_source        = ActionScheduler_SystemInformation::active_source();
		$as_source_path   = ActionScheduler_SystemInformation::active_source_path();
		$as_source_markup = sprintf( '<code>%s</code>', esc_html( $as_source_path ) );

		if ( ! empty( $as_source ) ) {
			$as_source_markup = sprintf(
				'%s: <abbr title="%s">%s</abbr>',
				ucfirst( $as_source['type'] ),
				esc_attr( $as_source_path ),
				esc_html( $as_source['name'] )
			);
		}

		$screen->add_help_tab(
			array(
				'id'      => 'action_scheduler_about',
				'title'   => __( 'About', 'action-scheduler' ),
				'content' =>
					// translators: %s is the Action Scheduler version.
					'<h2>' . sprintf( __( 'About Action Scheduler %s', 'action-scheduler' ), $as_version ) . '</h2>' .
					'<p>' .
						__( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) .
					'</p>' .
					'<h3>' . esc_html__( 'Source', 'action-scheduler' ) . '</h3>' .
					'<p>' .
						esc_html__( 'Action Scheduler is currently being loaded from the following location. This can be useful when debugging, or if requested by the support team.', 'action-scheduler' ) .
					'</p>' .
					'<p>' . $as_source_markup . '</p>' .
					'<h3>' . esc_html__( 'WP CLI', 'action-scheduler' ) . '</h3>' .
					'<p>' .
						sprintf(
							/* translators: %1$s is WP CLI command (not translatable) */
							esc_html__( 'WP CLI commands are available: execute %1$s for a list of available commands.', 'action-scheduler' ),
							'<code>wp help action-scheduler</code>'
						) .
					'</p>',
			)
		);

		$screen->add_help_tab(
			array(
				'id'      => 'action_scheduler_columns',
				'title'   => __( 'Columns', 'action-scheduler' ),
				'content' =>
					'<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' .
					'<ul>' .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) .
					sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) .
					'</ul>',
			)
		);
	}
}
WP_CLI/Action_Command.php000066600000020224151137657220011162 0ustar00<?php

namespace Action_Scheduler\WP_CLI;

/**
 * Action command for Action Scheduler.
 */
class Action_Command extends \WP_CLI_Command {

	/**
	 * Cancel the next occurrence or all occurrences of a scheduled action.
	 *
	 * ## OPTIONS
	 *
	 * [<hook>]
	 * : Name of the action hook.
	 *
	 * [--group=<group>]
	 * : The group the job is assigned to.
	 *
	 * [--args=<args>]
	 * : JSON object of arguments assigned to the job.
	 * ---
	 * default: []
	 * ---
	 *
	 * [--all]
	 * : Cancel all occurrences of a scheduled action.
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function cancel( array $args, array $assoc_args ) {
		require_once 'Action/Cancel_Command.php';
		$command = new Action\Cancel_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Creates a new scheduled action.
	 *
	 * ## OPTIONS
	 *
	 * <hook>
	 * : Name of the action hook.
	 *
	 * <start>
	 * : A unix timestamp representing the date you want the action to start. Also 'async' or 'now' to enqueue an async action.
	 *
	 * [--args=<args>]
	 * : JSON object of arguments to pass to callbacks when the hook triggers.
	 * ---
	 * default: []
	 * ---
	 *
	 * [--cron=<cron>]
	 * : A cron-like schedule string (https://crontab.guru/).
	 * ---
	 * default: ''
	 * ---
	 *
	 * [--group=<group>]
	 * : The group to assign this job to.
	 * ---
	 * default: ''
	 * ---
	 *
	 * [--interval=<interval>]
	 * : Number of seconds to wait between runs.
	 * ---
	 * default: 0
	 * ---
	 *
	 * ## EXAMPLES
	 *
	 *     wp action-scheduler action create hook_async async
	 *     wp action-scheduler action create hook_single 1627147598
	 *     wp action-scheduler action create hook_recurring 1627148188 --interval=5
	 *     wp action-scheduler action create hook_cron 1627147655 --cron='5 4 * * *'
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function create( array $args, array $assoc_args ) {
		require_once 'Action/Create_Command.php';
		$command = new Action\Create_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Delete existing scheduled action(s).
	 *
	 * ## OPTIONS
	 *
	 * <id>...
	 * : One or more IDs of actions to delete.
	 * ---
	 * default: 0
	 * ---
	 *
	 * ## EXAMPLES
	 *
	 *     # Delete the action with id 100
	 *     $ wp action-scheduler action delete 100
	 *
	 *     # Delete the actions with ids 100 and 200
	 *     $ wp action-scheduler action delete 100 200
	 *
	 *     # Delete the first five pending actions in 'action-scheduler' group
	 *     $ wp action-scheduler action delete $( wp action-scheduler action list --status=pending --group=action-scheduler --format=ids )
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function delete( array $args, array $assoc_args ) {
		require_once 'Action/Delete_Command.php';
		$command = new Action\Delete_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Generates some scheduled actions.
	 *
	 * ## OPTIONS
	 *
	 * <hook>
	 * : Name of the action hook.
	 *
	 * <start>
	 * : The Unix timestamp representing the date you want the action to start.
	 *
	 * [--count=<count>]
	 * : Number of actions to create.
	 * ---
	 * default: 1
	 * ---
	 *
	 * [--interval=<interval>]
	 * : Number of seconds to wait between runs.
	 * ---
	 * default: 0
	 * ---
	 *
	 * [--args=<args>]
	 * : JSON object of arguments to pass to callbacks when the hook triggers.
	 * ---
	 * default: []
	 * ---
	 *
	 * [--group=<group>]
	 * : The group to assign this job to.
	 * ---
	 * default: ''
	 * ---
	 *
	 * ## EXAMPLES
	 *
	 *     wp action-scheduler action generate test_multiple 1627147598 --count=5 --interval=5
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function generate( array $args, array $assoc_args ) {
		require_once 'Action/Generate_Command.php';
		$command = new Action\Generate_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Get details about a scheduled action.
	 *
	 * ## OPTIONS
	 *
	 * <id>
	 * : The ID of the action to get.
	 * ---
	 * default: 0
	 * ---
	 *
	 * [--field=<field>]
	 * : Instead of returning the whole action, returns the value of a single field.
	 *
	 * [--fields=<fields>]
	 * : Limit the output to specific fields (comma-separated). Defaults to all fields.
	 *
	 * [--format=<format>]
	 * : Render output in a particular format.
	 * ---
	 * default: table
	 * options:
	 *   - table
	 *   - csv
	 *   - json
	 *   - yaml
	 * ---
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function get( array $args, array $assoc_args ) {
		require_once 'Action/Get_Command.php';
		$command = new Action\Get_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Get a list of scheduled actions.
	 *
	 * Display actions based on all arguments supported by
	 * [as_get_scheduled_actions()](https://actionscheduler.org/api/#function-reference--as_get_scheduled_actions).
	 *
	 * ## OPTIONS
	 *
	 * [--<field>=<value>]
	 * : One or more arguments to pass to as_get_scheduled_actions().
	 *
	 * [--field=<field>]
	 * : Prints the value of a single property for each action.
	 *
	 * [--fields=<fields>]
	 * : Limit the output to specific object properties.
	 *
	 * [--format=<format>]
	 * : Render output in a particular format.
	 * ---
	 * default: table
	 * options:
	 *   - table
	 *   - csv
	 *   - ids
	 *   - json
	 *   - count
	 *   - yaml
	 * ---
	 *
	 * ## AVAILABLE FIELDS
	 *
	 * These fields will be displayed by default for each action:
	 *
	 * * id
	 * * hook
	 * * status
	 * * group
	 * * recurring
	 * * scheduled_date
	 *
	 * These fields are optionally available:
	 *
	 * * args
	 * * log_entries
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 *
	 * @subcommand list
	 */
	public function subcommand_list( array $args, array $assoc_args ) {
		require_once 'Action/List_Command.php';
		$command = new Action\List_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Get logs for a scheduled action.
	 *
	 * ## OPTIONS
	 *
	 * <id>
	 * : The ID of the action to get.
	 * ---
	 * default: 0
	 * ---
	 *
	 * @param array $args Positional arguments.
	 * @return void
	 */
	public function logs( array $args ) {
		$command = sprintf( 'action-scheduler action get %d --field=log_entries', $args[0] );
		WP_CLI::runcommand( $command );
	}

	/**
	 * Get the ID or timestamp of the next scheduled action.
	 *
	 * ## OPTIONS
	 *
	 * <hook>
	 * : The hook of the next scheduled action.
	 *
	 * [--args=<args>]
	 * : JSON object of arguments to search for next scheduled action.
	 * ---
	 * default: []
	 * ---
	 *
	 * [--group=<group>]
	 * : The group to which the next scheduled action is assigned.
	 * ---
	 * default: ''
	 * ---
	 *
	 * [--raw]
	 * : Display the raw output of as_next_scheduled_action() (timestamp or boolean).
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function next( array $args, array $assoc_args ) {
		require_once 'Action/Next_Command.php';
		$command = new Action\Next_Command( $args, $assoc_args );
		$command->execute();
	}

	/**
	 * Run existing scheduled action(s).
	 *
	 * ## OPTIONS
	 *
	 * <id>...
	 * : One or more IDs of actions to run.
	 * ---
	 * default: 0
	 * ---
	 *
	 * ## EXAMPLES
	 *
	 *     # Run the action with id 100
	 *     $ wp action-scheduler action run 100
	 *
	 *     # Run the actions with ids 100 and 200
	 *     $ wp action-scheduler action run 100 200
	 *
	 *     # Run the first five pending actions in 'action-scheduler' group
	 *     $ wp action-scheduler action run $( wp action-scheduler action list --status=pending --group=action-scheduler --format=ids )
	 *
	 * @param array $args       Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @return void
	 */
	public function run( array $args, array $assoc_args ) {
		require_once 'Action/Run_Command.php';
		$command = new Action\Run_Command( $args, $assoc_args );
		$command->execute();
	}

}
WP_CLI/ActionScheduler_WPCLI_Scheduler_command.php000066600000015307151137657220016023 0ustar00<?php

/**
 * Commands for Action Scheduler.
 */
class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {

	/**
	 * Force tables schema creation for Action Scheduler
	 *
	 * ## OPTIONS
	 *
	 * @param array $args Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 *
	 * @subcommand fix-schema
	 */
	public function fix_schema( $args, $assoc_args ) {
		$schema_classes = array( ActionScheduler_LoggerSchema::class, ActionScheduler_StoreSchema::class );

		foreach ( $schema_classes as $classname ) {
			if ( is_subclass_of( $classname, ActionScheduler_Abstract_Schema::class ) ) {
				$obj = new $classname();
				$obj->init();
				$obj->register_tables( true );

				WP_CLI::success(
					sprintf(
						/* translators: %s refers to the schema name*/
						__( 'Registered schema for %s', 'action-scheduler' ),
						$classname
					)
				);
			}
		}
	}

	/**
	 * Run the Action Scheduler
	 *
	 * ## OPTIONS
	 *
	 * [--batch-size=<size>]
	 * : The maximum number of actions to run. Defaults to 100.
	 *
	 * [--batches=<size>]
	 * : Limit execution to a number of batches. Defaults to 0, meaning batches will continue being executed until all actions are complete.
	 *
	 * [--cleanup-batch-size=<size>]
	 * : The maximum number of actions to clean up. Defaults to the value of --batch-size.
	 *
	 * [--hooks=<hooks>]
	 * : Only run actions with the specified hook. Omitting this option runs actions with any hook. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=hook_one,hook_two,hook_three`
	 *
	 * [--group=<group>]
	 * : Only run actions from the specified group. Omitting this option runs actions from all groups.
	 *
	 * [--exclude-groups=<groups>]
	 * : Run actions from all groups except the specified group(s). Define multiple groups as a comma separated string (without spaces), e.g. '--group_a,group_b'. This option is ignored when `--group` is used.
	 *
	 * [--free-memory-on=<count>]
	 * : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50.
	 *
	 * [--pause=<seconds>]
	 * : The number of seconds to pause when freeing memory. Default no pause.
	 *
	 * [--force]
	 * : Whether to force execution despite the maximum number of concurrent processes being exceeded.
	 *
	 * @param array $args Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @throws \WP_CLI\ExitException When an error occurs.
	 *
	 * @subcommand run
	 */
	public function run( $args, $assoc_args ) {
		// Handle passed arguments.
		$batch          = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 100 ) );
		$batches        = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) );
		$clean          = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'cleanup-batch-size', $batch ) );
		$hooks          = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) );
		$hooks          = array_filter( array_map( 'trim', $hooks ) );
		$group          = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' );
		$exclude_groups = \WP_CLI\Utils\get_flag_value( $assoc_args, 'exclude-groups', '' );
		$free_on        = \WP_CLI\Utils\get_flag_value( $assoc_args, 'free-memory-on', 50 );
		$sleep          = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 );
		$force          = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );

		ActionScheduler_DataController::set_free_ticks( $free_on );
		ActionScheduler_DataController::set_sleep_time( $sleep );

		$batches_completed = 0;
		$actions_completed = 0;
		$unlimited         = 0 === $batches;
		if ( is_callable( array( ActionScheduler::store(), 'set_claim_filter' ) ) ) {
			$exclude_groups = $this->parse_comma_separated_string( $exclude_groups );

			if ( ! empty( $exclude_groups ) ) {
				ActionScheduler::store()->set_claim_filter( 'exclude-groups', $exclude_groups );
			}
		}

		try {
			// Custom queue cleaner instance.
			$cleaner = new ActionScheduler_QueueCleaner( null, $clean );

			// Get the queue runner instance.
			$runner = new ActionScheduler_WPCLI_QueueRunner( null, null, $cleaner );

			// Determine how many tasks will be run in the first batch.
			$total = $runner->setup( $batch, $hooks, $group, $force );

			// Run actions for as long as possible.
			while ( $total > 0 ) {
				$this->print_total_actions( $total );
				$actions_completed += $runner->run();
				$batches_completed++;

				// Maybe set up tasks for the next batch.
				$total = ( $unlimited || $batches_completed < $batches ) ? $runner->setup( $batch, $hooks, $group, $force ) : 0;
			}
		} catch ( Exception $e ) {
			$this->print_error( $e );
		}

		$this->print_total_batches( $batches_completed );
		$this->print_success( $actions_completed );
	}

	/**
	 * Converts a string of comma-separated values into an array of those same values.
	 *
	 * @param string $string The string of one or more comma separated values.
	 *
	 * @return array
	 */
	private function parse_comma_separated_string( $string ): array {
		return array_filter( str_getcsv( $string ) );
	}

	/**
	 * Print WP CLI message about how many actions are about to be processed.
	 *
	 * @param int $total Number of actions found.
	 */
	protected function print_total_actions( $total ) {
		WP_CLI::log(
			sprintf(
				/* translators: %d refers to how many scheduled tasks were found to run */
				_n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ),
				$total
			)
		);
	}

	/**
	 * Print WP CLI message about how many batches of actions were processed.
	 *
	 * @param int $batches_completed Number of completed batches.
	 */
	protected function print_total_batches( $batches_completed ) {
		WP_CLI::log(
			sprintf(
				/* translators: %d refers to the total number of batches executed */
				_n( '%d batch executed.', '%d batches executed.', $batches_completed, 'action-scheduler' ),
				$batches_completed
			)
		);
	}

	/**
	 * Convert an exception into a WP CLI error.
	 *
	 * @param Exception $e The error object.
	 *
	 * @throws \WP_CLI\ExitException Under some conditions WP CLI may throw an exception.
	 */
	protected function print_error( Exception $e ) {
		WP_CLI::error(
			sprintf(
				/* translators: %s refers to the exception error message */
				__( 'There was an error running the action scheduler: %s', 'action-scheduler' ),
				$e->getMessage()
			)
		);
	}

	/**
	 * Print a success message with the number of completed actions.
	 *
	 * @param int $actions_completed Number of completed actions.
	 */
	protected function print_success( $actions_completed ) {
		WP_CLI::success(
			sprintf(
				/* translators: %d refers to the total number of tasks completed */
				_n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ),
				$actions_completed
			)
		);
	}
}
WP_CLI/Migration_Command.php000066600000011670151137657220011703 0ustar00<?php


namespace Action_Scheduler\WP_CLI;

use Action_Scheduler\Migration\Config;
use Action_Scheduler\Migration\Runner;
use Action_Scheduler\Migration\Scheduler;
use Action_Scheduler\Migration\Controller;
use WP_CLI;
use WP_CLI_Command;

/**
 * Class Migration_Command
 *
 * @package Action_Scheduler\WP_CLI
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class Migration_Command extends WP_CLI_Command {

	/**
	 * Number of actions migrated.
	 *
	 * @var int
	 */
	private $total_processed = 0;

	/**
	 * Register the command with WP-CLI
	 */
	public function register() {
		if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
			return;
		}

		WP_CLI::add_command(
			'action-scheduler migrate',
			array( $this, 'migrate' ),
			array(
				'shortdesc' => 'Migrates actions to the DB tables store',
				'synopsis'  => array(
					array(
						'type'        => 'assoc',
						'name'        => 'batch-size',
						'optional'    => true,
						'default'     => 100,
						'description' => 'The number of actions to process in each batch',
					),
					array(
						'type'        => 'assoc',
						'name'        => 'free-memory-on',
						'optional'    => true,
						'default'     => 50,
						'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory',
					),
					array(
						'type'        => 'assoc',
						'name'        => 'pause',
						'optional'    => true,
						'default'     => 0,
						'description' => 'The number of seconds to pause when freeing memory',
					),
					array(
						'type'        => 'flag',
						'name'        => 'dry-run',
						'optional'    => true,
						'description' => 'Reports on the actions that would have been migrated, but does not change any data',
					),
				),
			)
		);
	}

	/**
	 * Process the data migration.
	 *
	 * @param array $positional_args Required for WP CLI. Not used in migration.
	 * @param array $assoc_args Optional arguments.
	 *
	 * @return void
	 */
	public function migrate( $positional_args, $assoc_args ) {
		$this->init_logging();

		$config = $this->get_migration_config( $assoc_args );
		$runner = new Runner( $config );
		$runner->init_destination();

		$batch_size = isset( $assoc_args['batch-size'] ) ? (int) $assoc_args['batch-size'] : 100;
		$free_on    = isset( $assoc_args['free-memory-on'] ) ? (int) $assoc_args['free-memory-on'] : 50;
		$sleep      = isset( $assoc_args['pause'] ) ? (int) $assoc_args['pause'] : 0;
		\ActionScheduler_DataController::set_free_ticks( $free_on );
		\ActionScheduler_DataController::set_sleep_time( $sleep );

		do {
			$actions_processed      = $runner->run( $batch_size );
			$this->total_processed += $actions_processed;
		} while ( $actions_processed > 0 );

		if ( ! $config->get_dry_run() ) {
			// let the scheduler know that there's nothing left to do.
			$scheduler = new Scheduler();
			$scheduler->mark_complete();
		}

		WP_CLI::success( sprintf( '%s complete. %d actions processed.', $config->get_dry_run() ? 'Dry run' : 'Migration', $this->total_processed ) );
	}

	/**
	 * Build the config object used to create the Runner
	 *
	 * @param array $args Optional arguments.
	 *
	 * @return ActionScheduler\Migration\Config
	 */
	private function get_migration_config( $args ) {
		$args = wp_parse_args(
			$args,
			array(
				'dry-run' => false,
			)
		);

		$config = Controller::instance()->get_migration_config_object();
		$config->set_dry_run( ! empty( $args['dry-run'] ) );

		return $config;
	}

	/**
	 * Hook command line logging into migration actions.
	 */
	private function init_logging() {
		add_action(
			'action_scheduler/migrate_action_dry_run',
			function ( $action_id ) {
				WP_CLI::debug( sprintf( 'Dry-run: migrated action %d', $action_id ) );
			}
		);

		add_action(
			'action_scheduler/no_action_to_migrate',
			function ( $action_id ) {
				WP_CLI::debug( sprintf( 'No action found to migrate for ID %d', $action_id ) );
			}
		);

		add_action(
			'action_scheduler/migrate_action_failed',
			function ( $action_id ) {
				WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) );
			}
		);

		add_action(
			'action_scheduler/migrate_action_incomplete',
			function ( $source_id, $destination_id ) {
				WP_CLI::warning( sprintf( 'Unable to remove source action with ID %d after migrating to new ID %d', $source_id, $destination_id ) );
			},
			10,
			2
		);

		add_action(
			'action_scheduler/migrated_action',
			function ( $source_id, $destination_id ) {
				WP_CLI::debug( sprintf( 'Migrated source action with ID %d to new store with ID %d', $source_id, $destination_id ) );
			},
			10,
			2
		);

		add_action(
			'action_scheduler/migration_batch_starting',
			function ( $batch ) {
				WP_CLI::debug( 'Beginning migration of batch: ' . print_r( $batch, true ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
			}
		);

		add_action(
			'action_scheduler/migration_batch_complete',
			function ( $batch ) {
				WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) );
			}
		);
	}
}
WP_CLI/ActionScheduler_WPCLI_Clean_Command.php000066600000007363151137657220015072 0ustar00<?php

/**
 * Commands for Action Scheduler.
 */
class ActionScheduler_WPCLI_Clean_Command extends WP_CLI_Command {
	/**
	 * Run the Action Scheduler Queue Cleaner
	 *
	 * ## OPTIONS
	 *
	 * [--batch-size=<size>]
	 * : The maximum number of actions to delete per batch. Defaults to 20.
	 *
	 * [--batches=<size>]
	 * : Limit execution to a number of batches. Defaults to 0, meaning batches will continue all eligible actions are deleted.
	 *
	 * [--status=<status>]
	 * : Only clean actions with the specified status. Defaults to Canceled, Completed. Define multiple statuses as a comma separated string (without spaces), e.g. `--status=complete,failed,canceled`
	 *
	 * [--before=<datestring>]
	 * : Only delete actions with scheduled date older than this. Defaults to 31 days. e.g `--before='7 days ago'`, `--before='02-Feb-2020 20:20:20'`
	 *
	 * [--pause=<seconds>]
	 * : The number of seconds to pause between batches. Default no pause.
	 *
	 * @param array $args Positional arguments.
	 * @param array $assoc_args Keyed arguments.
	 * @throws \WP_CLI\ExitException When an error occurs.
	 *
	 * @subcommand clean
	 */
	public function clean( $args, $assoc_args ) {
		// Handle passed arguments.
		$batch   = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 20 ) );
		$batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) );
		$status  = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'status', '' ) );
		$status  = array_filter( array_map( 'trim', $status ) );
		$before  = \WP_CLI\Utils\get_flag_value( $assoc_args, 'before', '' );
		$sleep   = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 );

		$batches_completed = 0;
		$actions_deleted   = 0;
		$unlimited         = 0 === $batches;
		try {
			$lifespan = as_get_datetime_object( $before );
		} catch ( Exception $e ) {
			$lifespan = null;
		}

		try {
			// Custom queue cleaner instance.
			$cleaner = new ActionScheduler_QueueCleaner( null, $batch );

			// Clean actions for as long as possible.
			while ( $unlimited || $batches_completed < $batches ) {
				if ( $sleep && $batches_completed > 0 ) {
					sleep( $sleep );
				}

				$deleted = count( $cleaner->clean_actions( $status, $lifespan, null, 'CLI' ) );
				if ( $deleted <= 0 ) {
					break;
				}
				$actions_deleted += $deleted;
				$batches_completed++;
				$this->print_success( $deleted );
			}
		} catch ( Exception $e ) {
			$this->print_error( $e );
		}

		$this->print_total_batches( $batches_completed );
		if ( $batches_completed > 1 ) {
			$this->print_success( $actions_deleted );
		}
	}

	/**
	 * Print WP CLI message about how many batches of actions were processed.
	 *
	 * @param int $batches_processed Number of batches processed.
	 */
	protected function print_total_batches( int $batches_processed ) {
		WP_CLI::log(
			sprintf(
				/* translators: %d refers to the total number of batches processed */
				_n( '%d batch processed.', '%d batches processed.', $batches_processed, 'action-scheduler' ),
				$batches_processed
			)
		);
	}

	/**
	 * Convert an exception into a WP CLI error.
	 *
	 * @param Exception $e The error object.
	 */
	protected function print_error( Exception $e ) {
		WP_CLI::error(
			sprintf(
				/* translators: %s refers to the exception error message */
				__( 'There was an error deleting an action: %s', 'action-scheduler' ),
				$e->getMessage()
			)
		);
	}

	/**
	 * Print a success message with the number of completed actions.
	 *
	 * @param int $actions_deleted Number of deleted actions.
	 */
	protected function print_success( int $actions_deleted ) {
		WP_CLI::success(
			sprintf(
				/* translators: %d refers to the total number of actions deleted */
				_n( '%d action deleted.', '%d actions deleted.', $actions_deleted, 'action-scheduler' ),
				$actions_deleted
			)
		);
	}
}
WP_CLI/System_Command.php000066600000016135151137657220011237 0ustar00<?php

namespace Action_Scheduler\WP_CLI;

// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI.

use ActionScheduler_SystemInformation;
use WP_CLI;
use function \WP_CLI\Utils\get_flag_value;

/**
 * System info WP-CLI commands for Action Scheduler.
 */
class System_Command {

	/**
	 * Data store for querying actions
	 *
	 * @var ActionScheduler_Store
	 */
	protected $store;

	/**
	 * Construct.
	 */
	public function __construct() {
		$this->store = \ActionScheduler::store();
	}

	/**
	 * Print in-use data store class.
	 *
	 * @param array $args       Positional args.
	 * @param array $assoc_args Keyed args.
	 * @return void
	 *
	 * @subcommand data-store
	 */
	public function datastore( array $args, array $assoc_args ) {
		echo $this->get_current_datastore();
	}

	/**
	 * Print in-use runner class.
	 *
	 * @param array $args       Positional args.
	 * @param array $assoc_args Keyed args.
	 * @return void
	 */
	public function runner( array $args, array $assoc_args ) {
		echo $this->get_current_runner();
	}

	/**
	 * Get system status.
	 *
	 * @param array $args       Positional args.
	 * @param array $assoc_args Keyed args.
	 * @return void
	 */
	public function status( array $args, array $assoc_args ) {
		/**
		 * Get runner status.
		 *
		 * @link https://github.com/woocommerce/action-scheduler-disable-default-runner
		 */
		$runner_enabled = has_action( 'action_scheduler_run_queue', array( \ActionScheduler::runner(), 'run' ) );

		\WP_CLI::line( sprintf( 'Data store: %s', $this->get_current_datastore() ) );
		\WP_CLI::line( sprintf( 'Runner: %s%s', $this->get_current_runner(), ( $runner_enabled ? '' : ' (disabled)' ) ) );
		\WP_CLI::line( sprintf( 'Version: %s', $this->get_latest_version() ) );

		$rows              = array();
		$action_counts     = $this->store->action_counts();
		$oldest_and_newest = $this->get_oldest_and_newest( array_keys( $action_counts ) );

		foreach ( $action_counts as $status => $count ) {
			$rows[] = array(
				'status' => $status,
				'count'  => $count,
				'oldest' => $oldest_and_newest[ $status ]['oldest'],
				'newest' => $oldest_and_newest[ $status ]['newest'],
			);
		}

		$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'status', 'count', 'oldest', 'newest' ) );
		$formatter->display_items( $rows );
	}

	/**
	 * Display the active version, or all registered versions.
	 *
	 * ## OPTIONS
	 *
	 * [--all]
	 * : List all registered versions.
	 *
	 * @param array $args       Positional args.
	 * @param array $assoc_args Keyed args.
	 * @return void
	 */
	public function version( array $args, array $assoc_args ) {
		$all    = (bool) get_flag_value( $assoc_args, 'all' );
		$latest = $this->get_latest_version();

		if ( ! $all ) {
			echo $latest;
			\WP_CLI::halt( 0 );
		}

		$instance = \ActionScheduler_Versions::instance();
		$versions = $instance->get_versions();
		$rows     = array();

		foreach ( $versions as $version => $callback ) {
			$active = $version === $latest;

			$rows[ $version ] = array(
				'version'  => $version,
				'callback' => $callback,
				'active'   => $active ? 'yes' : 'no',
			);
		}

		uksort( $rows, 'version_compare' );

		$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'version', 'callback', 'active' ) );
		$formatter->display_items( $rows );
	}

	/**
	 * Display the current source, or all registered sources.
	 *
	 * ## OPTIONS
	 *
	 * [--all]
	 * : List all registered sources.
	 *
	 * [--fullpath]
	 * : List full path of source(s).
	 *
	 * @param array $args       Positional args.
	 * @param array $assoc_args Keyed args.
	 * @uses ActionScheduler_SystemInformation::active_source_path()
	 * @uses \WP_CLI\Formatter::display_items()
	 * @uses $this->get_latest_version()
	 * @return void
	 */
	public function source( array $args, array $assoc_args ) {
		$all      = (bool) get_flag_value( $assoc_args, 'all' );
		$fullpath = (bool) get_flag_value( $assoc_args, 'fullpath' );
		$source   = ActionScheduler_SystemInformation::active_source_path();
		$path     = $source;

		if ( ! $fullpath ) {
			$path = str_replace( ABSPATH, '', $path );
		}

		if ( ! $all ) {
			echo $path;
			\WP_CLI::halt( 0 );
		}

		$sources = ActionScheduler_SystemInformation::get_sources();

		if ( empty( $sources ) ) {
			WP_CLI::log( __( 'Detailed information about registered sources is not currently available.', 'action-scheduler' ) );
			return;
		}

		$rows = array();

		foreach ( $sources as $check_source => $version ) {
			$active = dirname( $check_source ) === $source;
			$path   = $check_source;

			if ( ! $fullpath ) {
				$path = str_replace( ABSPATH, '', $path );
			}

			$rows[ $check_source ] = array(
				'source'  => $path,
				'version' => $version,
				'active'  => $active ? 'yes' : 'no',
			);
		}

		ksort( $rows );

		\WP_CLI::log( PHP_EOL . 'Please note there can only be one unique registered instance of Action Scheduler per ' . PHP_EOL . 'version number, so this list may not include all the currently present copies of ' . PHP_EOL . 'Action Scheduler.' . PHP_EOL );

		$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'source', 'version', 'active' ) );
		$formatter->display_items( $rows );
	}

	/**
	 * Get current data store.
	 *
	 * @return string
	 */
	protected function get_current_datastore() {
		return get_class( $this->store );
	}

	/**
	 * Get latest version.
	 *
	 * @param null|\ActionScheduler_Versions $instance Versions.
	 * @return string
	 */
	protected function get_latest_version( $instance = null ) {
		if ( is_null( $instance ) ) {
			$instance = \ActionScheduler_Versions::instance();
		}

		return $instance->latest_version();
	}

	/**
	 * Get current runner.
	 *
	 * @return string
	 */
	protected function get_current_runner() {
		return get_class( \ActionScheduler::runner() );
	}

	/**
	 * Get oldest and newest scheduled dates for a given set of statuses.
	 *
	 * @param array $status_keys Set of statuses to find oldest & newest action for.
	 * @return array
	 */
	protected function get_oldest_and_newest( $status_keys ) {
		$oldest_and_newest = array();

		foreach ( $status_keys as $status ) {
			$oldest_and_newest[ $status ] = array(
				'oldest' => '&ndash;',
				'newest' => '&ndash;',
			);

			if ( 'in-progress' === $status ) {
				continue;
			}

			$oldest_and_newest[ $status ]['oldest'] = $this->get_action_status_date( $status, 'oldest' );
			$oldest_and_newest[ $status ]['newest'] = $this->get_action_status_date( $status, 'newest' );
		}

		return $oldest_and_newest;
	}

	/**
	 * Get oldest or newest scheduled date for a given status.
	 *
	 * @param string $status Action status label/name string.
	 * @param string $date_type Oldest or Newest.
	 * @return string
	 */
	protected function get_action_status_date( $status, $date_type = 'oldest' ) {
		$order = 'oldest' === $date_type ? 'ASC' : 'DESC';

		$args = array(
			'claimed'  => false,
			'status'   => $status,
			'per_page' => 1,
			'order'    => $order,
		);

		$action = $this->store->query_actions( $args );

		if ( ! empty( $action ) ) {
			$date_object = $this->store->get_date( $action[0] );
			$action_date = $date_object->format( 'Y-m-d H:i:s O' );
		} else {
			$action_date = '&ndash;';
		}

		return $action_date;
	}

}
WP_CLI/Action/Create_Command.php000066600000010476151137657220012375 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

/**
 * WP-CLI command: action-scheduler action create
 */
class Create_Command extends \ActionScheduler_WPCLI_Command {

	const ASYNC_OPTS = array( 'async', 0 );

	/**
	 * Execute command.
	 *
	 * @return void
	 */
	public function execute() {
		$hook           = $this->args[0];
		$schedule_start = $this->args[1];
		$callback_args  = get_flag_value( $this->assoc_args, 'args', array() );
		$group          = get_flag_value( $this->assoc_args, 'group', '' );
		$interval       = absint( get_flag_value( $this->assoc_args, 'interval', 0 ) );
		$cron           = get_flag_value( $this->assoc_args, 'cron', '' );
		$unique         = get_flag_value( $this->assoc_args, 'unique', false );
		$priority       = absint( get_flag_value( $this->assoc_args, 'priority', 10 ) );

		if ( ! empty( $callback_args ) ) {
			$callback_args = json_decode( $callback_args, true );
		}

		$function_args = array(
			'start'         => $schedule_start,
			'cron'          => $cron,
			'interval'      => $interval,
			'hook'          => $hook,
			'callback_args' => $callback_args,
			'group'         => $group,
			'unique'        => $unique,
			'priority'      => $priority,
		);

		try {
			// Generate schedule start if appropriate.
			if ( ! in_array( $schedule_start, static::ASYNC_OPTS, true ) ) {
				$schedule_start         = as_get_datetime_object( $schedule_start );
				$function_args['start'] = $schedule_start->format( 'U' );
			}
		} catch ( \Exception $e ) {
			\WP_CLI::error( $e->getMessage() );
		}

		// Default to creating single action.
		$action_type = 'single';
		$function    = 'as_schedule_single_action';

		if ( ! empty( $interval ) ) { // Creating recurring action.
			$action_type = 'recurring';
			$function    = 'as_schedule_recurring_action';

			$function_args = array_filter(
				$function_args,
				static function( $key ) {
					return in_array( $key, array( 'start', 'interval', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
				},
				ARRAY_FILTER_USE_KEY
			);
		} elseif ( ! empty( $cron ) ) { // Creating cron action.
			$action_type = 'cron';
			$function    = 'as_schedule_cron_action';

			$function_args = array_filter(
				$function_args,
				static function( $key ) {
					return in_array( $key, array( 'start', 'cron', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
				},
				ARRAY_FILTER_USE_KEY
			);
		} elseif ( in_array( $function_args['start'], static::ASYNC_OPTS, true ) ) { // Enqueue async action.
			$action_type = 'async';
			$function    = 'as_enqueue_async_action';

			$function_args = array_filter(
				$function_args,
				static function( $key ) {
					return in_array( $key, array( 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
				},
				ARRAY_FILTER_USE_KEY
			);
		} else { // Enqueue single action.
			$function_args = array_filter(
				$function_args,
				static function( $key ) {
					return in_array( $key, array( 'start', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
				},
				ARRAY_FILTER_USE_KEY
			);
		}

		$function_args = array_values( $function_args );

		try {
			$action_id = call_user_func_array( $function, $function_args );
		} catch ( \Exception $e ) {
			$this->print_error( $e );
		}

		if ( 0 === $action_id ) {
			$e = new \Exception( __( 'Unable to create a scheduled action.', 'action-scheduler' ) );
			$this->print_error( $e );
		}

		$this->print_success( $action_id, $action_type );
	}

	/**
	 * Print a success message with the action ID.
	 *
	 * @param int    $action_id   Created action ID.
	 * @param string $action_type Type of action.
	 *
	 * @return void
	 */
	protected function print_success( $action_id, $action_type ) {
		\WP_CLI::success(
			sprintf(
				/* translators: %1$s: type of action, %2$d: ID of the created action */
				__( '%1$s action (%2$d) scheduled.', 'action-scheduler' ),
				ucfirst( $action_type ),
				$action_id
			)
		);
	}

	/**
	 * Convert an exception into a WP CLI error.
	 *
	 * @param \Exception $e The error object.
	 * @throws \WP_CLI\ExitException When an error occurs.
	 * @return void
	 */
	protected function print_error( \Exception $e ) {
		\WP_CLI::error(
			sprintf(
				/* translators: %s refers to the exception error message. */
				__( 'There was an error creating the scheduled action: %s', 'action-scheduler' ),
				$e->getMessage()
			)
		);
	}

}
WP_CLI/Action/List_Command.php000066600000006067151137657220012106 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI.

/**
 * WP-CLI command: action-scheduler action list
 */
class List_Command extends \ActionScheduler_WPCLI_Command {

	const PARAMETERS = array(
		'hook',
		'args',
		'date',
		'date_compare',
		'modified',
		'modified_compare',
		'group',
		'status',
		'claimed',
		'per_page',
		'offset',
		'orderby',
		'order',
	);

	/**
	 * Execute command.
	 *
	 * @return void
	 */
	public function execute() {
		$store  = \ActionScheduler::store();
		$logger = \ActionScheduler::logger();

		$fields = array(
			'id',
			'hook',
			'status',
			'group',
			'recurring',
			'scheduled_date',
		);

		$this->process_csv_arguments_to_arrays();

		if ( ! empty( $this->assoc_args['fields'] ) ) {
			$fields = $this->assoc_args['fields'];
		}

		$formatter  = new \WP_CLI\Formatter( $this->assoc_args, $fields );
		$query_args = $this->assoc_args;

		/**
		 * The `claimed` parameter expects a boolean or integer:
		 * check for string 'false', and set explicitly to `false` boolean.
		 */
		if ( array_key_exists( 'claimed', $query_args ) && 'false' === strtolower( $query_args['claimed'] ) ) {
			$query_args['claimed'] = false;
		}

		$return_format = 'OBJECT';

		if ( in_array( $formatter->format, array( 'ids', 'count' ), true ) ) {
			$return_format = '\'ids\'';
		}

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		$params = var_export( $query_args, true );

		if ( empty( $query_args ) ) {
			$params = 'array()';
		}

		\WP_CLI::debug(
			sprintf(
				'as_get_scheduled_actions( %s, %s )',
				$params,
				$return_format
			)
		);

		if ( ! empty( $query_args['args'] ) ) {
			$query_args['args'] = json_decode( $query_args['args'], true );
		}

		switch ( $formatter->format ) {

			case 'ids':
				$actions = as_get_scheduled_actions( $query_args, 'ids' );
				echo implode( ' ', $actions );
				break;

			case 'count':
				$actions = as_get_scheduled_actions( $query_args, 'ids' );
				$formatter->display_items( $actions );
				break;

			default:
				$actions = as_get_scheduled_actions( $query_args, OBJECT );

				$actions_arr = array();

				foreach ( $actions as $action_id => $action ) {
					$action_arr = array(
						'id'             => $action_id,
						'hook'           => $action->get_hook(),
						'status'         => $store->get_status( $action_id ),
						'args'           => $action->get_args(),
						'group'          => $action->get_group(),
						'recurring'      => $action->get_schedule()->is_recurring() ? 'yes' : 'no',
						'scheduled_date' => $this->get_schedule_display_string( $action->get_schedule() ),
						'log_entries'    => array(),
					);

					foreach ( $logger->get_logs( $action_id ) as $log_entry ) {
						$action_arr['log_entries'][] = array(
							'date'    => $log_entry->get_date()->format( static::DATE_FORMAT ),
							'message' => $log_entry->get_message(),
						);
					}

					$actions_arr[] = $action_arr;
				}

				$formatter->display_items( $actions_arr );
				break;

		}
	}

}
WP_CLI/Action/Delete_Command.php000066600000005145151137657220012371 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

/**
 * WP-CLI command: action-scheduler action delete
 */
class Delete_Command extends \ActionScheduler_WPCLI_Command {

	/**
	 * Array of action IDs to delete.
	 *
	 * @var int[]
	 */
	protected $action_ids = array();

	/**
	 * Number of deleted, failed, and total actions deleted.
	 *
	 * @var array<string, int>
	 */
	protected $action_counts = array(
		'deleted' => 0,
		'failed'  => 0,
		'total'   => 0,
	);

	/**
	 * Construct.
	 *
	 * @param string[]              $args       Positional arguments.
	 * @param array<string, string> $assoc_args Keyed arguments.
	 */
	public function __construct( array $args, array $assoc_args ) {
		parent::__construct( $args, $assoc_args );

		$this->action_ids             = array_map( 'absint', $args );
		$this->action_counts['total'] = count( $this->action_ids );

		add_action( 'action_scheduler_deleted_action', array( $this, 'on_action_deleted' ) );
	}

	/**
	 * Execute.
	 *
	 * @return void
	 */
	public function execute() {
		$store = \ActionScheduler::store();

		$progress_bar = \WP_CLI\Utils\make_progress_bar(
			sprintf(
				/* translators: %d: number of actions to be deleted */
				_n( 'Deleting %d action', 'Deleting %d actions', $this->action_counts['total'], 'action-scheduler' ),
				number_format_i18n( $this->action_counts['total'] )
			),
			$this->action_counts['total']
		);

		foreach ( $this->action_ids as $action_id ) {
			try {
				$store->delete_action( $action_id );
			} catch ( \Exception $e ) {
				$this->action_counts['failed']++;
				\WP_CLI::warning( $e->getMessage() );
			}

			$progress_bar->tick();
		}

		$progress_bar->finish();

		/* translators: %1$d: number of actions deleted */
		$format = _n( 'Deleted %1$d action', 'Deleted %1$d actions', $this->action_counts['deleted'], 'action-scheduler' ) . ', ';
		/* translators: %2$d: number of actions deletions failed */
		$format .= _n( '%2$d failure.', '%2$d failures.', $this->action_counts['failed'], 'action-scheduler' );

		\WP_CLI::success(
			sprintf(
				$format,
				number_format_i18n( $this->action_counts['deleted'] ),
				number_format_i18n( $this->action_counts['failed'] )
			)
		);
	}

	/**
	 * Action: action_scheduler_deleted_action
	 *
	 * @param int $action_id Action ID.
	 * @return void
	 */
	public function on_action_deleted( $action_id ) {
		if ( 'action_scheduler_deleted_action' !== current_action() ) {
			return;
		}

		$action_id = absint( $action_id );

		if ( ! in_array( $action_id, $this->action_ids, true ) ) {
			return;
		}

		$this->action_counts['deleted']++;
		\WP_CLI::debug( sprintf( 'Action %d was deleted.', $action_id ) );
	}

}
WP_CLI/Action/Get_Command.php000066600000004240151137657220011701 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

/**
 * WP-CLI command: action-scheduler action get
 */
class Get_Command extends \ActionScheduler_WPCLI_Command {

	/**
	 * Execute command.
	 *
	 * @return void
	 */
	public function execute() {
		$action_id = $this->args[0];
		$store     = \ActionScheduler::store();
		$logger    = \ActionScheduler::logger();
		$action    = $store->fetch_action( $action_id );

		if ( is_a( $action, ActionScheduler_NullAction::class ) ) {
			/* translators: %d is action ID. */
			\WP_CLI::error( sprintf( esc_html__( 'Unable to retrieve action %d.', 'action-scheduler' ), $action_id ) );
		}

		$only_logs   = ! empty( $this->assoc_args['field'] ) && 'log_entries' === $this->assoc_args['field'];
		$only_logs   = $only_logs || ( ! empty( $this->assoc_args['fields'] && 'log_entries' === $this->assoc_args['fields'] ) );
		$log_entries = array();

		foreach ( $logger->get_logs( $action_id ) as $log_entry ) {
			$log_entries[] = array(
				'date'    => $log_entry->get_date()->format( static::DATE_FORMAT ),
				'message' => $log_entry->get_message(),
			);
		}

		if ( $only_logs ) {
			$args = array(
				'format' => \WP_CLI\Utils\get_flag_value( $this->assoc_args, 'format', 'table' ),
			);

			$formatter = new \WP_CLI\Formatter( $args, array( 'date', 'message' ) );
			$formatter->display_items( $log_entries );

			return;
		}

		try {
			$status = $store->get_status( $action_id );
		} catch ( \Exception $e ) {
			\WP_CLI::error( $e->getMessage() );
		}

		$action_arr = array(
			'id'             => $this->args[0],
			'hook'           => $action->get_hook(),
			'status'         => $status,
			'args'           => $action->get_args(),
			'group'          => $action->get_group(),
			'recurring'      => $action->get_schedule()->is_recurring() ? 'yes' : 'no',
			'scheduled_date' => $this->get_schedule_display_string( $action->get_schedule() ),
			'log_entries'    => $log_entries,
		);

		$fields = array_keys( $action_arr );

		if ( ! empty( $this->assoc_args['fields'] ) ) {
			$fields = explode( ',', $this->assoc_args['fields'] );
		}

		$formatter = new \WP_CLI\Formatter( $this->assoc_args, $fields );
		$formatter->display_item( $action_arr );
	}

}
WP_CLI/Action/Run_Command.php000066600000011161151137657220011726 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

/**
 * WP-CLI command: action-scheduler action run
 */
class Run_Command extends \ActionScheduler_WPCLI_Command {

	/**
	 * Array of action IDs to execute.
	 *
	 * @var int[]
	 */
	protected $action_ids = array();

	/**
	 * Number of executed, failed, ignored, invalid, and total actions.
	 *
	 * @var array<string, int>
	 */
	protected $action_counts = array(
		'executed' => 0,
		'failed'   => 0,
		'ignored'  => 0,
		'invalid'  => 0,
		'total'    => 0,
	);

	/**
	 * Construct.
	 *
	 * @param string[]              $args       Positional arguments.
	 * @param array<string, string> $assoc_args Keyed arguments.
	 */
	public function __construct( array $args, array $assoc_args ) {
		parent::__construct( $args, $assoc_args );

		$this->action_ids             = array_map( 'absint', $args );
		$this->action_counts['total'] = count( $this->action_ids );

		add_action( 'action_scheduler_execution_ignored', array( $this, 'on_action_ignored' ) );
		add_action( 'action_scheduler_after_execute', array( $this, 'on_action_executed' ) );
		add_action( 'action_scheduler_failed_execution', array( $this, 'on_action_failed' ), 10, 2 );
		add_action( 'action_scheduler_failed_validation', array( $this, 'on_action_invalid' ), 10, 2 );
	}

	/**
	 * Execute.
	 *
	 * @return void
	 */
	public function execute() {
		$runner = \ActionScheduler::runner();

		$progress_bar = \WP_CLI\Utils\make_progress_bar(
			sprintf(
				/* translators: %d: number of actions */
				_n( 'Executing %d action', 'Executing %d actions', $this->action_counts['total'], 'action-scheduler' ),
				number_format_i18n( $this->action_counts['total'] )
			),
			$this->action_counts['total']
		);

		foreach ( $this->action_ids as $action_id ) {
			$runner->process_action( $action_id, 'Action Scheduler CLI' );
			$progress_bar->tick();
		}

		$progress_bar->finish();

		foreach ( array(
			'ignored',
			'invalid',
			'failed',
		) as $type ) {
			$count = $this->action_counts[ $type ];

			if ( empty( $count ) ) {
				continue;
			}

			/*
			 * translators:
			 * %1$d: count of actions evaluated.
			 * %2$s: type of action evaluated.
			 */
			$format = _n( '%1$d action %2$s.', '%1$d actions %2$s.', $count, 'action-scheduler' );

			\WP_CLI::warning(
				sprintf(
					$format,
					number_format_i18n( $count ),
					$type
				)
			);
		}

		\WP_CLI::success(
			sprintf(
				/* translators: %d: number of executed actions */
				_n( 'Executed %d action.', 'Executed %d actions.', $this->action_counts['executed'], 'action-scheduler' ),
				number_format_i18n( $this->action_counts['executed'] )
			)
		);
	}

	/**
	 * Action: action_scheduler_execution_ignored
	 *
	 * @param int $action_id Action ID.
	 * @return void
	 */
	public function on_action_ignored( $action_id ) {
		if ( 'action_scheduler_execution_ignored' !== current_action() ) {
			return;
		}

		$action_id = absint( $action_id );

		if ( ! in_array( $action_id, $this->action_ids, true ) ) {
			return;
		}

		$this->action_counts['ignored']++;
		\WP_CLI::debug( sprintf( 'Action %d was ignored.', $action_id ) );
	}

	/**
	 * Action: action_scheduler_after_execute
	 *
	 * @param int $action_id Action ID.
	 * @return void
	 */
	public function on_action_executed( $action_id ) {
		if ( 'action_scheduler_after_execute' !== current_action() ) {
			return;
		}

		$action_id = absint( $action_id );

		if ( ! in_array( $action_id, $this->action_ids, true ) ) {
			return;
		}

		$this->action_counts['executed']++;
		\WP_CLI::debug( sprintf( 'Action %d was executed.', $action_id ) );
	}

	/**
	 * Action: action_scheduler_failed_execution
	 *
	 * @param int        $action_id Action ID.
	 * @param \Exception $e         Exception.
	 * @return void
	 */
	public function on_action_failed( $action_id, \Exception $e ) {
		if ( 'action_scheduler_failed_execution' !== current_action() ) {
			return;
		}

		$action_id = absint( $action_id );

		if ( ! in_array( $action_id, $this->action_ids, true ) ) {
			return;
		}

		$this->action_counts['failed']++;
		\WP_CLI::debug( sprintf( 'Action %d failed execution: %s', $action_id, $e->getMessage() ) );
	}

	/**
	 * Action: action_scheduler_failed_validation
	 *
	 * @param int        $action_id Action ID.
	 * @param \Exception $e         Exception.
	 * @return void
	 */
	public function on_action_invalid( $action_id, \Exception $e ) {
		if ( 'action_scheduler_failed_validation' !== current_action() ) {
			return;
		}

		$action_id = absint( $action_id );

		if ( ! in_array( $action_id, $this->action_ids, true ) ) {
			return;
		}

		$this->action_counts['invalid']++;
		\WP_CLI::debug( sprintf( 'Action %d failed validation: %s', $action_id, $e->getMessage() ) );
	}

}
WP_CLI/Action/Cancel_Command.php000066600000006410151137657220012350 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

use function \WP_CLI\Utils\get_flag_value;

/**
 * WP-CLI command: action-scheduler action cancel
 */
class Cancel_Command extends \ActionScheduler_WPCLI_Command {

	/**
	 * Execute command.
	 *
	 * @return void
	 */
	public function execute() {
		$hook          = '';
		$group         = get_flag_value( $this->assoc_args, 'group', '' );
		$callback_args = get_flag_value( $this->assoc_args, 'args', null );
		$all           = get_flag_value( $this->assoc_args, 'all', false );

		if ( ! empty( $this->args[0] ) ) {
			$hook = $this->args[0];
		}

		if ( ! empty( $callback_args ) ) {
			$callback_args = json_decode( $callback_args, true );
		}

		if ( $all ) {
			$this->cancel_all( $hook, $callback_args, $group );
			return;
		}

		$this->cancel_single( $hook, $callback_args, $group );
	}

	/**
	 * Cancel single action.
	 *
	 * @param string $hook The hook that the job will trigger.
	 * @param array  $callback_args Args that would have been passed to the job.
	 * @param string $group The group the job is assigned to.
	 * @return void
	 */
	protected function cancel_single( $hook, $callback_args, $group ) {
		if ( empty( $hook ) ) {
			\WP_CLI::error( __( 'Please specify hook of action to cancel.', 'action-scheduler' ) );
		}

		try {
			$result = as_unschedule_action( $hook, $callback_args, $group );
		} catch ( \Exception $e ) {
			$this->print_error( $e, false );
		}

		if ( null === $result ) {
			$e = new \Exception( __( 'Unable to cancel scheduled action: check the logs.', 'action-scheduler' ) );
			$this->print_error( $e, false );
		}

		$this->print_success( false );
	}

	/**
	 * Cancel all actions.
	 *
	 * @param string $hook The hook that the job will trigger.
	 * @param array  $callback_args Args that would have been passed to the job.
	 * @param string $group The group the job is assigned to.
	 * @return void
	 */
	protected function cancel_all( $hook, $callback_args, $group ) {
		if ( empty( $hook ) && empty( $group ) ) {
			\WP_CLI::error( __( 'Please specify hook and/or group of actions to cancel.', 'action-scheduler' ) );
		}

		try {
			$result = as_unschedule_all_actions( $hook, $callback_args, $group );
		} catch ( \Exception $e ) {
			$this->print_error( $e, $multiple );
		}

		/**
		 * Because as_unschedule_all_actions() does not provide a result,
		 * neither confirm or deny actions cancelled.
		 */
		\WP_CLI::success( __( 'Request to cancel scheduled actions completed.', 'action-scheduler' ) );
	}

	/**
	 * Print a success message.
	 *
	 * @return void
	 */
	protected function print_success() {
		\WP_CLI::success( __( 'Scheduled action cancelled.', 'action-scheduler' ) );
	}

	/**
	 * Convert an exception into a WP CLI error.
	 *
	 * @param \Exception $e The error object.
	 * @param bool       $multiple Boolean if multiple actions.
	 * @throws \WP_CLI\ExitException When an error occurs.
	 * @return void
	 */
	protected function print_error( \Exception $e, $multiple ) {
		\WP_CLI::error(
			sprintf(
				/* translators: %1$s: singular or plural %2$s: refers to the exception error message. */
				__( 'There was an error cancelling the %1$s: %2$s', 'action-scheduler' ),
				$multiple ? __( 'scheduled actions', 'action-scheduler' ) : __( 'scheduled action', 'action-scheduler' ),
				$e->getMessage()
			)
		);
	}

}
WP_CLI/Action/Next_Command.php000066600000003503151137657220012101 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI.

use function \WP_CLI\Utils\get_flag_value;

/**
 * WP-CLI command: action-scheduler action next
 */
class Next_Command extends \ActionScheduler_WPCLI_Command {

	/**
	 * Execute command.
	 *
	 * @return void
	 */
	public function execute() {
		$hook          = $this->args[0];
		$group         = get_flag_value( $this->assoc_args, 'group', '' );
		$callback_args = get_flag_value( $this->assoc_args, 'args', null );
		$raw           = (bool) get_flag_value( $this->assoc_args, 'raw', false );

		if ( ! empty( $callback_args ) ) {
			$callback_args = json_decode( $callback_args, true );
		}

		if ( $raw ) {
			\WP_CLI::line( as_next_scheduled_action( $hook, $callback_args, $group ) );
			return;
		}

		$params = array(
			'hook'    => $hook,
			'orderby' => 'date',
			'order'   => 'ASC',
			'group'   => $group,
		);

		if ( is_array( $callback_args ) ) {
			$params['args'] = $callback_args;
		}

		$params['status'] = \ActionScheduler_Store::STATUS_RUNNING;
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		\WP_CLI::debug( 'ActionScheduler()::store()->query_action( ' . var_export( $params, true ) . ' )' );

		$store     = \ActionScheduler::store();
		$action_id = $store->query_action( $params );

		if ( $action_id ) {
			echo $action_id;
			return;
		}

		$params['status'] = \ActionScheduler_Store::STATUS_PENDING;
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		\WP_CLI::debug( 'ActionScheduler()::store()->query_action( ' . var_export( $params, true ) . ' )' );

		$action_id = $store->query_action( $params );

		if ( $action_id ) {
			echo $action_id;
			return;
		}

		\WP_CLI::warning( 'No matching next action.' );
	}

}
WP_CLI/Action/Generate_Command.php000066600000006737151137657220012731 0ustar00<?php

namespace Action_Scheduler\WP_CLI\Action;

use function \WP_CLI\Utils\get_flag_value;

/**
 * WP-CLI command: action-scheduler action generate
 */
class Generate_Command extends \ActionScheduler_WPCLI_Command {

	/**
	 * Execute command.
	 *
	 * @return void
	 */
	public function execute() {
		$hook           = $this->args[0];
		$schedule_start = $this->args[1];
		$callback_args  = get_flag_value( $this->assoc_args, 'args', array() );
		$group          = get_flag_value( $this->assoc_args, 'group', '' );
		$interval       = (int) get_flag_value( $this->assoc_args, 'interval', 0 ); // avoid absint() to support negative intervals
		$count          = absint( get_flag_value( $this->assoc_args, 'count', 1 ) );

		if ( ! empty( $callback_args ) ) {
			$callback_args = json_decode( $callback_args, true );
		}

		$schedule_start = as_get_datetime_object( $schedule_start );

		$function_args = array(
			'start'         => absint( $schedule_start->format( 'U' ) ),
			'interval'      => $interval,
			'count'         => $count,
			'hook'          => $hook,
			'callback_args' => $callback_args,
			'group'         => $group,
		);

		$function_args = array_values( $function_args );

		try {
			$actions_added = $this->generate( ...$function_args );
		} catch ( \Exception $e ) {
			$this->print_error( $e );
		}

		$num_actions_added = count( (array) $actions_added );

		$this->print_success( $num_actions_added, 'single' );
	}

	/**
	 * Schedule multiple single actions.
	 *
	 * @param int    $schedule_start Starting timestamp of first action.
	 * @param int    $interval How long to wait between runs.
	 * @param int    $count Limit number of actions to schedule.
	 * @param string $hook The hook to trigger.
	 * @param array  $args Arguments to pass when the hook triggers.
	 * @param string $group The group to assign this job to.
	 * @return int[] IDs of actions added.
	 */
	protected function generate( $schedule_start, $interval, $count, $hook, array $args = array(), $group = '' ) {
		$actions_added = array();

		$progress_bar = \WP_CLI\Utils\make_progress_bar(
			sprintf(
				/* translators: %d is number of actions to create */
				_n( 'Creating %d action', 'Creating %d actions', $count, 'action-scheduler' ),
				number_format_i18n( $count )
			),
			$count
		);

		for ( $i = 0; $i < $count; $i++ ) {
			$actions_added[] = as_schedule_single_action( $schedule_start + ( $i * $interval ), $hook, $args, $group );
			$progress_bar->tick();
		}

		$progress_bar->finish();

		return $actions_added;
	}

	/**
	 * Print a success message with the action ID.
	 *
	 * @param int    $actions_added Number of actions generated.
	 * @param string $action_type   Type of actions scheduled.
	 * @return void
	 */
	protected function print_success( $actions_added, $action_type ) {
		\WP_CLI::success(
			sprintf(
				/* translators: %1$d refers to the total number of tasks added, %2$s is the action type */
				_n( '%1$d %2$s action scheduled.', '%1$d %2$s actions scheduled.', $actions_added, 'action-scheduler' ),
				number_format_i18n( $actions_added ),
				$action_type
			)
		);
	}

	/**
	 * Convert an exception into a WP CLI error.
	 *
	 * @param \Exception $e The error object.
	 * @throws \WP_CLI\ExitException When an error occurs.
	 * @return void
	 */
	protected function print_error( \Exception $e ) {
		\WP_CLI::error(
			sprintf(
				/* translators: %s refers to the exception error message. */
				__( 'There was an error creating the scheduled action: %s', 'action-scheduler' ),
				$e->getMessage()
			)
		);
	}

}
WP_CLI/ProgressBar.php000066600000005316151137657220010545 0ustar00<?php

namespace Action_Scheduler\WP_CLI;

/**
 * WP_CLI progress bar for Action Scheduler.
 */

/**
 * Class ProgressBar
 *
 * @package Action_Scheduler\WP_CLI
 *
 * @since 3.0.0
 *
 * @codeCoverageIgnore
 */
class ProgressBar {

	/**
	 * Current number of ticks.
	 *
	 * @var integer
	 */
	protected $total_ticks;

	/**
	 * Total number of ticks.
	 *
	 * @var integer
	 */
	protected $count;

	/**
	 * Progress bar update interval.
	 *
	 * @var integer
	 */
	protected $interval;

	/**
	 * Progress bar message.
	 *
	 * @var string
	 */
	protected $message;

	/**
	 * Instance.
	 *
	 * @var \cli\progress\Bar
	 */
	protected $progress_bar;

	/**
	 * ProgressBar constructor.
	 *
	 * @param string  $message    Text to display before the progress bar.
	 * @param integer $count      Total number of ticks to be performed.
	 * @param integer $interval   Optional. The interval in milliseconds between updates. Default 100.
	 *
	 * @throws \Exception When this is not run within WP CLI.
	 */
	public function __construct( $message, $count, $interval = 100 ) {
		if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
			/* translators: %s php class name */
			throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
		}

		$this->total_ticks = 0;
		$this->message     = $message;
		$this->count       = $count;
		$this->interval    = $interval;
	}

	/**
	 * Increment the progress bar ticks.
	 */
	public function tick() {
		if ( null === $this->progress_bar ) {
			$this->setup_progress_bar();
		}

		$this->progress_bar->tick();
		$this->total_ticks++;

		do_action( 'action_scheduler/progress_tick', $this->total_ticks ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
	}

	/**
	 * Get the progress bar tick count.
	 *
	 * @return int
	 */
	public function current() {
		return $this->progress_bar ? $this->progress_bar->current() : 0;
	}

	/**
	 * Finish the current progress bar.
	 */
	public function finish() {
		if ( null !== $this->progress_bar ) {
			$this->progress_bar->finish();
		}

		$this->progress_bar = null;
	}

	/**
	 * Set the message used when creating the progress bar.
	 *
	 * @param string $message The message to be used when the next progress bar is created.
	 */
	public function set_message( $message ) {
		$this->message = $message;
	}

	/**
	 * Set the count for a new progress bar.
	 *
	 * @param integer $count The total number of ticks expected to complete.
	 */
	public function set_count( $count ) {
		$this->count = $count;
		$this->finish();
	}

	/**
	 * Set up the progress bar.
	 */
	protected function setup_progress_bar() {
		$this->progress_bar = \WP_CLI\Utils\make_progress_bar(
			$this->message,
			$this->count,
			$this->interval
		);
	}
}
WP_CLI/ActionScheduler_WPCLI_QueueRunner.php000066600000014331151137657220014661 0ustar00<?php

use Action_Scheduler\WP_CLI\ProgressBar;

/**
 * WP CLI Queue runner.
 *
 * This class can only be called from within a WP CLI instance.
 */
class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner {

	/**
	 * Claimed actions.
	 *
	 * @var array
	 */
	protected $actions;

	/**
	 * ActionScheduler_ActionClaim instance.
	 *
	 * @var ActionScheduler_ActionClaim
	 */
	protected $claim;

	/**
	 * Progress bar instance.
	 *
	 * @var \cli\progress\Bar
	 */
	protected $progress_bar;

	/**
	 * ActionScheduler_WPCLI_QueueRunner constructor.
	 *
	 * @param ActionScheduler_Store|null             $store Store object.
	 * @param ActionScheduler_FatalErrorMonitor|null $monitor Monitor object.
	 * @param ActionScheduler_QueueCleaner|null      $cleaner Cleaner object.
	 *
	 * @throws Exception When this is not run within WP CLI.
	 */
	public function __construct( ?ActionScheduler_Store $store = null, ?ActionScheduler_FatalErrorMonitor $monitor = null, ?ActionScheduler_QueueCleaner $cleaner = null ) {
		if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
			/* translators: %s php class name */
			throw new Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
		}

		parent::__construct( $store, $monitor, $cleaner );
	}

	/**
	 * Set up the Queue before processing.
	 *
	 * @param int    $batch_size The batch size to process.
	 * @param array  $hooks      The hooks being used to filter the actions claimed in this batch.
	 * @param string $group      The group of actions to claim with this batch.
	 * @param bool   $force      Whether to force running even with too many concurrent processes.
	 *
	 * @return int The number of actions that will be run.
	 * @throws \WP_CLI\ExitException When there are too many concurrent batches.
	 */
	public function setup( $batch_size, $hooks = array(), $group = '', $force = false ) {
		$this->run_cleanup();
		$this->add_hooks();

		// Check to make sure there aren't too many concurrent processes running.
		if ( $this->has_maximum_concurrent_batches() ) {
			if ( $force ) {
				WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) );
			} else {
				WP_CLI::error( __( 'There are too many concurrent batches.', 'action-scheduler' ) );
			}
		}

		// Stake a claim and store it.
		$this->claim = $this->store->stake_claim( $batch_size, null, $hooks, $group );
		$this->monitor->attach( $this->claim );
		$this->actions = $this->claim->get_actions();

		return count( $this->actions );
	}

	/**
	 * Add our hooks to the appropriate actions.
	 */
	protected function add_hooks() {
		add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) );
		add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ), 10, 2 );
		add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 );
	}

	/**
	 * Set up the WP CLI progress bar.
	 */
	protected function setup_progress_bar() {
		$count              = count( $this->actions );
		$this->progress_bar = new ProgressBar(
			/* translators: %d: amount of actions */
			sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), $count ),
			$count
		);
	}

	/**
	 * Process actions in the queue.
	 *
	 * @param string $context Optional runner context. Default 'WP CLI'.
	 *
	 * @return int The number of actions processed.
	 */
	public function run( $context = 'WP CLI' ) {
		do_action( 'action_scheduler_before_process_queue' );
		$this->setup_progress_bar();
		foreach ( $this->actions as $action_id ) {
			// Error if we lost the claim.
			if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $this->claim->get_id() ), true ) ) {
				WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) );
				break;
			}

			$this->process_action( $action_id, $context );
			$this->progress_bar->tick();
		}

		$completed = $this->progress_bar->current();
		$this->progress_bar->finish();
		$this->store->release_claim( $this->claim );
		do_action( 'action_scheduler_after_process_queue' );

		return $completed;
	}

	/**
	 * Handle WP CLI message when the action is starting.
	 *
	 * @param int $action_id Action ID.
	 */
	public function before_execute( $action_id ) {
		/* translators: %s refers to the action ID */
		WP_CLI::log( sprintf( __( 'Started processing action %s', 'action-scheduler' ), $action_id ) );
	}

	/**
	 * Handle WP CLI message when the action has completed.
	 *
	 * @param int                         $action_id ActionID.
	 * @param null|ActionScheduler_Action $action The instance of the action. Default to null for backward compatibility.
	 */
	public function after_execute( $action_id, $action = null ) {
		// backward compatibility.
		if ( null === $action ) {
			$action = $this->store->fetch_action( $action_id );
		}
		/* translators: 1: action ID 2: hook name */
		WP_CLI::log( sprintf( __( 'Completed processing action %1$s with hook: %2$s', 'action-scheduler' ), $action_id, $action->get_hook() ) );
	}

	/**
	 * Handle WP CLI message when the action has failed.
	 *
	 * @param int       $action_id Action ID.
	 * @param Exception $exception Exception.
	 * @throws \WP_CLI\ExitException With failure message.
	 */
	public function action_failed( $action_id, $exception ) {
		WP_CLI::error(
			/* translators: 1: action ID 2: exception message */
			sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ),
			false
		);
	}

	/**
	 * Sleep and help avoid hitting memory limit
	 *
	 * @param int $sleep_time Amount of seconds to sleep.
	 * @deprecated 3.0.0
	 */
	protected function stop_the_insanity( $sleep_time = 0 ) {
		_deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' );

		ActionScheduler_DataController::free_memory();
	}

	/**
	 * Maybe trigger the stop_the_insanity() method to free up memory.
	 */
	protected function maybe_stop_the_insanity() {
		// The value returned by progress_bar->current() might be padded. Remove padding, and convert to int.
		$current_iteration = intval( trim( $this->progress_bar->current() ) );
		if ( 0 === $current_iteration % 50 ) {
			$this->stop_the_insanity();
		}
	}
}
abstracts/ActionScheduler_TimezoneHelper.php000066600000011415151137657220015350 0ustar00<?php

/**
 * Class ActionScheduler_TimezoneHelper
 */
abstract class ActionScheduler_TimezoneHelper {

	/**
	 * DateTimeZone object.
	 *
	 * @var null|DateTimeZone
	 */
	private static $local_timezone = null;

	/**
	 * Set a DateTime's timezone to the WordPress site's timezone, or a UTC offset
	 * if no timezone string is available.
	 *
	 * @since  2.1.0
	 *
	 * @param DateTime $date Timestamp.
	 * @return ActionScheduler_DateTime
	 */
	public static function set_local_timezone( DateTime $date ) {

		// Accept a DateTime for easier backward compatibility, even though we require methods on ActionScheduler_DateTime.
		if ( ! is_a( $date, 'ActionScheduler_DateTime' ) ) {
			$date = as_get_datetime_object( $date->format( 'U' ) );
		}

		if ( get_option( 'timezone_string' ) ) {
			$date->setTimezone( new DateTimeZone( self::get_local_timezone_string() ) );
		} else {
			$date->setUtcOffset( self::get_local_timezone_offset() );
		}

		return $date;
	}

	/**
	 * Helper to retrieve the timezone string for a site until a WP core method exists
	 * (see https://core.trac.wordpress.org/ticket/24730).
	 *
	 * Adapted from wc_timezone_string() and https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
	 *
	 * If no timezone string is set, and its not possible to match the UTC offset set for the site to a timezone
	 * string, then an empty string will be returned, and the UTC offset should be used to set a DateTime's
	 * timezone.
	 *
	 * @since 2.1.0
	 * @param bool $reset Unused.
	 * @return string PHP timezone string for the site or empty if no timezone string is available.
	 */
	protected static function get_local_timezone_string( $reset = false ) {
		// If site timezone string exists, return it.
		$timezone = get_option( 'timezone_string' );
		if ( $timezone ) {
			return $timezone;
		}

		// Get UTC offset, if it isn't set then return UTC.
		$utc_offset = intval( get_option( 'gmt_offset', 0 ) );
		if ( 0 === $utc_offset ) {
			return 'UTC';
		}

		// Adjust UTC offset from hours to seconds.
		$utc_offset *= 3600;

		// Attempt to guess the timezone string from the UTC offset.
		$timezone = timezone_name_from_abbr( '', $utc_offset );
		if ( $timezone ) {
			return $timezone;
		}

		// Last try, guess timezone string manually.
		foreach ( timezone_abbreviations_list() as $abbr ) {
			foreach ( $abbr as $city ) {
				if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) { // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date	 -- we are actually interested in the runtime timezone.
					return $city['timezone_id'];
				}
			}
		}

		// No timezone string.
		return '';
	}

	/**
	 * Get timezone offset in seconds.
	 *
	 * @since  2.1.0
	 * @return float
	 */
	protected static function get_local_timezone_offset() {
		$timezone = get_option( 'timezone_string' );

		if ( $timezone ) {
			$timezone_object = new DateTimeZone( $timezone );
			return $timezone_object->getOffset( new DateTime( 'now' ) );
		} else {
			return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
		}
	}

	/**
	 * Get local timezone.
	 *
	 * @param bool $reset Toggle to discard stored value.
	 * @deprecated 2.1.0
	 */
	public static function get_local_timezone( $reset = false ) {
		_deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' );
		if ( $reset ) {
			self::$local_timezone = null;
		}
		if ( ! isset( self::$local_timezone ) ) {
			$tzstring = get_option( 'timezone_string' );

			if ( empty( $tzstring ) ) {
				$gmt_offset = absint( get_option( 'gmt_offset' ) );
				if ( 0 === $gmt_offset ) {
					$tzstring = 'UTC';
				} else {
					$gmt_offset *= HOUR_IN_SECONDS;
					$tzstring    = timezone_name_from_abbr( '', $gmt_offset, 1 );

					// If there's no timezone string, try again with no DST.
					if ( false === $tzstring ) {
						$tzstring = timezone_name_from_abbr( '', $gmt_offset, 0 );
					}

					// Try mapping to the first abbreviation we can find.
					if ( false === $tzstring ) {
						$is_dst = date( 'I' ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date	 -- we are actually interested in the runtime timezone.
						foreach ( timezone_abbreviations_list() as $abbr ) {
							foreach ( $abbr as $city ) {
								if ( $city['dst'] === $is_dst && $city['offset'] === $gmt_offset ) {
									// If there's no valid timezone ID, keep looking.
									if ( is_null( $city['timezone_id'] ) ) {
										continue;
									}

									$tzstring = $city['timezone_id'];
									break 2;
								}
							}
						}
					}

					// If we still have no valid string, then fall back to UTC.
					if ( false === $tzstring ) {
						$tzstring = 'UTC';
					}
				}
			}

			self::$local_timezone = new DateTimeZone( $tzstring );
		}
		return self::$local_timezone;
	}
}
abstracts/ActionScheduler.php000066600000025610151137657220012340 0ustar00<?php

use Action_Scheduler\WP_CLI\Migration_Command;
use Action_Scheduler\Migration\Controller;

/**
 * Class ActionScheduler
 *
 * @codeCoverageIgnore
 */
abstract class ActionScheduler {

	/**
	 * Plugin file path.
	 *
	 * @var string
	 */
	private static $plugin_file = '';

	/**
	 * ActionScheduler_ActionFactory instance.
	 *
	 * @var ActionScheduler_ActionFactory
	 */
	private static $factory = null;

	/**
	 * Data store is initialized.
	 *
	 * @var bool
	 */
	private static $data_store_initialized = false;

	/**
	 * Factory.
	 */
	public static function factory() {
		if ( ! isset( self::$factory ) ) {
			self::$factory = new ActionScheduler_ActionFactory();
		}
		return self::$factory;
	}

	/**
	 * Get Store instance.
	 */
	public static function store() {
		return ActionScheduler_Store::instance();
	}

	/**
	 * Get Lock instance.
	 */
	public static function lock() {
		return ActionScheduler_Lock::instance();
	}

	/**
	 * Get Logger instance.
	 */
	public static function logger() {
		return ActionScheduler_Logger::instance();
	}

	/**
	 * Get QueueRunner instance.
	 */
	public static function runner() {
		return ActionScheduler_QueueRunner::instance();
	}

	/**
	 * Get AdminView instance.
	 */
	public static function admin_view() {
		return ActionScheduler_AdminView::instance();
	}

	/**
	 * Get the absolute system path to the plugin directory, or a file therein
	 *
	 * @static
	 * @param string $path Path relative to plugin directory.
	 * @return string
	 */
	public static function plugin_path( $path ) {
		$base = dirname( self::$plugin_file );
		if ( $path ) {
			return trailingslashit( $base ) . $path;
		} else {
			return untrailingslashit( $base );
		}
	}

	/**
	 * Get the absolute URL to the plugin directory, or a file therein
	 *
	 * @static
	 * @param string $path Path relative to plugin directory.
	 * @return string
	 */
	public static function plugin_url( $path ) {
		return plugins_url( $path, self::$plugin_file );
	}

	/**
	 * Autoload.
	 *
	 * @param string $class Class name.
	 */
	public static function autoload( $class ) {
		$d           = DIRECTORY_SEPARATOR;
		$classes_dir = self::plugin_path( 'classes' . $d );
		$separator   = strrpos( $class, '\\' );
		if ( false !== $separator ) {
			if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) {
				return;
			}
			$class = substr( $class, $separator + 1 );
		}

		if ( 'Deprecated' === substr( $class, -10 ) ) {
			$dir = self::plugin_path( 'deprecated' . $d );
		} elseif ( self::is_class_abstract( $class ) ) {
			$dir = $classes_dir . 'abstracts' . $d;
		} elseif ( self::is_class_migration( $class ) ) {
			$dir = $classes_dir . 'migration' . $d;
		} elseif ( 'Schedule' === substr( $class, -8 ) ) {
			$dir = $classes_dir . 'schedules' . $d;
		} elseif ( 'Action' === substr( $class, -6 ) ) {
			$dir = $classes_dir . 'actions' . $d;
		} elseif ( 'Schema' === substr( $class, -6 ) ) {
			$dir = $classes_dir . 'schema' . $d;
		} elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) {
			$segments = explode( '_', $class );
			$type     = isset( $segments[1] ) ? $segments[1] : '';

			switch ( $type ) {
				case 'WPCLI':
					$dir = $classes_dir . 'WP_CLI' . $d;
					break;
				case 'DBLogger':
				case 'DBStore':
				case 'HybridStore':
				case 'wpPostStore':
				case 'wpCommentLogger':
					$dir = $classes_dir . 'data-stores' . $d;
					break;
				default:
					$dir = $classes_dir;
					break;
			}
		} elseif ( self::is_class_cli( $class ) ) {
			$dir = $classes_dir . 'WP_CLI' . $d;
		} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
			$dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d );
		} elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) {
			$dir = self::plugin_path( 'lib' . $d );
		} else {
			return;
		}

		if ( file_exists( $dir . "{$class}.php" ) ) {
			include $dir . "{$class}.php";
			return;
		}
	}

	/**
	 * Initialize the plugin
	 *
	 * @static
	 * @param string $plugin_file Plugin file path.
	 */
	public static function init( $plugin_file ) {
		self::$plugin_file = $plugin_file;
		spl_autoload_register( array( __CLASS__, 'autoload' ) );

		/**
		 * Fires in the early stages of Action Scheduler init hook.
		 */
		do_action( 'action_scheduler_pre_init' );

		require_once self::plugin_path( 'functions.php' );
		ActionScheduler_DataController::init();

		$store      = self::store();
		$logger     = self::logger();
		$runner     = self::runner();
		$admin_view = self::admin_view();

		// Ensure initialization on plugin activation.
		if ( ! did_action( 'init' ) ) {
			// phpcs:ignore Squiz.PHP.CommentedOutCode
			add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init().
			add_action( 'init', array( $store, 'init' ), 1, 0 );
			add_action( 'init', array( $logger, 'init' ), 1, 0 );
			add_action( 'init', array( $runner, 'init' ), 1, 0 );

			add_action(
				'init',
				/**
				 * Runs after the active store's init() method has been called.
				 *
				 * It would probably be preferable to have $store->init() (or it's parent method) set this itself,
				 * once it has initialized, however that would cause problems in cases where a custom data store is in
				 * use and it has not yet been updated to follow that same logic.
				 */
				function () {
					self::$data_store_initialized = true;

					/**
					 * Fires when Action Scheduler is ready: it is safe to use the procedural API after this point.
					 *
					 * @since 3.5.5
					 */
					do_action( 'action_scheduler_init' );
				},
				1
			);
		} else {
			$admin_view->init();
			$store->init();
			$logger->init();
			$runner->init();
			self::$data_store_initialized = true;

			/**
			 * Fires when Action Scheduler is ready: it is safe to use the procedural API after this point.
			 *
			 * @since 3.5.5
			 */
			do_action( 'action_scheduler_init' );
		}

		if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) {
			require_once self::plugin_path( 'deprecated/functions.php' );
		}

		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
			WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Clean_Command' );
			WP_CLI::add_command( 'action-scheduler action', '\Action_Scheduler\WP_CLI\Action_Command' );
			WP_CLI::add_command( 'action-scheduler', '\Action_Scheduler\WP_CLI\System_Command' );
			if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) {
				$command = new Migration_Command();
				$command->register();
			}
		}

		/**
		 * Handle WP comment cleanup after migration.
		 */
		if ( is_a( $logger, 'ActionScheduler_DBLogger' ) && ActionScheduler_DataController::is_migration_complete() && ActionScheduler_WPCommentCleaner::has_logs() ) {
			ActionScheduler_WPCommentCleaner::init();
		}

		add_action( 'action_scheduler/migration_complete', 'ActionScheduler_WPCommentCleaner::maybe_schedule_cleanup' );
	}

	/**
	 * Check whether the AS data store has been initialized.
	 *
	 * @param string $function_name The name of the function being called. Optional. Default `null`.
	 * @return bool
	 */
	public static function is_initialized( $function_name = null ) {
		if ( ! self::$data_store_initialized && ! empty( $function_name ) ) {
			$message = sprintf(
				/* translators: %s function name. */
				__( '%s() was called before the Action Scheduler data store was initialized', 'action-scheduler' ),
				esc_attr( $function_name )
			);
			_doing_it_wrong( esc_html( $function_name ), esc_html( $message ), '3.1.6' );
		}

		return self::$data_store_initialized;
	}

	/**
	 * Determine if the class is one of our abstract classes.
	 *
	 * @since 3.0.0
	 *
	 * @param string $class The class name.
	 *
	 * @return bool
	 */
	protected static function is_class_abstract( $class ) {
		static $abstracts = array(
			'ActionScheduler'                            => true,
			'ActionScheduler_Abstract_ListTable'         => true,
			'ActionScheduler_Abstract_QueueRunner'       => true,
			'ActionScheduler_Abstract_Schedule'          => true,
			'ActionScheduler_Abstract_RecurringSchedule' => true,
			'ActionScheduler_Lock'                       => true,
			'ActionScheduler_Logger'                     => true,
			'ActionScheduler_Abstract_Schema'            => true,
			'ActionScheduler_Store'                      => true,
			'ActionScheduler_TimezoneHelper'             => true,
			'ActionScheduler_WPCLI_Command'              => true,
		);

		return isset( $abstracts[ $class ] ) && $abstracts[ $class ];
	}

	/**
	 * Determine if the class is one of our migration classes.
	 *
	 * @since 3.0.0
	 *
	 * @param string $class The class name.
	 *
	 * @return bool
	 */
	protected static function is_class_migration( $class ) {
		static $migration_segments = array(
			'ActionMigrator'  => true,
			'BatchFetcher'    => true,
			'DBStoreMigrator' => true,
			'DryRun'          => true,
			'LogMigrator'     => true,
			'Config'          => true,
			'Controller'      => true,
			'Runner'          => true,
			'Scheduler'       => true,
		);

		$segments = explode( '_', $class );
		$segment  = isset( $segments[1] ) ? $segments[1] : $class;

		return isset( $migration_segments[ $segment ] ) && $migration_segments[ $segment ];
	}

	/**
	 * Determine if the class is one of our WP CLI classes.
	 *
	 * @since 3.0.0
	 *
	 * @param string $class The class name.
	 *
	 * @return bool
	 */
	protected static function is_class_cli( $class ) {
		static $cli_segments = array(
			'QueueRunner'                             => true,
			'Command'                                 => true,
			'ProgressBar'                             => true,
			'\Action_Scheduler\WP_CLI\Action_Command' => true,
			'\Action_Scheduler\WP_CLI\System_Command' => true,
		);

		$segments = explode( '_', $class );
		$segment  = isset( $segments[1] ) ? $segments[1] : $class;

		return isset( $cli_segments[ $segment ] ) && $cli_segments[ $segment ];
	}

	/**
	 * Clone.
	 */
	final public function __clone() {
		trigger_error( 'Singleton. No cloning allowed!', E_USER_ERROR ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
	}

	/**
	 * Wakeup.
	 */
	final public function __wakeup() {
		trigger_error( 'Singleton. No serialization allowed!', E_USER_ERROR ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
	}

	/**
	 * Construct.
	 */
	final private function __construct() {}

	/** Deprecated **/

	/**
	 * Get DateTime object.
	 *
	 * @param null|string $when     Date/time string.
	 * @param string      $timezone Timezone string.
	 */
	public static function get_datetime_object( $when = null, $timezone = 'UTC' ) {
		_deprecated_function( __METHOD__, '2.0', 'wcs_add_months()' );
		return as_get_datetime_object( $when, $timezone );
	}

	/**
	 * Issue deprecated warning if an Action Scheduler function is called in the shutdown hook.
	 *
	 * @param string $function_name The name of the function being called.
	 * @deprecated 3.1.6.
	 */
	public static function check_shutdown_hook( $function_name ) {
		_deprecated_function( __FUNCTION__, '3.1.6' );
	}
}
abstracts/ActionScheduler_Abstract_QueueRunner.php000066600000032710151137657220016520 0ustar00<?php

/**
 * Abstract class with common Queue Cleaner functionality.
 */
abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abstract_QueueRunner_Deprecated {

	/**
	 * ActionScheduler_QueueCleaner instance.
	 *
	 * @var ActionScheduler_QueueCleaner
	 */
	protected $cleaner;

	/**
	 * ActionScheduler_FatalErrorMonitor instance.
	 *
	 * @var ActionScheduler_FatalErrorMonitor
	 */
	protected $monitor;

	/**
	 * ActionScheduler_Store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	protected $store;

	/**
	 * The created time.
	 *
	 * Represents when the queue runner was constructed and used when calculating how long a PHP request has been running.
	 * For this reason it should be as close as possible to the PHP request start time.
	 *
	 * @var int
	 */
	private $created_time;

	/**
	 * ActionScheduler_Abstract_QueueRunner constructor.
	 *
	 * @param ActionScheduler_Store|null             $store Store object.
	 * @param ActionScheduler_FatalErrorMonitor|null $monitor Monitor object.
	 * @param ActionScheduler_QueueCleaner|null      $cleaner Cleaner object.
	 */
	public function __construct( ?ActionScheduler_Store $store = null, ?ActionScheduler_FatalErrorMonitor $monitor = null, ?ActionScheduler_QueueCleaner $cleaner = null ) {

		$this->created_time = microtime( true );

		$this->store   = $store ? $store : ActionScheduler_Store::instance();
		$this->monitor = $monitor ? $monitor : new ActionScheduler_FatalErrorMonitor( $this->store );
		$this->cleaner = $cleaner ? $cleaner : new ActionScheduler_QueueCleaner( $this->store );
	}

	/**
	 * Process an individual action.
	 *
	 * @param int    $action_id The action ID to process.
	 * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
	 *                        Generally, this should be capitalised and not localised as it's a proper noun.
	 * @throws \Exception When error running action.
	 */
	public function process_action( $action_id, $context = '' ) {
		// Temporarily override the error handler while we process the current action.
		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
		set_error_handler(
			/**
			 * Temporary error handler which can catch errors and convert them into exceptions. This facilitates more
			 * robust error handling across all supported PHP versions.
			 *
			 * @throws Exception
			 *
			 * @param int    $type    Error level expressed as an integer.
			 * @param string $message Error message.
			 */
			function ( $type, $message ) {
				throw new Exception( $message );
			},
			E_USER_ERROR | E_RECOVERABLE_ERROR
		);

		/*
		 * The nested try/catch structure is required because we potentially need to convert thrown errors into
		 * exceptions (and an exception thrown from a catch block cannot be caught by a later catch block in the *same*
		 * structure).
		 */
		try {
			try {
				$valid_action = false;
				do_action( 'action_scheduler_before_execute', $action_id, $context );

				if ( ActionScheduler_Store::STATUS_PENDING !== $this->store->get_status( $action_id ) ) {
					do_action( 'action_scheduler_execution_ignored', $action_id, $context );
					return;
				}

				$valid_action = true;
				do_action( 'action_scheduler_begin_execute', $action_id, $context );

				$action = $this->store->fetch_action( $action_id );
				$this->store->log_execution( $action_id );
				$action->execute();
				do_action( 'action_scheduler_after_execute', $action_id, $action, $context );
				$this->store->mark_complete( $action_id );
			} catch ( Throwable $e ) {
				// Throwable is defined when executing under PHP 7.0 and up. We convert it to an exception, for
				// compatibility with ActionScheduler_Logger.
				throw new Exception( $e->getMessage(), $e->getCode(), $e );
			}
		} catch ( Exception $e ) {
			// This catch block exists for compatibility with PHP 5.6.
			$this->handle_action_error( $action_id, $e, $context, $valid_action );
		} finally {
			restore_error_handler();
		}

		if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
			$this->schedule_next_instance( $action, $action_id );
		}
	}

	/**
	 * Marks actions as either having failed execution or failed validation, as appropriate.
	 *
	 * @param int       $action_id    Action ID.
	 * @param Exception $e            Exception instance.
	 * @param string    $context      Execution context.
	 * @param bool      $valid_action If the action is valid.
	 *
	 * @return void
	 */
	private function handle_action_error( $action_id, $e, $context, $valid_action ) {
		if ( $valid_action ) {
			$this->store->mark_failure( $action_id );
			/**
			 * Runs when action execution fails.
			 *
			 * @param int       $action_id Action ID.
			 * @param Exception $e         Exception instance.
			 * @param string    $context   Execution context.
			 */
			do_action( 'action_scheduler_failed_execution', $action_id, $e, $context );
		} else {
			/**
			 * Runs when action validation fails.
			 *
			 * @param int       $action_id Action ID.
			 * @param Exception $e         Exception instance.
			 * @param string    $context   Execution context.
			 */
			do_action( 'action_scheduler_failed_validation', $action_id, $e, $context );
		}
	}

	/**
	 * Schedule the next instance of the action if necessary.
	 *
	 * @param ActionScheduler_Action $action Action.
	 * @param int                    $action_id Action ID.
	 */
	protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) {
		// If a recurring action has been consistently failing, we may wish to stop rescheduling it.
		if (
			ActionScheduler_Store::STATUS_FAILED === $this->store->get_status( $action_id )
			&& $this->recurring_action_is_consistently_failing( $action, $action_id )
		) {
			ActionScheduler_Logger::instance()->log(
				$action_id,
				__( 'This action appears to be consistently failing. A new instance will not be scheduled.', 'action-scheduler' )
			);

			return;
		}

		try {
			ActionScheduler::factory()->repeat( $action );
		} catch ( Exception $e ) {
			do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action );
		}
	}

	/**
	 * Determine if the specified recurring action has been consistently failing.
	 *
	 * @param ActionScheduler_Action $action    The recurring action to be rescheduled.
	 * @param int                    $action_id The ID of the recurring action.
	 *
	 * @return bool
	 */
	private function recurring_action_is_consistently_failing( ActionScheduler_Action $action, $action_id ) {
		/**
		 * Controls the failure threshold for recurring actions.
		 *
		 * Before rescheduling a recurring action, we look at its status. If it failed, we then check if all of the most
		 * recent actions (upto the threshold set by this filter) sharing the same hook have also failed: if they have,
		 * that is considered consistent failure and a new instance of the action will not be scheduled.
		 *
		 * @param int $failure_threshold Number of actions of the same hook to examine for failure. Defaults to 5.
		 */
		$consistent_failure_threshold = (int) apply_filters( 'action_scheduler_recurring_action_failure_threshold', 5 );

		// This query should find the earliest *failing* action (for the hook we are interested in) within our threshold.
		$query_args = array(
			'hook'         => $action->get_hook(),
			'status'       => ActionScheduler_Store::STATUS_FAILED,
			'date'         => date_create( 'now', timezone_open( 'UTC' ) )->format( 'Y-m-d H:i:s' ),
			'date_compare' => '<',
			'per_page'     => 1,
			'offset'       => $consistent_failure_threshold - 1,
		);

		$first_failing_action_id = $this->store->query_actions( $query_args );

		// If we didn't retrieve an action ID, then there haven't been enough failures for us to worry about.
		if ( empty( $first_failing_action_id ) ) {
			return false;
		}

		// Now let's fetch the first action (having the same hook) of *any status* within the same window.
		unset( $query_args['status'] );
		$first_action_id_with_the_same_hook = $this->store->query_actions( $query_args );

		/**
		 * If a recurring action is assessed as consistently failing, it will not be rescheduled. This hook provides a
		 * way to observe and optionally override that assessment.
		 *
		 * @param bool                   $is_consistently_failing If the action is considered to be consistently failing.
		 * @param ActionScheduler_Action $action                  The action being assessed.
		 */
		return (bool) apply_filters(
			'action_scheduler_recurring_action_is_consistently_failing',
			$first_action_id_with_the_same_hook === $first_failing_action_id,
			$action
		);
	}

	/**
	 * Run the queue cleaner.
	 */
	protected function run_cleanup() {
		$this->cleaner->clean( 10 * $this->get_time_limit() );
	}

	/**
	 * Get the number of concurrent batches a runner allows.
	 *
	 * @return int
	 */
	public function get_allowed_concurrent_batches() {
		return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 1 );
	}

	/**
	 * Check if the number of allowed concurrent batches is met or exceeded.
	 *
	 * @return bool
	 */
	public function has_maximum_concurrent_batches() {
		return $this->store->get_claim_count() >= $this->get_allowed_concurrent_batches();
	}

	/**
	 * Get the maximum number of seconds a batch can run for.
	 *
	 * @return int The number of seconds.
	 */
	protected function get_time_limit() {

		$time_limit = 30;

		// Apply deprecated filter from deprecated get_maximum_execution_time() method.
		if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) {
			_deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' );
			$time_limit = apply_filters( 'action_scheduler_maximum_execution_time', $time_limit );
		}

		return absint( apply_filters( 'action_scheduler_queue_runner_time_limit', $time_limit ) );
	}

	/**
	 * Get the number of seconds the process has been running.
	 *
	 * @return int The number of seconds.
	 */
	protected function get_execution_time() {
		$execution_time = microtime( true ) - $this->created_time;

		// Get the CPU time if the hosting environment uses it rather than wall-clock time to calculate a process's execution time.
		if ( function_exists( 'getrusage' ) && apply_filters( 'action_scheduler_use_cpu_execution_time', defined( 'PANTHEON_ENVIRONMENT' ) ) ) {
			$resource_usages = getrusage();

			if ( isset( $resource_usages['ru_stime.tv_usec'], $resource_usages['ru_stime.tv_usec'] ) ) {
				$execution_time = $resource_usages['ru_stime.tv_sec'] + ( $resource_usages['ru_stime.tv_usec'] / 1000000 );
			}
		}

		return $execution_time;
	}

	/**
	 * Check if the host's max execution time is (likely) to be exceeded if processing more actions.
	 *
	 * @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action.
	 * @return bool
	 */
	protected function time_likely_to_be_exceeded( $processed_actions ) {
		$execution_time     = $this->get_execution_time();
		$max_execution_time = $this->get_time_limit();

		// Safety against division by zero errors.
		if ( 0 === $processed_actions ) {
			return $execution_time >= $max_execution_time;
		}

		$time_per_action       = $execution_time / $processed_actions;
		$estimated_time        = $execution_time + ( $time_per_action * 3 );
		$likely_to_be_exceeded = $estimated_time > $max_execution_time;

		return apply_filters( 'action_scheduler_maximum_execution_time_likely_to_be_exceeded', $likely_to_be_exceeded, $this, $processed_actions, $execution_time, $max_execution_time );
	}

	/**
	 * Get memory limit
	 *
	 * Based on WP_Background_Process::get_memory_limit()
	 *
	 * @return int
	 */
	protected function get_memory_limit() {
		if ( function_exists( 'ini_get' ) ) {
			$memory_limit = ini_get( 'memory_limit' );
		} else {
			$memory_limit = '128M'; // Sensible default, and minimum required by WooCommerce.
		}

		if ( ! $memory_limit || -1 === $memory_limit || '-1' === $memory_limit ) {
			// Unlimited, set to 32GB.
			$memory_limit = '32G';
		}

		return ActionScheduler_Compatibility::convert_hr_to_bytes( $memory_limit );
	}

	/**
	 * Memory exceeded
	 *
	 * Ensures the batch process never exceeds 90% of the maximum WordPress memory.
	 *
	 * Based on WP_Background_Process::memory_exceeded()
	 *
	 * @return bool
	 */
	protected function memory_exceeded() {

		$memory_limit    = $this->get_memory_limit() * 0.90;
		$current_memory  = memory_get_usage( true );
		$memory_exceeded = $current_memory >= $memory_limit;

		return apply_filters( 'action_scheduler_memory_exceeded', $memory_exceeded, $this );
	}

	/**
	 * See if the batch limits have been exceeded, which is when memory usage is almost at
	 * the maximum limit, or the time to process more actions will exceed the max time limit.
	 *
	 * Based on WC_Background_Process::batch_limits_exceeded()
	 *
	 * @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action.
	 * @return bool
	 */
	protected function batch_limits_exceeded( $processed_actions ) {
		return $this->memory_exceeded() || $this->time_likely_to_be_exceeded( $processed_actions );
	}

	/**
	 * Process actions in the queue.
	 *
	 * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
	 *        Generally, this should be capitalised and not localised as it's a proper noun.
	 * @return int The number of actions processed.
	 */
	abstract public function run( $context = '' );
}
abstracts/ActionScheduler_Store.php000066600000034071151137657220013515 0ustar00<?php

/**
 * Class ActionScheduler_Store
 *
 * @codeCoverageIgnore
 */
abstract class ActionScheduler_Store extends ActionScheduler_Store_Deprecated {
	const STATUS_COMPLETE = 'complete';
	const STATUS_PENDING  = 'pending';
	const STATUS_RUNNING  = 'in-progress';
	const STATUS_FAILED   = 'failed';
	const STATUS_CANCELED = 'canceled';
	const DEFAULT_CLASS   = 'ActionScheduler_wpPostStore';

	/**
	 * ActionScheduler_Store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private static $store = null;

	/**
	 * Maximum length of args.
	 *
	 * @var int
	 */
	protected static $max_args_length = 191;

	/**
	 * Save action.
	 *
	 * @param ActionScheduler_Action $action Action to save.
	 * @param null|DateTime          $scheduled_date Optional Date of the first instance
	 *                                               to store. Otherwise uses the first date of the action's
	 *                                               schedule.
	 *
	 * @return int The action ID
	 */
	abstract public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null );

	/**
	 * Get action.
	 *
	 * @param string $action_id Action ID.
	 *
	 * @return ActionScheduler_Action
	 */
	abstract public function fetch_action( $action_id );

	/**
	 * Find an action.
	 *
	 * Note: the query ordering changes based on the passed 'status' value.
	 *
	 * @param string $hook Action hook.
	 * @param array  $params Parameters of the action to find.
	 *
	 * @return string|null ID of the next action matching the criteria or NULL if not found.
	 */
	public function find_action( $hook, $params = array() ) {
		$params = wp_parse_args(
			$params,
			array(
				'args'   => null,
				'status' => self::STATUS_PENDING,
				'group'  => '',
			)
		);

		// These params are fixed for this method.
		$params['hook']     = $hook;
		$params['orderby']  = 'date';
		$params['per_page'] = 1;

		if ( ! empty( $params['status'] ) ) {
			if ( self::STATUS_PENDING === $params['status'] ) {
				$params['order'] = 'ASC'; // Find the next action that matches.
			} else {
				$params['order'] = 'DESC'; // Find the most recent action that matches.
			}
		}

		$results = $this->query_actions( $params );

		return empty( $results ) ? null : $results[0];
	}

	/**
	 * Query for action count or list of action IDs.
	 *
	 * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status.
	 *
	 * @param array  $query {
	 *      Query filtering options.
	 *
	 *      @type string       $hook             The name of the actions. Optional.
	 *      @type string|array $status           The status or statuses of the actions. Optional.
	 *      @type array        $args             The args array of the actions. Optional.
	 *      @type DateTime     $date             The scheduled date of the action. Used in UTC timezone. Optional.
	 *      @type string       $date_compare     Operator for selecting by $date param. Accepted values are '!=', '>', '>=', '<', '<=', '='. Defaults to '<='.
	 *      @type DateTime     $modified         The last modified date of the action. Used in UTC timezone. Optional.
	 *      @type string       $modified_compare Operator for comparing $modified param. Accepted values are '!=', '>', '>=', '<', '<=', '='. Defaults to '<='.
	 *      @type string       $group            The group the action belongs to. Optional.
	 *      @type bool|int     $claimed          TRUE to find claimed actions, FALSE to find unclaimed actions, an int to find a specific claim ID. Optional.
	 *      @type int          $per_page         Number of results to return. Defaults to 5.
	 *      @type int          $offset           The query pagination offset. Defaults to 0.
	 *      @type int          $orderby          Accepted values are 'hook', 'group', 'modified', 'date' or 'none'. Defaults to 'date'.
	 *      @type string       $order            Accepted values are 'ASC' or 'DESC'. Defaults to 'ASC'.
	 * }
	 * @param string $query_type Whether to select or count the results. Default, select.
	 *
	 * @return string|array|null The IDs of actions matching the query. Null on failure.
	 */
	abstract public function query_actions( $query = array(), $query_type = 'select' );

	/**
	 * Run query to get a single action ID.
	 *
	 * @since 3.3.0
	 *
	 * @see ActionScheduler_Store::query_actions for $query arg usage but 'per_page' and 'offset' can't be used.
	 *
	 * @param array $query Query parameters.
	 *
	 * @return int|null
	 */
	public function query_action( $query ) {
		$query['per_page'] = 1;
		$query['offset']   = 0;
		$results           = $this->query_actions( $query );

		if ( empty( $results ) ) {
			return null;
		} else {
			return (int) $results[0];
		}
	}

	/**
	 * Get a count of all actions in the store, grouped by status
	 *
	 * @return array
	 */
	abstract public function action_counts();

	/**
	 * Get additional action counts.
	 *
	 * - add past-due actions
	 *
	 * @return array
	 */
	public function extra_action_counts() {
		$extra_actions = array();

		$pastdue_action_counts = (int) $this->query_actions(
			array(
				'status' => self::STATUS_PENDING,
				'date'   => as_get_datetime_object(),
			),
			'count'
		);

		if ( $pastdue_action_counts ) {
			$extra_actions['past-due'] = $pastdue_action_counts;
		}

		/**
		 * Allows 3rd party code to add extra action counts (used in filters in the list table).
		 *
		 * @since 3.5.0
		 * @param $extra_actions array Array with format action_count_identifier => action count.
		 */
		return apply_filters( 'action_scheduler_extra_action_counts', $extra_actions );
	}

	/**
	 * Cancel action.
	 *
	 * @param string $action_id Action ID.
	 */
	abstract public function cancel_action( $action_id );

	/**
	 * Delete action.
	 *
	 * @param string $action_id Action ID.
	 */
	abstract public function delete_action( $action_id );

	/**
	 * Get action's schedule or run timestamp.
	 *
	 * @param string $action_id Action ID.
	 *
	 * @return DateTime The date the action is schedule to run, or the date that it ran.
	 */
	abstract public function get_date( $action_id );


	/**
	 * Make a claim.
	 *
	 * @param int           $max_actions Maximum number of actions to claim.
	 * @param DateTime|null $before_date Claim only actions schedule before the given date. Defaults to now.
	 * @param array         $hooks       Claim only actions with a hook or hooks.
	 * @param string        $group       Claim only actions in the given group.
	 *
	 * @return ActionScheduler_ActionClaim
	 */
	abstract public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' );

	/**
	 * Get claim count.
	 *
	 * @return int
	 */
	abstract public function get_claim_count();

	/**
	 * Release the claim.
	 *
	 * @param ActionScheduler_ActionClaim $claim Claim object.
	 */
	abstract public function release_claim( ActionScheduler_ActionClaim $claim );

	/**
	 * Un-claim the action.
	 *
	 * @param string $action_id Action ID.
	 */
	abstract public function unclaim_action( $action_id );

	/**
	 * Mark action as failed.
	 *
	 * @param string $action_id Action ID.
	 */
	abstract public function mark_failure( $action_id );

	/**
	 * Log action's execution.
	 *
	 * @param string $action_id Actoin ID.
	 */
	abstract public function log_execution( $action_id );

	/**
	 * Mark action as complete.
	 *
	 * @param string $action_id Action ID.
	 */
	abstract public function mark_complete( $action_id );

	/**
	 * Get action's status.
	 *
	 * @param string $action_id Action ID.
	 * @return string
	 */
	abstract public function get_status( $action_id );

	/**
	 * Get action's claim ID.
	 *
	 * @param string $action_id Action ID.
	 * @return mixed
	 */
	abstract public function get_claim_id( $action_id );

	/**
	 * Find actions by claim ID.
	 *
	 * @param string $claim_id Claim ID.
	 * @return array
	 */
	abstract public function find_actions_by_claim_id( $claim_id );

	/**
	 * Validate SQL operator.
	 *
	 * @param string $comparison_operator Operator.
	 * @return string
	 */
	protected function validate_sql_comparator( $comparison_operator ) {
		if ( in_array( $comparison_operator, array( '!=', '>', '>=', '<', '<=', '=' ), true ) ) {
			return $comparison_operator;
		}

		return '=';
	}

	/**
	 * Get the time MySQL formatted date/time string for an action's (next) scheduled date.
	 *
	 * @param ActionScheduler_Action $action Action.
	 * @param null|DateTime          $scheduled_date Action's schedule date (optional).
	 * @return string
	 */
	protected function get_scheduled_date_string( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) {
		$next = is_null( $scheduled_date ) ? $action->get_schedule()->get_date() : $scheduled_date;

		if ( ! $next ) {
			$next = date_create();
		}

		$next->setTimezone( new DateTimeZone( 'UTC' ) );

		return $next->format( 'Y-m-d H:i:s' );
	}

	/**
	 * Get the time MySQL formatted date/time string for an action's (next) scheduled date.
	 *
	 * @param ActionScheduler_Action|null $action Action.
	 * @param null|DateTime               $scheduled_date Action's scheduled date (optional).
	 * @return string
	 */
	protected function get_scheduled_date_string_local( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) {
		$next = is_null( $scheduled_date ) ? $action->get_schedule()->get_date() : $scheduled_date;

		if ( ! $next ) {
			$next = date_create();
		}

		ActionScheduler_TimezoneHelper::set_local_timezone( $next );
		return $next->format( 'Y-m-d H:i:s' );
	}

	/**
	 * Validate that we could decode action arguments.
	 *
	 * @param mixed $args      The decoded arguments.
	 * @param int   $action_id The action ID.
	 *
	 * @throws ActionScheduler_InvalidActionException When the decoded arguments are invalid.
	 */
	protected function validate_args( $args, $action_id ) {
		// Ensure we have an array of args.
		if ( ! is_array( $args ) ) {
			throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id );
		}

		// Validate JSON decoding if possible.
		if ( function_exists( 'json_last_error' ) && JSON_ERROR_NONE !== json_last_error() ) {
			throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id, $args );
		}
	}

	/**
	 * Validate a ActionScheduler_Schedule object.
	 *
	 * @param mixed $schedule  The unserialized ActionScheduler_Schedule object.
	 * @param int   $action_id The action ID.
	 *
	 * @throws ActionScheduler_InvalidActionException When the schedule is invalid.
	 */
	protected function validate_schedule( $schedule, $action_id ) {
		if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) {
			throw ActionScheduler_InvalidActionException::from_schedule( $action_id, $schedule );
		}
	}

	/**
	 * InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4.
	 *
	 * Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However,
	 * with custom tables, we use an indexed VARCHAR column instead.
	 *
	 * @param  ActionScheduler_Action $action Action to be validated.
	 * @throws InvalidArgumentException When json encoded args is too long.
	 */
	protected function validate_action( ActionScheduler_Action $action ) {
		if ( strlen( wp_json_encode( $action->get_args() ) ) > static::$max_args_length ) {
			// translators: %d is a number (maximum length of action arguments).
			throw new InvalidArgumentException( sprintf( __( 'ActionScheduler_Action::$args too long. To ensure the args column can be indexed, action args should not be more than %d characters when encoded as JSON.', 'action-scheduler' ), static::$max_args_length ) );
		}
	}

	/**
	 * Cancel pending actions by hook.
	 *
	 * @since 3.0.0
	 *
	 * @param string $hook Hook name.
	 *
	 * @return void
	 */
	public function cancel_actions_by_hook( $hook ) {
		$action_ids = true;
		while ( ! empty( $action_ids ) ) {
			$action_ids = $this->query_actions(
				array(
					'hook'     => $hook,
					'status'   => self::STATUS_PENDING,
					'per_page' => 1000,
					'orderby'  => 'none',
				)
			);

			$this->bulk_cancel_actions( $action_ids );
		}
	}

	/**
	 * Cancel pending actions by group.
	 *
	 * @since 3.0.0
	 *
	 * @param string $group Group slug.
	 *
	 * @return void
	 */
	public function cancel_actions_by_group( $group ) {
		$action_ids = true;
		while ( ! empty( $action_ids ) ) {
			$action_ids = $this->query_actions(
				array(
					'group'    => $group,
					'status'   => self::STATUS_PENDING,
					'per_page' => 1000,
					'orderby'  => 'none',
				)
			);

			$this->bulk_cancel_actions( $action_ids );
		}
	}

	/**
	 * Cancel a set of action IDs.
	 *
	 * @since 3.0.0
	 *
	 * @param int[] $action_ids List of action IDs.
	 *
	 * @return void
	 */
	private function bulk_cancel_actions( $action_ids ) {
		foreach ( $action_ids as $action_id ) {
			$this->cancel_action( $action_id );
		}

		do_action( 'action_scheduler_bulk_cancel_actions', $action_ids );
	}

	/**
	 * Get status labels.
	 *
	 * @return array<string, string>
	 */
	public function get_status_labels() {
		return array(
			self::STATUS_COMPLETE => __( 'Complete', 'action-scheduler' ),
			self::STATUS_PENDING  => __( 'Pending', 'action-scheduler' ),
			self::STATUS_RUNNING  => __( 'In-progress', 'action-scheduler' ),
			self::STATUS_FAILED   => __( 'Failed', 'action-scheduler' ),
			self::STATUS_CANCELED => __( 'Canceled', 'action-scheduler' ),
		);
	}

	/**
	 * Check if there are any pending scheduled actions due to run.
	 *
	 * @return string
	 */
	public function has_pending_actions_due() {
		$pending_actions = $this->query_actions(
			array(
				'per_page' => 1,
				'date'     => as_get_datetime_object(),
				'status'   => self::STATUS_PENDING,
				'orderby'  => 'none',
			),
			'count'
		);

		return ! empty( $pending_actions );
	}

	/**
	 * Callable initialization function optionally overridden in derived classes.
	 */
	public function init() {}

	/**
	 * Callable function to mark an action as migrated optionally overridden in derived classes.
	 *
	 * @param int $action_id Action ID.
	 */
	public function mark_migrated( $action_id ) {}

	/**
	 * Get instance.
	 *
	 * @return ActionScheduler_Store
	 */
	public static function instance() {
		if ( empty( self::$store ) ) {
			$class       = apply_filters( 'action_scheduler_store_class', self::DEFAULT_CLASS );
			self::$store = new $class();
		}
		return self::$store;
	}
}
abstracts/ActionScheduler_Lock.php000066600000003437151137657220013313 0ustar00<?php

/**
 * Abstract class for setting a basic lock to throttle some action.
 *
 * Class ActionScheduler_Lock
 */
abstract class ActionScheduler_Lock {

	/**
	 * Instance.
	 *
	 * @var ActionScheduler_Lock
	 */
	private static $locker = null;

	/**
	 * Duration of lock.
	 *
	 * @var int
	 */
	protected static $lock_duration = MINUTE_IN_SECONDS;

	/**
	 * Check if a lock is set for a given lock type.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @return bool
	 */
	public function is_locked( $lock_type ) {
		return ( $this->get_expiration( $lock_type ) >= time() );
	}

	/**
	 * Set a lock.
	 *
	 * To prevent race conditions, implementations should avoid setting the lock if the lock is already held.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @return bool
	 */
	abstract public function set( $lock_type );

	/**
	 * If a lock is set, return the timestamp it was set to expiry.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
	 */
	abstract public function get_expiration( $lock_type );

	/**
	 * Get the amount of time to set for a given lock. 60 seconds by default.
	 *
	 * @param string $lock_type A string to identify different lock types.
	 * @return int
	 */
	protected function get_duration( $lock_type ) {
		return apply_filters( 'action_scheduler_lock_duration', self::$lock_duration, $lock_type );
	}

	/**
	 * Get instance.
	 *
	 * @return ActionScheduler_Lock
	 */
	public static function instance() {
		if ( empty( self::$locker ) ) {
			$class        = apply_filters( 'action_scheduler_lock_class', 'ActionScheduler_OptionLock' );
			self::$locker = new $class();
		}
		return self::$locker;
	}
}
abstracts/ActionScheduler_Logger.php000066600000017525151137657220013645 0ustar00<?php

/**
 * Class ActionScheduler_Logger
 *
 * @codeCoverageIgnore
 */
abstract class ActionScheduler_Logger {

	/**
	 * Instance.
	 *
	 * @var null|self
	 */
	private static $logger = null;

	/**
	 * Get instance.
	 *
	 * @return ActionScheduler_Logger
	 */
	public static function instance() {
		if ( empty( self::$logger ) ) {
			$class        = apply_filters( 'action_scheduler_logger_class', 'ActionScheduler_wpCommentLogger' );
			self::$logger = new $class();
		}
		return self::$logger;
	}

	/**
	 * Create log entry.
	 *
	 * @param string        $action_id Action ID.
	 * @param string        $message   Log message.
	 * @param DateTime|null $date      Log date.
	 *
	 * @return string The log entry ID
	 */
	abstract public function log( $action_id, $message, ?DateTime $date = null );

	/**
	 * Get action's log entry.
	 *
	 * @param string $entry_id Entry ID.
	 *
	 * @return ActionScheduler_LogEntry
	 */
	abstract public function get_entry( $entry_id );

	/**
	 * Get action's logs.
	 *
	 * @param string $action_id Action ID.
	 *
	 * @return ActionScheduler_LogEntry[]
	 */
	abstract public function get_logs( $action_id );


	/**
	 * Initialize.
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {
		$this->hook_stored_action();
		add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 );
		add_action( 'action_scheduler_begin_execute', array( $this, 'log_started_action' ), 10, 2 );
		add_action( 'action_scheduler_after_execute', array( $this, 'log_completed_action' ), 10, 3 );
		add_action( 'action_scheduler_failed_execution', array( $this, 'log_failed_action' ), 10, 3 );
		add_action( 'action_scheduler_failed_action', array( $this, 'log_timed_out_action' ), 10, 2 );
		add_action( 'action_scheduler_unexpected_shutdown', array( $this, 'log_unexpected_shutdown' ), 10, 2 );
		add_action( 'action_scheduler_reset_action', array( $this, 'log_reset_action' ), 10, 1 );
		add_action( 'action_scheduler_execution_ignored', array( $this, 'log_ignored_action' ), 10, 2 );
		add_action( 'action_scheduler_failed_fetch_action', array( $this, 'log_failed_fetch_action' ), 10, 2 );
		add_action( 'action_scheduler_failed_to_schedule_next_instance', array( $this, 'log_failed_schedule_next_instance' ), 10, 2 );
		add_action( 'action_scheduler_bulk_cancel_actions', array( $this, 'bulk_log_cancel_actions' ), 10, 1 );
	}

	/**
	 * Register callback for storing action.
	 */
	public function hook_stored_action() {
		add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) );
	}

	/**
	 * Unhook callback for storing action.
	 */
	public function unhook_stored_action() {
		remove_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) );
	}

	/**
	 * Log action stored.
	 *
	 * @param int $action_id Action ID.
	 */
	public function log_stored_action( $action_id ) {
		$this->log( $action_id, __( 'action created', 'action-scheduler' ) );
	}

	/**
	 * Log action cancellation.
	 *
	 * @param int $action_id Action ID.
	 */
	public function log_canceled_action( $action_id ) {
		$this->log( $action_id, __( 'action canceled', 'action-scheduler' ) );
	}

	/**
	 * Log action start.
	 *
	 * @param int    $action_id Action ID.
	 * @param string $context Action execution context.
	 */
	public function log_started_action( $action_id, $context = '' ) {
		if ( ! empty( $context ) ) {
			/* translators: %s: context */
			$message = sprintf( __( 'action started via %s', 'action-scheduler' ), $context );
		} else {
			$message = __( 'action started', 'action-scheduler' );
		}
		$this->log( $action_id, $message );
	}

	/**
	 * Log action completion.
	 *
	 * @param int                         $action_id Action ID.
	 * @param null|ActionScheduler_Action $action Action.
	 * @param string                      $context Action execution context.
	 */
	public function log_completed_action( $action_id, $action = null, $context = '' ) {
		if ( ! empty( $context ) ) {
			/* translators: %s: context */
			$message = sprintf( __( 'action complete via %s', 'action-scheduler' ), $context );
		} else {
			$message = __( 'action complete', 'action-scheduler' );
		}
		$this->log( $action_id, $message );
	}

	/**
	 * Log action failure.
	 *
	 * @param int       $action_id Action ID.
	 * @param Exception $exception Exception.
	 * @param string    $context Action execution context.
	 */
	public function log_failed_action( $action_id, Exception $exception, $context = '' ) {
		if ( ! empty( $context ) ) {
			/* translators: 1: context 2: exception message */
			$message = sprintf( __( 'action failed via %1$s: %2$s', 'action-scheduler' ), $context, $exception->getMessage() );
		} else {
			/* translators: %s: exception message */
			$message = sprintf( __( 'action failed: %s', 'action-scheduler' ), $exception->getMessage() );
		}
		$this->log( $action_id, $message );
	}

	/**
	 * Log action timeout.
	 *
	 * @param int    $action_id  Action ID.
	 * @param string $timeout Timeout.
	 */
	public function log_timed_out_action( $action_id, $timeout ) {
		/* translators: %s: amount of time */
		$this->log( $action_id, sprintf( __( 'action marked as failed after %s seconds. Unknown error occurred. Check server, PHP and database error logs to diagnose cause.', 'action-scheduler' ), $timeout ) );
	}

	/**
	 * Log unexpected shutdown.
	 *
	 * @param int     $action_id Action ID.
	 * @param mixed[] $error     Error.
	 */
	public function log_unexpected_shutdown( $action_id, $error ) {
		if ( ! empty( $error ) ) {
			/* translators: 1: error message 2: filename 3: line */
			$this->log( $action_id, sprintf( __( 'unexpected shutdown: PHP Fatal error %1$s in %2$s on line %3$s', 'action-scheduler' ), $error['message'], $error['file'], $error['line'] ) );
		}
	}

	/**
	 * Log action reset.
	 *
	 * @param int $action_id Action ID.
	 */
	public function log_reset_action( $action_id ) {
		$this->log( $action_id, __( 'action reset', 'action-scheduler' ) );
	}

	/**
	 * Log ignored action.
	 *
	 * @param int    $action_id Action ID.
	 * @param string $context Action execution context.
	 */
	public function log_ignored_action( $action_id, $context = '' ) {
		if ( ! empty( $context ) ) {
			/* translators: %s: context */
			$message = sprintf( __( 'action ignored via %s', 'action-scheduler' ), $context );
		} else {
			$message = __( 'action ignored', 'action-scheduler' );
		}
		$this->log( $action_id, $message );
	}

	/**
	 * Log the failure of fetching the action.
	 *
	 * @param string         $action_id Action ID.
	 * @param null|Exception $exception The exception which occurred when fetching the action. NULL by default for backward compatibility.
	 */
	public function log_failed_fetch_action( $action_id, ?Exception $exception = null ) {

		if ( ! is_null( $exception ) ) {
			/* translators: %s: exception message */
			$log_message = sprintf( __( 'There was a failure fetching this action: %s', 'action-scheduler' ), $exception->getMessage() );
		} else {
			$log_message = __( 'There was a failure fetching this action', 'action-scheduler' );
		}

		$this->log( $action_id, $log_message );
	}

	/**
	 * Log the failure of scheduling the action's next instance.
	 *
	 * @param int       $action_id Action ID.
	 * @param Exception $exception Exception object.
	 */
	public function log_failed_schedule_next_instance( $action_id, Exception $exception ) {
		/* translators: %s: exception message */
		$this->log( $action_id, sprintf( __( 'There was a failure scheduling the next instance of this action: %s', 'action-scheduler' ), $exception->getMessage() ) );
	}

	/**
	 * Bulk add cancel action log entries.
	 *
	 * Implemented here for backward compatibility. Should be implemented in parent loggers
	 * for more performant bulk logging.
	 *
	 * @param array $action_ids List of action ID.
	 */
	public function bulk_log_cancel_actions( $action_ids ) {
		if ( empty( $action_ids ) ) {
			return;
		}

		foreach ( $action_ids as $action_id ) {
			$this->log_canceled_action( $action_id );
		}
	}
}
abstracts/ActionScheduler_Abstract_Schedule.php000066600000003547151137657220016004 0ustar00<?php

/**
 * Class ActionScheduler_Abstract_Schedule
 */
abstract class ActionScheduler_Abstract_Schedule extends ActionScheduler_Schedule_Deprecated {

	/**
	 * The date & time the schedule is set to run.
	 *
	 * @var DateTime
	 */
	private $scheduled_date = null;

	/**
	 * Timestamp equivalent of @see $this->scheduled_date
	 *
	 * @var int
	 */
	protected $scheduled_timestamp = null;

	/**
	 * Construct.
	 *
	 * @param DateTime $date The date & time to run the action.
	 */
	public function __construct( DateTime $date ) {
		$this->scheduled_date = $date;
	}

	/**
	 * Check if a schedule should recur.
	 *
	 * @return bool
	 */
	abstract public function is_recurring();

	/**
	 * Calculate when the next instance of this schedule would run based on a given date & time.
	 *
	 * @param DateTime $after Start timestamp.
	 * @return DateTime
	 */
	abstract protected function calculate_next( DateTime $after );

	/**
	 * Get the next date & time when this schedule should run after a given date & time.
	 *
	 * @param DateTime $after Start timestamp.
	 * @return DateTime|null
	 */
	public function get_next( DateTime $after ) {
		$after = clone $after;
		if ( $after > $this->scheduled_date ) {
			$after = $this->calculate_next( $after );
			return $after;
		}
		return clone $this->scheduled_date;
	}

	/**
	 * Get the date & time the schedule is set to run.
	 *
	 * @return DateTime|null
	 */
	public function get_date() {
		return $this->scheduled_date;
	}

	/**
	 * For PHP 5.2 compat, because DateTime objects can't be serialized
	 *
	 * @return array
	 */
	public function __sleep() {
		$this->scheduled_timestamp = $this->scheduled_date->getTimestamp();
		return array(
			'scheduled_timestamp',
		);
	}

	/**
	 * Wakeup.
	 */
	public function __wakeup() {
		$this->scheduled_date = as_get_datetime_object( $this->scheduled_timestamp );
		unset( $this->scheduled_timestamp );
	}
}
abstracts/ActionScheduler_Abstract_ListTable.php000066600000061057151137657220016133 0ustar00<?php

if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

/**
 * Action Scheduler Abstract List Table class
 *
 * This abstract class enhances WP_List_Table making it ready to use.
 *
 * By extending this class we can focus on describing how our table looks like,
 * which columns needs to be shown, filter, ordered by and more and forget about the details.
 *
 * This class supports:
 *  - Bulk actions
 *  - Search
 *  - Sortable columns
 *  - Automatic translations of the columns
 *
 * @codeCoverageIgnore
 * @since  2.0.0
 */
abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {

	/**
	 * The table name
	 *
	 * @var string
	 */
	protected $table_name;

	/**
	 * Package name, used to get options from WP_List_Table::get_items_per_page.
	 *
	 * @var string
	 */
	protected $package;

	/**
	 * How many items do we render per page?
	 *
	 * @var int
	 */
	protected $items_per_page = 10;

	/**
	 * Enables search in this table listing. If this array
	 * is empty it means the listing is not searchable.
	 *
	 * @var array
	 */
	protected $search_by = array();

	/**
	 * Columns to show in the table listing. It is a key => value pair. The
	 * key must much the table column name and the value is the label, which is
	 * automatically translated.
	 *
	 * @var array
	 */
	protected $columns = array();

	/**
	 * Defines the row-actions. It expects an array where the key
	 * is the column name and the value is an array of actions.
	 *
	 * The array of actions are key => value, where key is the method name
	 * (with the prefix row_action_<key>) and the value is the label
	 * and title.
	 *
	 * @var array
	 */
	protected $row_actions = array();

	/**
	 * The Primary key of our table
	 *
	 * @var string
	 */
	protected $ID = 'ID';

	/**
	 * Enables sorting, it expects an array
	 * of columns (the column names are the values)
	 *
	 * @var array
	 */
	protected $sort_by = array();

	/**
	 * The default sort order
	 *
	 * @var string
	 */
	protected $filter_by = array();

	/**
	 * The status name => count combinations for this table's items. Used to display status filters.
	 *
	 * @var array
	 */
	protected $status_counts = array();

	/**
	 * Notices to display when loading the table. Array of arrays of form array( 'class' => {updated|error}, 'message' => 'This is the notice text display.' ).
	 *
	 * @var array
	 */
	protected $admin_notices = array();

	/**
	 * Localised string displayed in the <h1> element above the able.
	 *
	 * @var string
	 */
	protected $table_header;

	/**
	 * Enables bulk actions. It must be an array where the key is the action name
	 * and the value is the label (which is translated automatically). It is important
	 * to notice that it will check that the method exists (`bulk_$name`) and will throw
	 * an exception if it does not exists.
	 *
	 * This class will automatically check if the current request has a bulk action, will do the
	 * validations and afterwards will execute the bulk method, with two arguments. The first argument
	 * is the array with primary keys, the second argument is a string with a list of the primary keys,
	 * escaped and ready to use (with `IN`).
	 *
	 * @var array
	 */
	protected $bulk_actions = array();

	/**
	 * Makes translation easier, it basically just wraps
	 * `_x` with some default (the package name).
	 *
	 * @param string $text The new text to translate.
	 * @param string $context The context of the text.
	 * @return string|void The translated text.
	 *
	 * @deprecated 3.0.0 Use `_x()` instead.
	 */
	protected function translate( $text, $context = '' ) {
		return $text;
	}

	/**
	 * Reads `$this->bulk_actions` and returns an array that WP_List_Table understands. It
	 * also validates that the bulk method handler exists. It throws an exception because
	 * this is a library meant for developers and missing a bulk method is a development-time error.
	 *
	 * @return array
	 *
	 * @throws RuntimeException Throws RuntimeException when the bulk action does not have a callback method.
	 */
	protected function get_bulk_actions() {
		$actions = array();

		foreach ( $this->bulk_actions as $action => $label ) {
			if ( ! is_callable( array( $this, 'bulk_' . $action ) ) ) {
				throw new RuntimeException( "The bulk action $action does not have a callback method" );
			}

			$actions[ $action ] = $label;
		}

		return $actions;
	}

	/**
	 * Checks if the current request has a bulk action. If that is the case it will validate and will
	 * execute the bulk method handler. Regardless if the action is valid or not it will redirect to
	 * the previous page removing the current arguments that makes this request a bulk action.
	 */
	protected function process_bulk_action() {
		global $wpdb;
		// Detect when a bulk action is being triggered.
		$action = $this->current_action();
		if ( ! $action ) {
			return;
		}

		check_admin_referer( 'bulk-' . $this->_args['plural'] );

		$method = 'bulk_' . $action;
		if ( array_key_exists( $action, $this->bulk_actions ) && is_callable( array( $this, $method ) ) && ! empty( $_GET['ID'] ) && is_array( $_GET['ID'] ) ) {
			$ids_sql = '(' . implode( ',', array_fill( 0, count( $_GET['ID'] ), '%s' ) ) . ')';
			$id      = array_map( 'absint', $_GET['ID'] );
			$this->$method( $id, $wpdb->prepare( $ids_sql, $id ) ); //phpcs:ignore WordPress.DB.PreparedSQL
		}

		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			wp_safe_redirect(
				remove_query_arg(
					array( '_wp_http_referer', '_wpnonce', 'ID', 'action', 'action2' ),
					esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) )
				)
			);
			exit;
		}
	}

	/**
	 * Default code for deleting entries.
	 * validated already by process_bulk_action()
	 *
	 * @param array  $ids ids of the items to delete.
	 * @param string $ids_sql the sql for the ids.
	 * @return void
	 */
	protected function bulk_delete( array $ids, $ids_sql ) {
		$store = ActionScheduler::store();
		foreach ( $ids as $action_id ) {
			$store->delete( $action_id );
		}
	}

	/**
	 * Prepares the _column_headers property which is used by WP_Table_List at rendering.
	 * It merges the columns and the sortable columns.
	 */
	protected function prepare_column_headers() {
		$this->_column_headers = array(
			$this->get_columns(),
			get_hidden_columns( $this->screen ),
			$this->get_sortable_columns(),
		);
	}

	/**
	 * Reads $this->sort_by and returns the columns name in a format that WP_Table_List
	 * expects
	 */
	public function get_sortable_columns() {
		$sort_by = array();
		foreach ( $this->sort_by as $column ) {
			$sort_by[ $column ] = array( $column, true );
		}
		return $sort_by;
	}

	/**
	 * Returns the columns names for rendering. It adds a checkbox for selecting everything
	 * as the first column
	 */
	public function get_columns() {
		$columns = array_merge(
			array( 'cb' => '<input type="checkbox" />' ),
			$this->columns
		);

		return $columns;
	}

	/**
	 * Get prepared LIMIT clause for items query
	 *
	 * @global wpdb $wpdb
	 *
	 * @return string Prepared LIMIT clause for items query.
	 */
	protected function get_items_query_limit() {
		global $wpdb;

		$per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
		return $wpdb->prepare( 'LIMIT %d', $per_page );
	}

	/**
	 * Returns the number of items to offset/skip for this current view.
	 *
	 * @return int
	 */
	protected function get_items_offset() {
		$per_page     = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
		$current_page = $this->get_pagenum();
		if ( 1 < $current_page ) {
			$offset = $per_page * ( $current_page - 1 );
		} else {
			$offset = 0;
		}

		return $offset;
	}

	/**
	 * Get prepared OFFSET clause for items query
	 *
	 * @global wpdb $wpdb
	 *
	 * @return string Prepared OFFSET clause for items query.
	 */
	protected function get_items_query_offset() {
		global $wpdb;

		return $wpdb->prepare( 'OFFSET %d', $this->get_items_offset() );
	}

	/**
	 * Prepares the ORDER BY sql statement. It uses `$this->sort_by` to know which
	 * columns are sortable. This requests validates the orderby $_GET parameter is a valid
	 * column and sortable. It will also use order (ASC|DESC) using DESC by default.
	 */
	protected function get_items_query_order() {
		if ( empty( $this->sort_by ) ) {
			return '';
		}

		$orderby = esc_sql( $this->get_request_orderby() );
		$order   = esc_sql( $this->get_request_order() );

		return "ORDER BY {$orderby} {$order}";
	}

	/**
	 * Querystring arguments to persist between form submissions.
	 *
	 * @since 3.7.3
	 *
	 * @return string[]
	 */
	protected function get_request_query_args_to_persist() {
		return array_merge(
			$this->sort_by,
			array(
				'page',
				'status',
				'tab',
			)
		);
	}

	/**
	 * Return the sortable column specified for this request to order the results by, if any.
	 *
	 * @return string
	 */
	protected function get_request_orderby() {

		$valid_sortable_columns = array_values( $this->sort_by );

		if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_sortable_columns, true ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$orderby = sanitize_text_field( wp_unslash( $_GET['orderby'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		} else {
			$orderby = $valid_sortable_columns[0];
		}

		return $orderby;
	}

	/**
	 * Return the sortable column order specified for this request.
	 *
	 * @return string
	 */
	protected function get_request_order() {

		if ( ! empty( $_GET['order'] ) && 'desc' === strtolower( sanitize_text_field( wp_unslash( $_GET['order'] ) ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$order = 'DESC';
		} else {
			$order = 'ASC';
		}

		return $order;
	}

	/**
	 * Return the status filter for this request, if any.
	 *
	 * @return string
	 */
	protected function get_request_status() {
		$status = ( ! empty( $_GET['status'] ) ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return $status;
	}

	/**
	 * Return the search filter for this request, if any.
	 *
	 * @return string
	 */
	protected function get_request_search_query() {
		$search_query = ( ! empty( $_GET['s'] ) ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return $search_query;
	}

	/**
	 * Process and return the columns name. This is meant for using with SQL, this means it
	 * always includes the primary key.
	 *
	 * @return array
	 */
	protected function get_table_columns() {
		$columns = array_keys( $this->columns );
		if ( ! in_array( $this->ID, $columns, true ) ) {
			$columns[] = $this->ID;
		}

		return $columns;
	}

	/**
	 * Check if the current request is doing a "full text" search. If that is the case
	 * prepares the SQL to search texts using LIKE.
	 *
	 * If the current request does not have any search or if this list table does not support
	 * that feature it will return an empty string.
	 *
	 * @return string
	 */
	protected function get_items_query_search() {
		global $wpdb;

		if ( empty( $_GET['s'] ) || empty( $this->search_by ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return '';
		}

		$search_string = sanitize_text_field( wp_unslash( $_GET['s'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$filter = array();
		foreach ( $this->search_by as $column ) {
			$wild     = '%';
			$sql_like = $wild . $wpdb->esc_like( $search_string ) . $wild;
			$filter[] = $wpdb->prepare( '`' . $column . '` LIKE %s', $sql_like ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.NotPrepared
		}
		return implode( ' OR ', $filter );
	}

	/**
	 * Prepares the SQL to filter rows by the options defined at `$this->filter_by`. Before trusting
	 * any data sent by the user it validates that it is a valid option.
	 */
	protected function get_items_query_filters() {
		global $wpdb;

		if ( ! $this->filter_by || empty( $_GET['filter_by'] ) || ! is_array( $_GET['filter_by'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return '';
		}

		$filter = array();

		foreach ( $this->filter_by as $column => $options ) {
			if ( empty( $_GET['filter_by'][ $column ] ) || empty( $options[ $_GET['filter_by'][ $column ] ] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
				continue;
			}

			$filter[] = $wpdb->prepare( "`$column` = %s", sanitize_text_field( wp_unslash( $_GET['filter_by'][ $column ] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		}

		return implode( ' AND ', $filter );

	}

	/**
	 * Prepares the data to feed WP_Table_List.
	 *
	 * This has the core for selecting, sorting and filtering data. To keep the code simple
	 * its logic is split among many methods (get_items_query_*).
	 *
	 * Beside populating the items this function will also count all the records that matches
	 * the filtering criteria and will do fill the pagination variables.
	 */
	public function prepare_items() {
		global $wpdb;

		$this->process_bulk_action();

		$this->process_row_actions();

		if ( ! empty( $_REQUEST['_wp_http_referer'] && ! empty( $_SERVER['REQUEST_URI'] ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
			wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) );
			exit;
		}

		$this->prepare_column_headers();

		$limit   = $this->get_items_query_limit();
		$offset  = $this->get_items_query_offset();
		$order   = $this->get_items_query_order();
		$where   = array_filter(
			array(
				$this->get_items_query_search(),
				$this->get_items_query_filters(),
			)
		);
		$columns = '`' . implode( '`, `', $this->get_table_columns() ) . '`';

		if ( ! empty( $where ) ) {
			$where = 'WHERE (' . implode( ') AND (', $where ) . ')';
		} else {
			$where = '';
		}

		$sql = "SELECT $columns FROM {$this->table_name} {$where} {$order} {$limit} {$offset}";

		$this->set_items( $wpdb->get_results( $sql, ARRAY_A ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		$query_count = "SELECT COUNT({$this->ID}) FROM {$this->table_name} {$where}";
		$total_items = $wpdb->get_var( $query_count ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$per_page    = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page );
		$this->set_pagination_args(
			array(
				'total_items' => $total_items,
				'per_page'    => $per_page,
				'total_pages' => ceil( $total_items / $per_page ),
			)
		);
	}

	/**
	 * Display the table.
	 *
	 * @param string $which The name of the table.
	 */
	public function extra_tablenav( $which ) {
		if ( ! $this->filter_by || 'top' !== $which ) {
			return;
		}

		echo '<div class="alignleft actions">';

		foreach ( $this->filter_by as $id => $options ) {
			$default = ! empty( $_GET['filter_by'][ $id ] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'][ $id ] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( empty( $options[ $default ] ) ) {
				$default = '';
			}

			echo '<select name="filter_by[' . esc_attr( $id ) . ']" class="first" id="filter-by-' . esc_attr( $id ) . '">';

			foreach ( $options as $value => $label ) {
				echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value === $default ? 'selected' : '' ) . '>'
					. esc_html( $label )
				. '</option>';
			}

			echo '</select>';
		}

		submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
		echo '</div>';
	}

	/**
	 * Set the data for displaying. It will attempt to unserialize (There is a chance that some columns
	 * are serialized). This can be override in child classes for further data transformation.
	 *
	 * @param array $items Items array.
	 */
	protected function set_items( array $items ) {
		$this->items = array();
		foreach ( $items as $item ) {
			$this->items[ $item[ $this->ID ] ] = array_map( 'maybe_unserialize', $item );
		}
	}

	/**
	 * Renders the checkbox for each row, this is the first column and it is named ID regardless
	 * of how the primary key is named (to keep the code simpler). The bulk actions will do the proper
	 * name transformation though using `$this->ID`.
	 *
	 * @param array $row The row to render.
	 */
	public function column_cb( $row ) {
		return '<input name="ID[]" type="checkbox" value="' . esc_attr( $row[ $this->ID ] ) . '" />';
	}

	/**
	 * Renders the row-actions.
	 *
	 * This method renders the action menu, it reads the definition from the $row_actions property,
	 * and it checks that the row action method exists before rendering it.
	 *
	 * @param array  $row Row to be rendered.
	 * @param string $column_name Column name.
	 * @return string
	 */
	protected function maybe_render_actions( $row, $column_name ) {
		if ( empty( $this->row_actions[ $column_name ] ) ) {
			return;
		}

		$row_id = $row[ $this->ID ];

		$actions      = '<div class="row-actions">';
		$action_count = 0;
		foreach ( $this->row_actions[ $column_name ] as $action_key => $action ) {

			$action_count++;

			if ( ! method_exists( $this, 'row_action_' . $action_key ) ) {
				continue;
			}

			$action_link = ! empty( $action['link'] ) ? $action['link'] : add_query_arg(
				array(
					'row_action' => $action_key,
					'row_id'     => $row_id,
					'nonce'      => wp_create_nonce( $action_key . '::' . $row_id ),
				)
			);
			$span_class  = ! empty( $action['class'] ) ? $action['class'] : $action_key;
			$separator   = ( $action_count < count( $this->row_actions[ $column_name ] ) ) ? ' | ' : '';

			$actions .= sprintf( '<span class="%s">', esc_attr( $span_class ) );
			$actions .= sprintf( '<a href="%1$s" title="%2$s">%3$s</a>', esc_url( $action_link ), esc_attr( $action['desc'] ), esc_html( $action['name'] ) );
			$actions .= sprintf( '%s</span>', $separator );
		}
		$actions .= '</div>';
		return $actions;
	}

	/**
	 * Process the bulk actions.
	 *
	 * @return void
	 */
	protected function process_row_actions() {
		$parameters = array( 'row_action', 'row_id', 'nonce' );
		foreach ( $parameters as $parameter ) {
			if ( empty( $_REQUEST[ $parameter ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
				return;
			}
		}

		$action = sanitize_text_field( wp_unslash( $_REQUEST['row_action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$row_id = sanitize_text_field( wp_unslash( $_REQUEST['row_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$nonce  = sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
		$method = 'row_action_' . $action; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		if ( wp_verify_nonce( $nonce, $action . '::' . $row_id ) && method_exists( $this, $method ) ) {
			$this->$method( sanitize_text_field( wp_unslash( $row_id ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}

		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			wp_safe_redirect(
				remove_query_arg(
					array( 'row_id', 'row_action', 'nonce' ),
					esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) )
				)
			);
			exit;
		}
	}

	/**
	 * Default column formatting, it will escape everything for security.
	 *
	 * @param array  $item The item array.
	 * @param string $column_name Column name to display.
	 *
	 * @return string
	 */
	public function column_default( $item, $column_name ) {
		$column_html  = esc_html( $item[ $column_name ] );
		$column_html .= $this->maybe_render_actions( $item, $column_name );
		return $column_html;
	}

	/**
	 * Display the table heading and search query, if any
	 */
	protected function display_header() {
		echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>';
		if ( $this->get_request_search_query() ) {
			/* translators: %s: search query */
			echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . '</span>';
		}
		echo '<hr class="wp-header-end">';
	}

	/**
	 * Display the table heading and search query, if any
	 */
	protected function display_admin_notices() {
		foreach ( $this->admin_notices as $notice ) {
			echo '<div id="message" class="' . esc_attr( $notice['class'] ) . '">';
			echo '	<p>' . wp_kses_post( $notice['message'] ) . '</p>';
			echo '</div>';
		}
	}

	/**
	 * Prints the available statuses so the user can click to filter.
	 */
	protected function display_filter_by_status() {

		$status_list_items = array();
		$request_status    = $this->get_request_status();

		// Helper to set 'all' filter when not set on status counts passed in.
		if ( ! isset( $this->status_counts['all'] ) ) {
			$all_count = array_sum( $this->status_counts );
			if ( isset( $this->status_counts['past-due'] ) ) {
				$all_count -= $this->status_counts['past-due'];
			}
			$this->status_counts = array( 'all' => $all_count ) + $this->status_counts;
		}

		// Translated status labels.
		$status_labels             = ActionScheduler_Store::instance()->get_status_labels();
		$status_labels['all']      = esc_html_x( 'All', 'status labels', 'action-scheduler' );
		$status_labels['past-due'] = esc_html_x( 'Past-due', 'status labels', 'action-scheduler' );

		foreach ( $this->status_counts as $status_slug => $count ) {

			if ( 0 === $count ) {
				continue;
			}

			if ( $status_slug === $request_status || ( empty( $request_status ) && 'all' === $status_slug ) ) {
				$status_list_item = '<li class="%1$s"><a href="%2$s" class="current">%3$s</a> (%4$d)</li>';
			} else {
				$status_list_item = '<li class="%1$s"><a href="%2$s">%3$s</a> (%4$d)</li>';
			}

			$status_name         = isset( $status_labels[ $status_slug ] ) ? $status_labels[ $status_slug ] : ucfirst( $status_slug );
			$status_filter_url   = ( 'all' === $status_slug ) ? remove_query_arg( 'status' ) : add_query_arg( 'status', $status_slug );
			$status_filter_url   = remove_query_arg( array( 'paged', 's' ), $status_filter_url );
			$status_list_items[] = sprintf( $status_list_item, esc_attr( $status_slug ), esc_url( $status_filter_url ), esc_html( $status_name ), absint( $count ) );
		}

		if ( $status_list_items ) {
			echo '<ul class="subsubsub">';
			echo implode( " | \n", $status_list_items ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo '</ul>';
		}
	}

	/**
	 * Renders the table list, we override the original class to render the table inside a form
	 * and to render any needed HTML (like the search box). By doing so the callee of a function can simple
	 * forget about any extra HTML.
	 */
	protected function display_table() {
		echo '<form id="' . esc_attr( $this->_args['plural'] ) . '-filter" method="get">';
		foreach ( $this->get_request_query_args_to_persist() as $arg ) {
			$arg_value = isset( $_GET[ $arg ] ) ? sanitize_text_field( wp_unslash( $_GET[ $arg ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			if ( ! $arg_value ) {
				continue;
			}

			echo '<input type="hidden" name="' . esc_attr( $arg ) . '" value="' . esc_attr( $arg_value ) . '" />';
		}

		if ( ! empty( $this->search_by ) ) {
			echo $this->search_box( $this->get_search_box_button_text(), 'plugin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}
		parent::display();
		echo '</form>';
	}

	/**
	 * Process any pending actions.
	 */
	public function process_actions() {
		$this->process_bulk_action();
		$this->process_row_actions();

		if ( ! empty( $_REQUEST['_wp_http_referer'] ) && ! empty( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
			wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) );
			exit;
		}
	}

	/**
	 * Render the list table page, including header, notices, status filters and table.
	 */
	public function display_page() {
		$this->prepare_items();

		echo '<div class="wrap">';
		$this->display_header();
		$this->display_admin_notices();
		$this->display_filter_by_status();
		$this->display_table();
		echo '</div>';
	}

	/**
	 * Get the text to display in the search box on the list table.
	 */
	protected function get_search_box_placeholder() {
		return esc_html__( 'Search', 'action-scheduler' );
	}

	/**
	 * Gets the screen per_page option name.
	 *
	 * @return string
	 */
	protected function get_per_page_option_name() {
		return $this->package . '_items_per_page';
	}
}
abstracts/ActionScheduler_WPCLI_Command.php000066600000004073151137657220014734 0ustar00<?php

/**
 * Abstract for WP-CLI commands.
 */
abstract class ActionScheduler_WPCLI_Command extends \WP_CLI_Command {

	const DATE_FORMAT = 'Y-m-d H:i:s O';

	/**
	 * Keyed arguments.
	 *
	 * @var string[]
	 */
	protected $args;

	/**
	 * Positional arguments.
	 *
	 * @var array<string, string>
	 */
	protected $assoc_args;

	/**
	 * Construct.
	 *
	 * @param string[]              $args       Positional arguments.
	 * @param array<string, string> $assoc_args Keyed arguments.
	 * @throws \Exception When loading a CLI command file outside of WP CLI context.
	 */
	public function __construct( array $args, array $assoc_args ) {
		if ( ! defined( 'WP_CLI' ) || ! constant( 'WP_CLI' ) ) {
			/* translators: %s php class name */
			throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), get_class( $this ) ) );
		}

		$this->args       = $args;
		$this->assoc_args = $assoc_args;
	}

	/**
	 * Execute command.
	 */
	abstract public function execute();

	/**
	 * Get the scheduled date in a human friendly format.
	 *
	 * @see ActionScheduler_ListTable::get_schedule_display_string()
	 * @param ActionScheduler_Schedule $schedule Schedule.
	 * @return string
	 */
	protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) {

		$schedule_display_string = '';

		if ( ! $schedule->get_date() ) {
			return '0000-00-00 00:00:00';
		}

		$next_timestamp = $schedule->get_date()->getTimestamp();

		$schedule_display_string .= $schedule->get_date()->format( static::DATE_FORMAT );

		return $schedule_display_string;
	}

	/**
	 * Transforms arguments with '__' from CSV into expected arrays.
	 *
	 * @see \WP_CLI\CommandWithDBObject::process_csv_arguments_to_arrays()
	 * @link https://github.com/wp-cli/entity-command/blob/c270cc9a2367cb8f5845f26a6b5e203397c91392/src/WP_CLI/CommandWithDBObject.php#L99
	 * @return void
	 */
	protected function process_csv_arguments_to_arrays() {
		foreach ( $this->assoc_args as $k => $v ) {
			if ( false !== strpos( $k, '__' ) ) {
				$this->assoc_args[ $k ] = explode( ',', $v );
			}
		}
	}

}
abstracts/ActionScheduler_Abstract_RecurringSchedule.php000066600000006346151137657230017666 0ustar00<?php

/**
 * Class ActionScheduler_Abstract_RecurringSchedule
 */
abstract class ActionScheduler_Abstract_RecurringSchedule extends ActionScheduler_Abstract_Schedule {

	/**
	 * The date & time the first instance of this schedule was setup to run (which may not be this instance).
	 *
	 * Schedule objects are attached to an action object. Each schedule stores the run date for that
	 * object as the start date - @see $this->start - and logic to calculate the next run date after
	 * that - @see $this->calculate_next(). The $first_date property also keeps a record of when the very
	 * first instance of this chain of schedules ran.
	 *
	 * @var DateTime
	 */
	private $first_date = null;

	/**
	 * Timestamp equivalent of @see $this->first_date
	 *
	 * @var int
	 */
	protected $first_timestamp = null;

	/**
	 * The recurrence between each time an action is run using this schedule.
	 * Used to calculate the start date & time. Can be a number of seconds, in the
	 * case of ActionScheduler_IntervalSchedule, or a cron expression, as in the
	 * case of ActionScheduler_CronSchedule. Or something else.
	 *
	 * @var mixed
	 */
	protected $recurrence;

	/**
	 * Construct.
	 *
	 * @param DateTime      $date The date & time to run the action.
	 * @param mixed         $recurrence The data used to determine the schedule's recurrence.
	 * @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance.
	 */
	public function __construct( DateTime $date, $recurrence, ?DateTime $first = null ) {
		parent::__construct( $date );
		$this->first_date = empty( $first ) ? $date : $first;
		$this->recurrence = $recurrence;
	}

	/**
	 * Schedule is recurring.
	 *
	 * @return bool
	 */
	public function is_recurring() {
		return true;
	}

	/**
	 * Get the date & time of the first schedule in this recurring series.
	 *
	 * @return DateTime|null
	 */
	public function get_first_date() {
		return clone $this->first_date;
	}

	/**
	 * Get the schedule's recurrence.
	 *
	 * @return string
	 */
	public function get_recurrence() {
		return $this->recurrence;
	}

	/**
	 * For PHP 5.2 compat, since DateTime objects can't be serialized
	 *
	 * @return array
	 */
	public function __sleep() {
		$sleep_params          = parent::__sleep();
		$this->first_timestamp = $this->first_date->getTimestamp();
		return array_merge(
			$sleep_params,
			array(
				'first_timestamp',
				'recurrence',
			)
		);
	}

	/**
	 * Unserialize recurring schedules serialized/stored prior to AS 3.0.0
	 *
	 * Prior to Action Scheduler 3.0.0, schedules used different property names to refer
	 * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
	 * was the same as ActionScheduler_SimpleSchedule::timestamp. This was addressed in
	 * Action Scheduler 3.0.0, where properties and property names were aligned for better
	 * inheritance. To maintain backward compatibility with scheduled serialized and stored
	 * prior to 3.0, we need to correctly map the old property names.
	 */
	public function __wakeup() {
		parent::__wakeup();
		if ( $this->first_timestamp > 0 ) {
			$this->first_date = as_get_datetime_object( $this->first_timestamp );
		} else {
			$this->first_date = $this->get_date();
		}
	}
}
abstracts/ActionScheduler_Abstract_Schema.php000066600000011443151137657230015443 0ustar00<?php


/**
 * Class ActionScheduler_Abstract_Schema
 *
 * @package Action_Scheduler
 *
 * @codeCoverageIgnore
 *
 * Utility class for creating/updating custom tables
 */
abstract class ActionScheduler_Abstract_Schema {

	/**
	 * Increment this value in derived class to trigger a schema update.
	 *
	 * @var int
	 */
	protected $schema_version = 1;

	/**
	 * Schema version stored in database.
	 *
	 * @var string
	 */
	protected $db_version;

	/**
	 * Names of tables that will be registered by this class.
	 *
	 * @var array
	 */
	protected $tables = array();

	/**
	 * Can optionally be used by concrete classes to carry out additional initialization work
	 * as needed.
	 */
	public function init() {}

	/**
	 * Register tables with WordPress, and create them if needed.
	 *
	 * @param bool $force_update Optional. Default false. Use true to always run the schema update.
	 *
	 * @return void
	 */
	public function register_tables( $force_update = false ) {
		global $wpdb;

		// make WP aware of our tables.
		foreach ( $this->tables as $table ) {
			$wpdb->tables[] = $table;
			$name           = $this->get_full_table_name( $table );
			$wpdb->$table   = $name;
		}

		// create the tables.
		if ( $this->schema_update_required() || $force_update ) {
			foreach ( $this->tables as $table ) {
				/**
				 * Allow custom processing before updating a table schema.
				 *
				 * @param string $table Name of table being updated.
				 * @param string $db_version Existing version of the table being updated.
				 */
				do_action( 'action_scheduler_before_schema_update', $table, $this->db_version );
				$this->update_table( $table );
			}
			$this->mark_schema_update_complete();
		}
	}

	/**
	 * Get table definition.
	 *
	 * @param string $table The name of the table.
	 *
	 * @return string The CREATE TABLE statement, suitable for passing to dbDelta
	 */
	abstract protected function get_table_definition( $table );

	/**
	 * Determine if the database schema is out of date
	 * by comparing the integer found in $this->schema_version
	 * with the option set in the WordPress options table
	 *
	 * @return bool
	 */
	private function schema_update_required() {
		$option_name      = 'schema-' . static::class;
		$this->db_version = get_option( $option_name, 0 );

		// Check for schema option stored by the Action Scheduler Custom Tables plugin in case site has migrated from that plugin with an older schema.
		if ( 0 === $this->db_version ) {

			$plugin_option_name = 'schema-';

			switch ( static::class ) {
				case 'ActionScheduler_StoreSchema':
					$plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Store_Table_Maker';
					break;
				case 'ActionScheduler_LoggerSchema':
					$plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Logger_Table_Maker';
					break;
			}

			$this->db_version = get_option( $plugin_option_name, 0 );

			delete_option( $plugin_option_name );
		}

		return version_compare( $this->db_version, $this->schema_version, '<' );
	}

	/**
	 * Update the option in WordPress to indicate that
	 * our schema is now up to date
	 *
	 * @return void
	 */
	private function mark_schema_update_complete() {
		$option_name = 'schema-' . static::class;

		// work around race conditions and ensure that our option updates.
		$value_to_save = (string) $this->schema_version . '.0.' . time();

		update_option( $option_name, $value_to_save );
	}

	/**
	 * Update the schema for the given table
	 *
	 * @param string $table The name of the table to update.
	 *
	 * @return void
	 */
	private function update_table( $table ) {
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		$definition = $this->get_table_definition( $table );
		if ( $definition ) {
			$updated = dbDelta( $definition );
			foreach ( $updated as $updated_table => $update_description ) {
				if ( strpos( $update_description, 'Created table' ) === 0 ) {
					do_action( 'action_scheduler/created_table', $updated_table, $table ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
				}
			}
		}
	}

	/**
	 * Get full table name.
	 *
	 * @param string $table Table name.
	 *
	 * @return string The full name of the table, including the
	 *                table prefix for the current blog
	 */
	protected function get_full_table_name( $table ) {
		return $GLOBALS['wpdb']->prefix . $table;
	}

	/**
	 * Confirms that all of the tables registered by this schema class have been created.
	 *
	 * @return bool
	 */
	public function tables_exist() {
		global $wpdb;

		$tables_exist = true;

		foreach ( $this->tables as $table_name ) {
			$table_name     = $wpdb->prefix . $table_name;
			$pattern        = str_replace( '_', '\\_', $table_name );
			$existing_table = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $pattern ) );

			if ( $existing_table !== $table_name ) {
				$tables_exist = false;
				break;
			}
		}

		return $tables_exist;
	}
}
ActionScheduler_wcSystemStatus.php000066600000012270151137657230013453 0ustar00<?php

/**
 * Class ActionScheduler_wcSystemStatus
 */
class ActionScheduler_wcSystemStatus {

	/**
	 * The active data stores
	 *
	 * @var ActionScheduler_Store
	 */
	protected $store;

	/**
	 * Constructor method for ActionScheduler_wcSystemStatus.
	 *
	 * @param ActionScheduler_Store $store Active store object.
	 *
	 * @return void
	 */
	public function __construct( $store ) {
		$this->store = $store;
	}

	/**
	 * Display action data, including number of actions grouped by status and the oldest & newest action in each status.
	 *
	 * Helpful to identify issues, like a clogged queue.
	 */
	public function render() {
		$action_counts     = $this->store->action_counts();
		$status_labels     = $this->store->get_status_labels();
		$oldest_and_newest = $this->get_oldest_and_newest( array_keys( $status_labels ) );

		$this->get_template( $status_labels, $action_counts, $oldest_and_newest );
	}

	/**
	 * Get oldest and newest scheduled dates for a given set of statuses.
	 *
	 * @param array $status_keys Set of statuses to find oldest & newest action for.
	 * @return array
	 */
	protected function get_oldest_and_newest( $status_keys ) {

		$oldest_and_newest = array();

		foreach ( $status_keys as $status ) {
			$oldest_and_newest[ $status ] = array(
				'oldest' => '&ndash;',
				'newest' => '&ndash;',
			);

			if ( 'in-progress' === $status ) {
				continue;
			}

			$oldest_and_newest[ $status ]['oldest'] = $this->get_action_status_date( $status, 'oldest' );
			$oldest_and_newest[ $status ]['newest'] = $this->get_action_status_date( $status, 'newest' );
		}

		return $oldest_and_newest;
	}

	/**
	 * Get oldest or newest scheduled date for a given status.
	 *
	 * @param string $status Action status label/name string.
	 * @param string $date_type Oldest or Newest.
	 * @return DateTime
	 */
	protected function get_action_status_date( $status, $date_type = 'oldest' ) {

		$order = 'oldest' === $date_type ? 'ASC' : 'DESC';

		$action = $this->store->query_actions(
			array(
				'claimed'  => false,
				'status'   => $status,
				'per_page' => 1,
				'order'    => $order,
			)
		);

		if ( ! empty( $action ) ) {
			$date_object = $this->store->get_date( $action[0] );
			$action_date = $date_object->format( 'Y-m-d H:i:s O' );
		} else {
			$action_date = '&ndash;';
		}

		return $action_date;
	}

	/**
	 * Get oldest or newest scheduled date for a given status.
	 *
	 * @param array $status_labels Set of statuses to find oldest & newest action for.
	 * @param array $action_counts Number of actions grouped by status.
	 * @param array $oldest_and_newest Date of the oldest and newest action with each status.
	 */
	protected function get_template( $status_labels, $action_counts, $oldest_and_newest ) {
		$as_version   = ActionScheduler_Versions::instance()->latest_version();
		$as_datastore = get_class( ActionScheduler_Store::instance() );
		?>

		<table class="wc_status_table widefat" cellspacing="0">
			<thead>
				<tr>
					<th colspan="5" data-export-label="Action Scheduler"><h2><?php esc_html_e( 'Action Scheduler', 'action-scheduler' ); ?><?php echo wc_help_tip( esc_html__( 'This section shows details of Action Scheduler.', 'action-scheduler' ) ); ?></h2></th>
				</tr>
				<tr>
					<td colspan="2" data-export-label="Version"><?php esc_html_e( 'Version:', 'action-scheduler' ); ?></td>
					<td colspan="3"><?php echo esc_html( $as_version ); ?></td>
				</tr>
				<tr>
					<td colspan="2" data-export-label="Data store"><?php esc_html_e( 'Data store:', 'action-scheduler' ); ?></td>
					<td colspan="3"><?php echo esc_html( $as_datastore ); ?></td>
				</tr>
				<tr>
					<td><strong><?php esc_html_e( 'Action Status', 'action-scheduler' ); ?></strong></td>
					<td class="help">&nbsp;</td>
					<td><strong><?php esc_html_e( 'Count', 'action-scheduler' ); ?></strong></td>
					<td><strong><?php esc_html_e( 'Oldest Scheduled Date', 'action-scheduler' ); ?></strong></td>
					<td><strong><?php esc_html_e( 'Newest Scheduled Date', 'action-scheduler' ); ?></strong></td>
				</tr>
			</thead>
			<tbody>
				<?php
				foreach ( $action_counts as $status => $count ) {
					// WC uses the 3rd column for export, so we need to display more data in that (hidden when viewed as part of the table) and add an empty 2nd column.
					printf(
						'<tr><td>%1$s</td><td>&nbsp;</td><td>%2$s<span style="display: none;">, Oldest: %3$s, Newest: %4$s</span></td><td>%3$s</td><td>%4$s</td></tr>',
						esc_html( $status_labels[ $status ] ),
						esc_html( number_format_i18n( $count ) ),
						esc_html( $oldest_and_newest[ $status ]['oldest'] ),
						esc_html( $oldest_and_newest[ $status ]['newest'] )
					);
				}
				?>
			</tbody>
		</table>

		<?php
	}

	/**
	 * Is triggered when invoking inaccessible methods in an object context.
	 *
	 * @param string $name Name of method called.
	 * @param array  $arguments Parameters to invoke the method with.
	 *
	 * @return mixed
	 * @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
	 */
	public function __call( $name, $arguments ) {
		switch ( $name ) {
			case 'print':
				_deprecated_function( __CLASS__ . '::print()', '2.2.4', __CLASS__ . '::render()' );
				return call_user_func_array( array( $this, 'render' ), $arguments );
		}

		return null;
	}
}
ActionScheduler_ActionFactory.php000066600000037657151137657230013216 0ustar00<?php

/**
 * Class ActionScheduler_ActionFactory
 */
class ActionScheduler_ActionFactory {

	/**
	 * Return stored actions for given params.
	 *
	 * @param string                        $status The action's status in the data store.
	 * @param string                        $hook The hook to trigger when this action runs.
	 * @param array                         $args Args to pass to callbacks when the hook is triggered.
	 * @param ActionScheduler_Schedule|null $schedule The action's schedule.
	 * @param string                        $group A group to put the action in.
	 * phpcs:ignore Squiz.Commenting.FunctionComment.ExtraParamComment
	 * @param int                           $priority The action priority.
	 *
	 * @return ActionScheduler_Action An instance of the stored action.
	 */
	public function get_stored_action( $status, $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) {
		// The 6th parameter ($priority) is not formally declared in the method signature to maintain compatibility with
		// third-party subclasses created before this param was added.
		$priority = func_num_args() >= 6 ? (int) func_get_arg( 5 ) : 10;

		switch ( $status ) {
			case ActionScheduler_Store::STATUS_PENDING:
				$action_class = 'ActionScheduler_Action';
				break;
			case ActionScheduler_Store::STATUS_CANCELED:
				$action_class = 'ActionScheduler_CanceledAction';
				if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) && ! is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) {
					$schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() );
				}
				break;
			default:
				$action_class = 'ActionScheduler_FinishedAction';
				break;
		}

		$action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group );

		$action = new $action_class( $hook, $args, $schedule, $group );
		$action->set_priority( $priority );

		/**
		 * Allow 3rd party code to change the instantiated action for a given hook, args, schedule and group.
		 *
		 * @param ActionScheduler_Action   $action The instantiated action.
		 * @param string                   $hook The instantiated action's hook.
		 * @param array                    $args The instantiated action's args.
		 * @param ActionScheduler_Schedule $schedule The instantiated action's schedule.
		 * @param string                   $group The instantiated action's group.
		 * @param int                      $priority The action priority.
		 */
		return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group, $priority );
	}

	/**
	 * Enqueue an action to run one time, as soon as possible (rather a specific scheduled time).
	 *
	 * This method creates a new action using the NullSchedule. In practice, this results in an action scheduled to
	 * execute "now". Therefore, it will generally run as soon as possible but is not prioritized ahead of other actions
	 * that are already past-due.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param string $group A group to put the action in.
	 *
	 * @return int The ID of the stored action.
	 */
	public function async( $hook, $args = array(), $group = '' ) {
		return $this->async_unique( $hook, $args, $group, false );
	}

	/**
	 * Same as async, but also supports $unique param.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param string $group A group to put the action in.
	 * @param bool   $unique Whether to ensure the action is unique.
	 *
	 * @return int The ID of the stored action.
	 */
	public function async_unique( $hook, $args = array(), $group = '', $unique = true ) {
		$schedule = new ActionScheduler_NullSchedule();
		$action   = new ActionScheduler_Action( $hook, $args, $schedule, $group );
		return $unique ? $this->store_unique_action( $action, $unique ) : $this->store( $action );
	}

	/**
	 * Create single action.
	 *
	 * @param string $hook  The hook to trigger when this action runs.
	 * @param array  $args  Args to pass when the hook is triggered.
	 * @param int    $when  Unix timestamp when the action will run.
	 * @param string $group A group to put the action in.
	 *
	 * @return int The ID of the stored action.
	 */
	public function single( $hook, $args = array(), $when = null, $group = '' ) {
		return $this->single_unique( $hook, $args, $when, $group, false );
	}

	/**
	 * Create single action only if there is no pending or running action with same name and params.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param int    $when Unix timestamp when the action will run.
	 * @param string $group A group to put the action in.
	 * @param bool   $unique Whether action scheduled should be unique.
	 *
	 * @return int The ID of the stored action.
	 */
	public function single_unique( $hook, $args = array(), $when = null, $group = '', $unique = true ) {
		$date     = as_get_datetime_object( $when );
		$schedule = new ActionScheduler_SimpleSchedule( $date );
		$action   = new ActionScheduler_Action( $hook, $args, $schedule, $group );
		return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
	}

	/**
	 * Create the first instance of an action recurring on a given interval.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param int    $first Unix timestamp for the first run.
	 * @param int    $interval Seconds between runs.
	 * @param string $group A group to put the action in.
	 *
	 * @return int The ID of the stored action.
	 */
	public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
		return $this->recurring_unique( $hook, $args, $first, $interval, $group, false );
	}

	/**
	 * Create the first instance of an action recurring on a given interval only if there is no pending or running action with same name and params.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param int    $first Unix timestamp for the first run.
	 * @param int    $interval Seconds between runs.
	 * @param string $group A group to put the action in.
	 * @param bool   $unique Whether action scheduled should be unique.
	 *
	 * @return int The ID of the stored action.
	 */
	public function recurring_unique( $hook, $args = array(), $first = null, $interval = null, $group = '', $unique = true ) {
		if ( empty( $interval ) ) {
			return $this->single_unique( $hook, $args, $first, $group, $unique );
		}
		$date     = as_get_datetime_object( $first );
		$schedule = new ActionScheduler_IntervalSchedule( $date, $interval );
		$action   = new ActionScheduler_Action( $hook, $args, $schedule, $group );
		return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
	}

	/**
	 * Create the first instance of an action recurring on a Cron schedule.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param int    $base_timestamp The first instance of the action will be scheduled
	 *        to run at a time calculated after this timestamp matching the cron
	 *        expression. This can be used to delay the first instance of the action.
	 * @param int    $schedule A cron definition string.
	 * @param string $group A group to put the action in.
	 *
	 * @return int The ID of the stored action.
	 */
	public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) {
		return $this->cron_unique( $hook, $args, $base_timestamp, $schedule, $group, false );
	}


	/**
	 * Create the first instance of an action recurring on a Cron schedule only if there is no pending or running action with same name and params.
	 *
	 * @param string $hook The hook to trigger when this action runs.
	 * @param array  $args Args to pass when the hook is triggered.
	 * @param int    $base_timestamp The first instance of the action will be scheduled
	 *        to run at a time calculated after this timestamp matching the cron
	 *        expression. This can be used to delay the first instance of the action.
	 * @param int    $schedule A cron definition string.
	 * @param string $group A group to put the action in.
	 * @param bool   $unique Whether action scheduled should be unique.
	 *
	 * @return int The ID of the stored action.
	 **/
	public function cron_unique( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '', $unique = true ) {
		if ( empty( $schedule ) ) {
			return $this->single_unique( $hook, $args, $base_timestamp, $group, $unique );
		}
		$date     = as_get_datetime_object( $base_timestamp );
		$cron     = CronExpression::factory( $schedule );
		$schedule = new ActionScheduler_CronSchedule( $date, $cron );
		$action   = new ActionScheduler_Action( $hook, $args, $schedule, $group );
		return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
	}

	/**
	 * Create a successive instance of a recurring or cron action.
	 *
	 * Importantly, the action will be rescheduled to run based on the current date/time.
	 * That means when the action is scheduled to run in the past, the next scheduled date
	 * will be pushed forward. For example, if a recurring action set to run every hour
	 * was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the
	 * future, which is 1 hour and 5 seconds from when it was last scheduled to run.
	 *
	 * Alternatively, if the action is scheduled to run in the future, and is run early,
	 * likely via manual intervention, then its schedule will change based on the time now.
	 * For example, if a recurring action set to run every day, and is run 12 hours early,
	 * it will run again in 24 hours, not 36 hours.
	 *
	 * This slippage is less of an issue with Cron actions, as the specific run time can
	 * be set for them to run, e.g. 1am each day. In those cases, and entire period would
	 * need to be missed before there was any change is scheduled, e.g. in the case of an
	 * action scheduled for 1am each day, the action would need to run an entire day late.
	 *
	 * @param ActionScheduler_Action $action The existing action.
	 *
	 * @return string The ID of the stored action
	 * @throws InvalidArgumentException If $action is not a recurring action.
	 */
	public function repeat( $action ) {
		$schedule = $action->get_schedule();
		$next     = $schedule->get_next( as_get_datetime_object() );

		if ( is_null( $next ) || ! $schedule->is_recurring() ) {
			throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) );
		}

		$schedule_class = get_class( $schedule );
		$new_schedule   = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() );
		$new_action     = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() );
		$new_action->set_priority( $action->get_priority() );
		return $this->store( $new_action );
	}

	/**
	 * Creates a scheduled action.
	 *
	 * This general purpose method can be used in place of specific methods such as async(),
	 * async_unique(), single() or single_unique(), etc.
	 *
	 * @internal Not intended for public use, should not be overridden by subclasses.
	 *
	 * @param array $options {
	 *     Describes the action we wish to schedule.
	 *
	 *     @type string     $type      Must be one of 'async', 'cron', 'recurring', or 'single'.
	 *     @type string     $hook      The hook to be executed.
	 *     @type array      $arguments Arguments to be passed to the callback.
	 *     @type string     $group     The action group.
	 *     @type bool       $unique    If the action should be unique.
	 *     @type int        $when      Timestamp. Indicates when the action, or first instance of the action in the case
	 *                                 of recurring or cron actions, becomes due.
	 *     @type int|string $pattern   Recurrence pattern. This is either an interval in seconds for recurring actions
	 *                                 or a cron expression for cron actions.
	 *     @type int        $priority  Lower values means higher priority. Should be in the range 0-255.
	 * }
	 *
	 * @return int The action ID. Zero if there was an error scheduling the action.
	 */
	public function create( array $options = array() ) {
		$defaults = array(
			'type'      => 'single',
			'hook'      => '',
			'arguments' => array(),
			'group'     => '',
			'unique'    => false,
			'when'      => time(),
			'pattern'   => null,
			'priority'  => 10,
		);

		$options = array_merge( $defaults, $options );

		// Cron/recurring actions without a pattern are treated as single actions (this gives calling code the ability
		// to use functions like as_schedule_recurring_action() to schedule recurring as well as single actions).
		if ( ( 'cron' === $options['type'] || 'recurring' === $options['type'] ) && empty( $options['pattern'] ) ) {
			$options['type'] = 'single';
		}

		switch ( $options['type'] ) {
			case 'async':
				$schedule = new ActionScheduler_NullSchedule();
				break;

			case 'cron':
				$date     = as_get_datetime_object( $options['when'] );
				$cron     = CronExpression::factory( $options['pattern'] );
				$schedule = new ActionScheduler_CronSchedule( $date, $cron );
				break;

			case 'recurring':
				$date     = as_get_datetime_object( $options['when'] );
				$schedule = new ActionScheduler_IntervalSchedule( $date, $options['pattern'] );
				break;

			case 'single':
				$date     = as_get_datetime_object( $options['when'] );
				$schedule = new ActionScheduler_SimpleSchedule( $date );
				break;

			default:
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
				error_log( "Unknown action type '{$options['type']}' specified when trying to create an action for '{$options['hook']}'." );
				return 0;
		}

		$action = new ActionScheduler_Action( $options['hook'], $options['arguments'], $schedule, $options['group'] );
		$action->set_priority( $options['priority'] );

		$action_id = 0;
		try {
			$action_id = $options['unique'] ? $this->store_unique_action( $action ) : $this->store( $action );
		} catch ( Exception $e ) {
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
			error_log(
				sprintf(
					/* translators: %1$s is the name of the hook to be enqueued, %2$s is the exception message. */
					__( 'Caught exception while enqueuing action "%1$s": %2$s', 'action-scheduler' ),
					$options['hook'],
					$e->getMessage()
				)
			);
		}
		return $action_id;
	}

	/**
	 * Save action to database.
	 *
	 * @param ActionScheduler_Action $action Action object to save.
	 *
	 * @return int The ID of the stored action
	 */
	protected function store( ActionScheduler_Action $action ) {
		$store = ActionScheduler_Store::instance();
		return $store->save_action( $action );
	}

	/**
	 * Store action if it's unique.
	 *
	 * @param ActionScheduler_Action $action Action object to store.
	 *
	 * @return int ID of the created action. Will be 0 if action was not created.
	 */
	protected function store_unique_action( ActionScheduler_Action $action ) {
		$store = ActionScheduler_Store::instance();
		if ( method_exists( $store, 'save_unique_action' ) ) {
			return $store->save_unique_action( $action );
		} else {
			/**
			 * Fallback to non-unique action if the store doesn't support unique actions.
			 * We try to save the action as unique, accepting that there might be a race condition.
			 * This is likely still better than giving up on unique actions entirely.
			 */
			$existing_action_id = (int) $store->find_action(
				$action->get_hook(),
				array(
					'args'   => $action->get_args(),
					'status' => ActionScheduler_Store::STATUS_PENDING,
					'group'  => $action->get_group(),
				)
			);
			if ( $existing_action_id > 0 ) {
				return 0;
			}
			return $store->save_action( $action );
		}
	}
}
ActionScheduler_NullLogEntry.php000066600000000512151137657230013023 0ustar00<?php

/**
 * Class ActionScheduler_NullLogEntry
 */
class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry {

	/**
	 * Construct.
	 *
	 * @param string $action_id Action ID.
	 * @param string $message   Log entry.
	 */
	public function __construct( $action_id = '', $message = '' ) {
		// nothing to see here.
	}

}
ActionScheduler_QueueCleaner.php000066600000017607151137657230013020 0ustar00<?php

/**
 * Class ActionScheduler_QueueCleaner
 */
class ActionScheduler_QueueCleaner {

	/**
	 * The batch size.
	 *
	 * @var int
	 */
	protected $batch_size;

	/**
	 * ActionScheduler_Store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $store = null;

	/**
	 * 31 days in seconds.
	 *
	 * @var int
	 */
	private $month_in_seconds = 2678400;

	/**
	 * Default list of statuses purged by the cleaner process.
	 *
	 * @var string[]
	 */
	private $default_statuses_to_purge = array(
		ActionScheduler_Store::STATUS_COMPLETE,
		ActionScheduler_Store::STATUS_CANCELED,
	);

	/**
	 * ActionScheduler_QueueCleaner constructor.
	 *
	 * @param ActionScheduler_Store|null $store      The store instance.
	 * @param int                        $batch_size The batch size.
	 */
	public function __construct( ?ActionScheduler_Store $store = null, $batch_size = 20 ) {
		$this->store      = $store ? $store : ActionScheduler_Store::instance();
		$this->batch_size = $batch_size;
	}

	/**
	 * Default queue cleaner process used by queue runner.
	 *
	 * @return array
	 */
	public function delete_old_actions() {
		/**
		 * Filter the minimum scheduled date age for action deletion.
		 *
		 * @param int $retention_period Minimum scheduled age in seconds of the actions to be deleted.
		 */
		$lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds );

		try {
			$cutoff = as_get_datetime_object( $lifespan . ' seconds ago' );
		} catch ( Exception $e ) {
			_doing_it_wrong(
				__METHOD__,
				sprintf(
					/* Translators: %s is the exception message. */
					esc_html__( 'It was not possible to determine a valid cut-off time: %s.', 'action-scheduler' ),
					esc_html( $e->getMessage() )
				),
				'3.5.5'
			);

			return array();
		}

		/**
		 * Filter the statuses when cleaning the queue.
		 *
		 * @param string[] $default_statuses_to_purge Action statuses to clean.
		 */
		$statuses_to_purge = (array) apply_filters( 'action_scheduler_default_cleaner_statuses', $this->default_statuses_to_purge );

		return $this->clean_actions( $statuses_to_purge, $cutoff, $this->get_batch_size() );
	}

	/**
	 * Delete selected actions limited by status and date.
	 *
	 * @param string[] $statuses_to_purge List of action statuses to purge. Defaults to canceled, complete.
	 * @param DateTime $cutoff_date Date limit for selecting actions. Defaults to 31 days ago.
	 * @param int|null $batch_size Maximum number of actions per status to delete. Defaults to 20.
	 * @param string   $context Calling process context. Defaults to `old`.
	 * @return array Actions deleted.
	 */
	public function clean_actions( array $statuses_to_purge, DateTime $cutoff_date, $batch_size = null, $context = 'old' ) {
		$batch_size = ! is_null( $batch_size ) ? $batch_size : $this->batch_size;
		$cutoff     = ! is_null( $cutoff_date ) ? $cutoff_date : as_get_datetime_object( $this->month_in_seconds . ' seconds ago' );
		$lifespan   = time() - $cutoff->getTimestamp();

		if ( empty( $statuses_to_purge ) ) {
			$statuses_to_purge = $this->default_statuses_to_purge;
		}

		$deleted_actions = array();

		foreach ( $statuses_to_purge as $status ) {
			$actions_to_delete = $this->store->query_actions(
				array(
					'status'           => $status,
					'modified'         => $cutoff,
					'modified_compare' => '<=',
					'per_page'         => $batch_size,
					'orderby'          => 'none',
				)
			);

			$deleted_actions = array_merge( $deleted_actions, $this->delete_actions( $actions_to_delete, $lifespan, $context ) );
		}

		return $deleted_actions;
	}

	/**
	 * Delete actions.
	 *
	 * @param int[]  $actions_to_delete List of action IDs to delete.
	 * @param int    $lifespan Minimum scheduled age in seconds of the actions being deleted.
	 * @param string $context Context of the delete request.
	 * @return array Deleted action IDs.
	 */
	private function delete_actions( array $actions_to_delete, $lifespan = null, $context = 'old' ) {
		$deleted_actions = array();

		if ( is_null( $lifespan ) ) {
			$lifespan = $this->month_in_seconds;
		}

		foreach ( $actions_to_delete as $action_id ) {
			try {
				$this->store->delete_action( $action_id );
				$deleted_actions[] = $action_id;
			} catch ( Exception $e ) {
				/**
				 * Notify 3rd party code of exceptions when deleting a completed action older than the retention period
				 *
				 * This hook provides a way for 3rd party code to log or otherwise handle exceptions relating to their
				 * actions.
				 *
				 * @param int $action_id The scheduled actions ID in the data store
				 * @param Exception $e The exception thrown when attempting to delete the action from the data store
				 * @param int $lifespan The retention period, in seconds, for old actions
				 * @param int $count_of_actions_to_delete The number of old actions being deleted in this batch
				 * @since 2.0.0
				 */
				do_action( "action_scheduler_failed_{$context}_action_deletion", $action_id, $e, $lifespan, count( $actions_to_delete ) );
			}
		}
		return $deleted_actions;
	}

	/**
	 * Unclaim pending actions that have not been run within a given time limit.
	 *
	 * When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
	 * as a parameter is 10x the time limit used for queue processing.
	 *
	 * @param int $time_limit The number of seconds to allow a queue to run before unclaiming its pending actions. Default 300 (5 minutes).
	 */
	public function reset_timeouts( $time_limit = 300 ) {
		$timeout = apply_filters( 'action_scheduler_timeout_period', $time_limit );

		if ( $timeout < 0 ) {
			return;
		}

		$cutoff           = as_get_datetime_object( $timeout . ' seconds ago' );
		$actions_to_reset = $this->store->query_actions(
			array(
				'status'           => ActionScheduler_Store::STATUS_PENDING,
				'modified'         => $cutoff,
				'modified_compare' => '<=',
				'claimed'          => true,
				'per_page'         => $this->get_batch_size(),
				'orderby'          => 'none',
			)
		);

		foreach ( $actions_to_reset as $action_id ) {
			$this->store->unclaim_action( $action_id );
			do_action( 'action_scheduler_reset_action', $action_id );
		}
	}

	/**
	 * Mark actions that have been running for more than a given time limit as failed, based on
	 * the assumption some uncatchable and unloggable fatal error occurred during processing.
	 *
	 * When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
	 * as a parameter is 10x the time limit used for queue processing.
	 *
	 * @param int $time_limit The number of seconds to allow an action to run before it is considered to have failed. Default 300 (5 minutes).
	 */
	public function mark_failures( $time_limit = 300 ) {
		$timeout = apply_filters( 'action_scheduler_failure_period', $time_limit );

		if ( $timeout < 0 ) {
			return;
		}

		$cutoff           = as_get_datetime_object( $timeout . ' seconds ago' );
		$actions_to_reset = $this->store->query_actions(
			array(
				'status'           => ActionScheduler_Store::STATUS_RUNNING,
				'modified'         => $cutoff,
				'modified_compare' => '<=',
				'per_page'         => $this->get_batch_size(),
				'orderby'          => 'none',
			)
		);

		foreach ( $actions_to_reset as $action_id ) {
			$this->store->mark_failure( $action_id );
			do_action( 'action_scheduler_failed_action', $action_id, $timeout );
		}
	}

	/**
	 * Do all of the cleaning actions.
	 *
	 * @param int $time_limit The number of seconds to use as the timeout and failure period. Default 300 (5 minutes).
	 */
	public function clean( $time_limit = 300 ) {
		$this->delete_old_actions();
		$this->reset_timeouts( $time_limit );
		$this->mark_failures( $time_limit );
	}

	/**
	 * Get the batch size for cleaning the queue.
	 *
	 * @return int
	 */
	protected function get_batch_size() {
		/**
		 * Filter the batch size when cleaning the queue.
		 *
		 * @param int $batch_size The number of actions to clean in one batch.
		 */
		return absint( apply_filters( 'action_scheduler_cleanup_batch_size', $this->batch_size ) );
	}
}
ActionScheduler_FatalErrorMonitor.php000066600000005005151137657230014040 0ustar00<?php

/**
 * Class ActionScheduler_FatalErrorMonitor
 */
class ActionScheduler_FatalErrorMonitor {

	/**
	 * ActionScheduler_ActionClaim instance.
	 *
	 * @var ActionScheduler_ActionClaim
	 */
	private $claim = null;

	/**
	 * ActionScheduler_Store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $store = null;

	/**
	 * Current action's ID.
	 *
	 * @var int
	 */
	private $action_id = 0;

	/**
	 * Construct.
	 *
	 * @param ActionScheduler_Store $store Action store.
	 */
	public function __construct( ActionScheduler_Store $store ) {
		$this->store = $store;
	}

	/**
	 * Start monitoring.
	 *
	 * @param ActionScheduler_ActionClaim $claim Claimed actions.
	 */
	public function attach( ActionScheduler_ActionClaim $claim ) {
		$this->claim = $claim;
		add_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
		add_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 );
		add_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 );
		add_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0, 0 );
		add_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 );
	}

	/**
	 * Stop monitoring.
	 */
	public function detach() {
		$this->claim = null;
		$this->untrack_action();
		remove_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
		remove_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0 );
		remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0 );
		remove_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0 );
		remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0 );
	}

	/**
	 * Track specified action.
	 *
	 * @param int $action_id Action ID to track.
	 */
	public function track_current_action( $action_id ) {
		$this->action_id = $action_id;
	}

	/**
	 * Un-track action.
	 */
	public function untrack_action() {
		$this->action_id = 0;
	}

	/**
	 * Handle unexpected shutdown.
	 */
	public function handle_unexpected_shutdown() {
		$error = error_get_last();

		if ( $error ) {
			if ( in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ), true ) ) {
				if ( ! empty( $this->action_id ) ) {
					$this->store->mark_failure( $this->action_id );
					do_action( 'action_scheduler_unexpected_shutdown', $this->action_id, $error );
				}
			}

			$this->store->release_claim( $this->claim );
		}
	}
}
ActionScheduler_ActionClaim.php000066600000001214151137657230012610 0ustar00<?php

/**
 * Class ActionScheduler_ActionClaim
 */
class ActionScheduler_ActionClaim {
	/**
	 * Claim ID.
	 *
	 * @var string
	 */
	private $id = '';

	/**
	 * Claimed action IDs.
	 *
	 * @var int[]
	 */
	private $action_ids = array();

	/**
	 * Construct.
	 *
	 * @param string $id Claim ID.
	 * @param int[]  $action_ids Action IDs.
	 */
	public function __construct( $id, array $action_ids ) {
		$this->id         = $id;
		$this->action_ids = $action_ids;
	}

	/**
	 * Get claim ID.
	 */
	public function get_id() {
		return $this->id;
	}

	/**
	 * Get IDs of claimed actions.
	 */
	public function get_actions() {
		return $this->action_ids;
	}
}
data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php000066600000003711151137657230020722 0ustar00<?php

/**
 * Class ActionScheduler_wpPostStore_PostTypeRegistrar
 *
 * @codeCoverageIgnore
 */
class ActionScheduler_wpPostStore_PostTypeRegistrar {
	/**
	 * Registrar.
	 */
	public function register() {
		register_post_type( ActionScheduler_wpPostStore::POST_TYPE, $this->post_type_args() );
	}

	/**
	 * Build the args array for the post type definition
	 *
	 * @return array
	 */
	protected function post_type_args() {
		$args = array(
			'label'        => __( 'Scheduled Actions', 'action-scheduler' ),
			'description'  => __( 'Scheduled actions are hooks triggered on a certain date and time.', 'action-scheduler' ),
			'public'       => false,
			'map_meta_cap' => true,
			'hierarchical' => false,
			'supports'     => array( 'title', 'editor', 'comments' ),
			'rewrite'      => false,
			'query_var'    => false,
			'can_export'   => true,
			'ep_mask'      => EP_NONE,
			'labels'       => array(
				'name'               => __( 'Scheduled Actions', 'action-scheduler' ),
				'singular_name'      => __( 'Scheduled Action', 'action-scheduler' ),
				'menu_name'          => _x( 'Scheduled Actions', 'Admin menu name', 'action-scheduler' ),
				'add_new'            => __( 'Add', 'action-scheduler' ),
				'add_new_item'       => __( 'Add New Scheduled Action', 'action-scheduler' ),
				'edit'               => __( 'Edit', 'action-scheduler' ),
				'edit_item'          => __( 'Edit Scheduled Action', 'action-scheduler' ),
				'new_item'           => __( 'New Scheduled Action', 'action-scheduler' ),
				'view'               => __( 'View Action', 'action-scheduler' ),
				'view_item'          => __( 'View Action', 'action-scheduler' ),
				'search_items'       => __( 'Search Scheduled Actions', 'action-scheduler' ),
				'not_found'          => __( 'No actions found', 'action-scheduler' ),
				'not_found_in_trash' => __( 'No actions found in trash', 'action-scheduler' ),
			),
		);

		$args = apply_filters( 'action_scheduler_post_type_args', $args );
		return $args;
	}
}
data-stores/ActionScheduler_wpPostStore.php000066600000106256151137657230015200 0ustar00<?php

/**
 * Class ActionScheduler_wpPostStore
 */
class ActionScheduler_wpPostStore extends ActionScheduler_Store {
	const POST_TYPE         = 'scheduled-action';
	const GROUP_TAXONOMY    = 'action-group';
	const SCHEDULE_META_KEY = '_action_manager_schedule';
	const DEPENDENCIES_MET  = 'as-post-store-dependencies-met';

	/**
	 * Used to share information about the before_date property of claims internally.
	 *
	 * This is used in preference to passing the same information as a method param
	 * for backwards-compatibility reasons.
	 *
	 * @var DateTime|null
	 */
	private $claim_before_date = null;

	/**
	 * Local Timezone.
	 *
	 * @var DateTimeZone
	 */
	protected $local_timezone = null;

	/**
	 * Save action.
	 *
	 * @param ActionScheduler_Action $action Scheduled Action.
	 * @param DateTime|null          $scheduled_date Scheduled Date.
	 *
	 * @throws RuntimeException Throws an exception if the action could not be saved.
	 * @return int
	 */
	public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) {
		try {
			$this->validate_action( $action );
			$post_array = $this->create_post_array( $action, $scheduled_date );
			$post_id    = $this->save_post_array( $post_array );
			$this->save_post_schedule( $post_id, $action->get_schedule() );
			$this->save_action_group( $post_id, $action->get_group() );
			do_action( 'action_scheduler_stored_action', $post_id );
			return $post_id;
		} catch ( Exception $e ) {
			/* translators: %s: action error message */
			throw new RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
		}
	}

	/**
	 * Create post array.
	 *
	 * @param ActionScheduler_Action $action Scheduled Action.
	 * @param DateTime|null          $scheduled_date Scheduled Date.
	 *
	 * @return array Returns an array of post data.
	 */
	protected function create_post_array( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) {
		$post = array(
			'post_type'     => self::POST_TYPE,
			'post_title'    => $action->get_hook(),
			'post_content'  => wp_json_encode( $action->get_args() ),
			'post_status'   => ( $action->is_finished() ? 'publish' : 'pending' ),
			'post_date_gmt' => $this->get_scheduled_date_string( $action, $scheduled_date ),
			'post_date'     => $this->get_scheduled_date_string_local( $action, $scheduled_date ),
		);
		return $post;
	}

	/**
	 * Save post array.
	 *
	 * @param array $post_array Post array.
	 * @return int Returns the post ID.
	 * @throws RuntimeException Throws an exception if the action could not be saved.
	 */
	protected function save_post_array( $post_array ) {
		add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
		add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );

		$has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );

		if ( $has_kses ) {
			// Prevent KSES from corrupting JSON in post_content.
			kses_remove_filters();
		}

		$post_id = wp_insert_post( $post_array );

		if ( $has_kses ) {
			kses_init_filters();
		}

		remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
		remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );

		if ( is_wp_error( $post_id ) || empty( $post_id ) ) {
			throw new RuntimeException( __( 'Unable to save action.', 'action-scheduler' ) );
		}
		return $post_id;
	}

	/**
	 * Filter insert post data.
	 *
	 * @param array $postdata Post data to filter.
	 *
	 * @return array
	 */
	public function filter_insert_post_data( $postdata ) {
		if ( self::POST_TYPE === $postdata['post_type'] ) {
			$postdata['post_author'] = 0;
			if ( 'future' === $postdata['post_status'] ) {
				$postdata['post_status'] = 'publish';
			}
		}
		return $postdata;
	}

	/**
	 * Create a (probably unique) post name for scheduled actions in a more performant manner than wp_unique_post_slug().
	 *
	 * When an action's post status is transitioned to something other than 'draft', 'pending' or 'auto-draft, like 'publish'
	 * or 'failed' or 'trash', WordPress will find a unique slug (stored in post_name column) using the wp_unique_post_slug()
	 * function. This is done to ensure URL uniqueness. The approach taken by wp_unique_post_slug() is to iterate over existing
	 * post_name values that match, and append a number 1 greater than the largest. This makes sense when manually creating a
	 * post from the Edit Post screen. It becomes a bottleneck when automatically processing thousands of actions, with a
	 * database containing thousands of related post_name values.
	 *
	 * WordPress 5.1 introduces the 'pre_wp_unique_post_slug' filter for plugins to address this issue.
	 *
	 * We can short-circuit WordPress's wp_unique_post_slug() approach using the 'pre_wp_unique_post_slug' filter. This
	 * method is available to be used as a callback on that filter. It provides a more scalable approach to generating a
	 * post_name/slug that is probably unique. Because Action Scheduler never actually uses the post_name field, or an
	 * action's slug, being probably unique is good enough.
	 *
	 * For more backstory on this issue, see:
	 * - https://github.com/woocommerce/action-scheduler/issues/44 and
	 * - https://core.trac.wordpress.org/ticket/21112
	 *
	 * @param string $override_slug Short-circuit return value.
	 * @param string $slug          The desired slug (post_name).
	 * @param int    $post_ID       Post ID.
	 * @param string $post_status   The post status.
	 * @param string $post_type     Post type.
	 * @return string
	 */
	public function set_unique_post_slug( $override_slug, $slug, $post_ID, $post_status, $post_type ) {
		if ( self::POST_TYPE === $post_type ) {
			$override_slug = uniqid( self::POST_TYPE . '-', true ) . '-' . wp_generate_password( 32, false );
		}
		return $override_slug;
	}

	/**
	 * Save post schedule.
	 *
	 * @param int    $post_id  Post ID of the scheduled action.
	 * @param string $schedule Schedule to save.
	 *
	 * @return void
	 */
	protected function save_post_schedule( $post_id, $schedule ) {
		update_post_meta( $post_id, self::SCHEDULE_META_KEY, $schedule );
	}

	/**
	 * Save action group.
	 *
	 * @param int    $post_id Post ID.
	 * @param string $group   Group to save.
	 * @return void
	 */
	protected function save_action_group( $post_id, $group ) {
		if ( empty( $group ) ) {
			wp_set_object_terms( $post_id, array(), self::GROUP_TAXONOMY, false );
		} else {
			wp_set_object_terms( $post_id, array( $group ), self::GROUP_TAXONOMY, false );
		}
	}

	/**
	 * Fetch actions.
	 *
	 * @param int $action_id Action ID.
	 * @return object
	 */
	public function fetch_action( $action_id ) {
		$post = $this->get_post( $action_id );
		if ( empty( $post ) || self::POST_TYPE !== $post->post_type ) {
			return $this->get_null_action();
		}

		try {
			$action = $this->make_action_from_post( $post );
		} catch ( ActionScheduler_InvalidActionException $exception ) {
			do_action( 'action_scheduler_failed_fetch_action', $post->ID, $exception );
			return $this->get_null_action();
		}

		return $action;
	}

	/**
	 * Get post.
	 *
	 * @param string $action_id - Action ID.
	 * @return WP_Post|null
	 */
	protected function get_post( $action_id ) {
		if ( empty( $action_id ) ) {
			return null;
		}
		return get_post( $action_id );
	}

	/**
	 * Get NULL action.
	 *
	 * @return ActionScheduler_NullAction
	 */
	protected function get_null_action() {
		return new ActionScheduler_NullAction();
	}

	/**
	 * Make action from post.
	 *
	 * @param WP_Post $post Post object.
	 * @return WP_Post
	 */
	protected function make_action_from_post( $post ) {
		$hook = $post->post_title;

		$args = json_decode( $post->post_content, true );
		$this->validate_args( $args, $post->ID );

		$schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true );
		$this->validate_schedule( $schedule, $post->ID );

		$group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array( 'fields' => 'names' ) );
		$group = empty( $group ) ? '' : reset( $group );

		return ActionScheduler::factory()->get_stored_action( $this->get_action_status_by_post_status( $post->post_status ), $hook, $args, $schedule, $group );
	}

	/**
	 * Get action status by post status.
	 *
	 * @param string $post_status Post status.
	 *
	 * @throws InvalidArgumentException Throw InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels().
	 * @return string
	 */
	protected function get_action_status_by_post_status( $post_status ) {

		switch ( $post_status ) {
			case 'publish':
				$action_status = self::STATUS_COMPLETE;
				break;
			case 'trash':
				$action_status = self::STATUS_CANCELED;
				break;
			default:
				if ( ! array_key_exists( $post_status, $this->get_status_labels() ) ) {
					throw new InvalidArgumentException( sprintf( 'Invalid post status: "%s". No matching action status available.', $post_status ) );
				}
				$action_status = $post_status;
				break;
		}

		return $action_status;
	}

	/**
	 * Get post status by action status.
	 *
	 * @param string $action_status Action status.
	 *
	 * @throws InvalidArgumentException Throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels().
	 * @return string
	 */
	protected function get_post_status_by_action_status( $action_status ) {

		switch ( $action_status ) {
			case self::STATUS_COMPLETE:
				$post_status = 'publish';
				break;
			case self::STATUS_CANCELED:
				$post_status = 'trash';
				break;
			default:
				if ( ! array_key_exists( $action_status, $this->get_status_labels() ) ) {
					throw new InvalidArgumentException( sprintf( 'Invalid action status: "%s".', $action_status ) );
				}
				$post_status = $action_status;
				break;
		}

		return $post_status;
	}

	/**
	 * Returns the SQL statement to query (or count) actions.
	 *
	 * @param array  $query            - Filtering options.
	 * @param string $select_or_count  - Whether the SQL should select and return the IDs or just the row count.
	 *
	 * @throws InvalidArgumentException - Throw InvalidArgumentException if $select_or_count not count or select.
	 * @return string SQL statement. The returned SQL is already properly escaped.
	 */
	protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) {

		if ( ! in_array( $select_or_count, array( 'select', 'count' ), true ) ) {
			throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
		}

		$query = wp_parse_args(
			$query,
			array(
				'hook'             => '',
				'args'             => null,
				'date'             => null,
				'date_compare'     => '<=',
				'modified'         => null,
				'modified_compare' => '<=',
				'group'            => '',
				'status'           => '',
				'claimed'          => null,
				'per_page'         => 5,
				'offset'           => 0,
				'orderby'          => 'date',
				'order'            => 'ASC',
				'search'           => '',
			)
		);

		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;
		$sql        = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID ';
		$sql       .= "FROM {$wpdb->posts} p";
		$sql_params = array();
		if ( empty( $query['group'] ) && 'group' === $query['orderby'] ) {
			$sql .= " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
			$sql .= " LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
			$sql .= " LEFT JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
		} elseif ( ! empty( $query['group'] ) ) {
			$sql         .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
			$sql         .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
			$sql         .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
			$sql         .= ' AND t.slug=%s';
			$sql_params[] = $query['group'];
		}
		$sql         .= ' WHERE post_type=%s';
		$sql_params[] = self::POST_TYPE;
		if ( $query['hook'] ) {
			$sql         .= ' AND p.post_title=%s';
			$sql_params[] = $query['hook'];
		}
		if ( ! is_null( $query['args'] ) ) {
			$sql         .= ' AND p.post_content=%s';
			$sql_params[] = wp_json_encode( $query['args'] );
		}

		if ( $query['status'] ) {
			$post_statuses = array_map( array( $this, 'get_post_status_by_action_status' ), (array) $query['status'] );
			$placeholders  = array_fill( 0, count( $post_statuses ), '%s' );
			$sql          .= ' AND p.post_status IN (' . join( ', ', $placeholders ) . ')';
			$sql_params    = array_merge( $sql_params, array_values( $post_statuses ) );
		}

		if ( $query['date'] instanceof DateTime ) {
			$date = clone $query['date'];
			$date->setTimezone( new DateTimeZone( 'UTC' ) );
			$date_string  = $date->format( 'Y-m-d H:i:s' );
			$comparator   = $this->validate_sql_comparator( $query['date_compare'] );
			$sql         .= " AND p.post_date_gmt $comparator %s";
			$sql_params[] = $date_string;
		}

		if ( $query['modified'] instanceof DateTime ) {
			$modified = clone $query['modified'];
			$modified->setTimezone( new DateTimeZone( 'UTC' ) );
			$date_string  = $modified->format( 'Y-m-d H:i:s' );
			$comparator   = $this->validate_sql_comparator( $query['modified_compare'] );
			$sql         .= " AND p.post_modified_gmt $comparator %s";
			$sql_params[] = $date_string;
		}

		if ( true === $query['claimed'] ) {
			$sql .= " AND p.post_password != ''";
		} elseif ( false === $query['claimed'] ) {
			$sql .= " AND p.post_password = ''";
		} elseif ( ! is_null( $query['claimed'] ) ) {
			$sql         .= ' AND p.post_password = %s';
			$sql_params[] = $query['claimed'];
		}

		if ( ! empty( $query['search'] ) ) {
			$sql .= ' AND (p.post_title LIKE %s OR p.post_content LIKE %s OR p.post_password LIKE %s)';
			for ( $i = 0; $i < 3; $i++ ) {
				$sql_params[] = sprintf( '%%%s%%', $query['search'] );
			}
		}

		if ( 'select' === $select_or_count ) {
			switch ( $query['orderby'] ) {
				case 'hook':
					$orderby = 'p.post_title';
					break;
				case 'group':
					$orderby = 't.name';
					break;
				case 'status':
					$orderby = 'p.post_status';
					break;
				case 'modified':
					$orderby = 'p.post_modified';
					break;
				case 'claim_id':
					$orderby = 'p.post_password';
					break;
				case 'schedule':
				case 'date':
				default:
					$orderby = 'p.post_date_gmt';
					break;
			}
			if ( 'ASC' === strtoupper( $query['order'] ) ) {
				$order = 'ASC';
			} else {
				$order = 'DESC';
			}
			$sql .= " ORDER BY $orderby $order";
			if ( $query['per_page'] > 0 ) {
				$sql         .= ' LIMIT %d, %d';
				$sql_params[] = $query['offset'];
				$sql_params[] = $query['per_page'];
			}
		}

		return $wpdb->prepare( $sql, $sql_params ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}

	/**
	 * Query for action count or list of action IDs.
	 *
	 * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status.
	 *
	 * @see ActionScheduler_Store::query_actions for $query arg usage.
	 *
	 * @param array  $query      Query filtering options.
	 * @param string $query_type Whether to select or count the results. Defaults to select.
	 *
	 * @return string|array|null The IDs of actions matching the query. Null on failure.
	 */
	public function query_actions( $query = array(), $query_type = 'select' ) {
		/**
		 * Global $wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		$sql = $this->get_query_actions_sql( $query, $query_type );

		return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared
	}

	/**
	 * Get a count of all actions in the store, grouped by status
	 *
	 * @return array
	 */
	public function action_counts() {

		$action_counts_by_status = array();
		$action_stati_and_labels = $this->get_status_labels();
		$posts_count_by_status   = (array) wp_count_posts( self::POST_TYPE, 'readable' );

		foreach ( $posts_count_by_status as $post_status_name => $count ) {

			try {
				$action_status_name = $this->get_action_status_by_post_status( $post_status_name );
			} catch ( Exception $e ) {
				// Ignore any post statuses that aren't for actions.
				continue;
			}
			if ( array_key_exists( $action_status_name, $action_stati_and_labels ) ) {
				$action_counts_by_status[ $action_status_name ] = $count;
			}
		}

		return $action_counts_by_status;
	}

	/**
	 * Cancel action.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @throws InvalidArgumentException If $action_id is not identified.
	 */
	public function cancel_action( $action_id ) {
		$post = get_post( $action_id );
		if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) {
			/* translators: %s is the action ID */
			throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to cancel this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		do_action( 'action_scheduler_canceled_action', $action_id );
		add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
		wp_trash_post( $action_id );
		remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
	}

	/**
	 * Delete action.
	 *
	 * @param int $action_id Action ID.
	 * @return void
	 * @throws InvalidArgumentException If action is not identified.
	 */
	public function delete_action( $action_id ) {
		$post = get_post( $action_id );
		if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) {
			/* translators: %s is the action ID */
			throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to delete this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		do_action( 'action_scheduler_deleted_action', $action_id );

		wp_delete_post( $action_id, true );
	}

	/**
	 * Get date for claim id.
	 *
	 * @param int $action_id Action ID.
	 * @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran.
	 */
	public function get_date( $action_id ) {
		$next = $this->get_date_gmt( $action_id );
		return ActionScheduler_TimezoneHelper::set_local_timezone( $next );
	}

	/**
	 * Get Date GMT.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @throws InvalidArgumentException If $action_id is not identified.
	 * @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran.
	 */
	public function get_date_gmt( $action_id ) {
		$post = get_post( $action_id );
		if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) {
			/* translators: %s is the action ID */
			throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to determine the date of this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		if ( 'publish' === $post->post_status ) {
			return as_get_datetime_object( $post->post_modified_gmt );
		} else {
			return as_get_datetime_object( $post->post_date_gmt );
		}
	}

	/**
	 * Stake claim.
	 *
	 * @param int           $max_actions Maximum number of actions.
	 * @param DateTime|null $before_date Jobs must be schedule before this date. Defaults to now.
	 * @param array         $hooks       Claim only actions with a hook or hooks.
	 * @param string        $group       Claim only actions in the given group.
	 *
	 * @return ActionScheduler_ActionClaim
	 * @throws RuntimeException When there is an error staking a claim.
	 * @throws InvalidArgumentException When the given group is not valid.
	 */
	public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ) {
		$this->claim_before_date = $before_date;
		$claim_id                = $this->generate_claim_id();
		$this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
		$action_ids              = $this->find_actions_by_claim_id( $claim_id );
		$this->claim_before_date = null;

		return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
	}

	/**
	 * Get claim count.
	 *
	 * @return int
	 */
	public function get_claim_count() {
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(DISTINCT post_password) FROM {$wpdb->posts} WHERE post_password != '' AND post_type = %s AND post_status IN ('in-progress','pending')",
				array( self::POST_TYPE )
			)
		);
	}

	/**
	 * Generate claim id.
	 *
	 * @return string
	 */
	protected function generate_claim_id() {
		$claim_id = md5( microtime( true ) . wp_rand( 0, 1000 ) );
		return substr( $claim_id, 0, 20 ); // to fit in db field with 20 char limit.
	}

	/**
	 * Claim actions.
	 *
	 * @param string        $claim_id    Claim ID.
	 * @param int           $limit       Limit.
	 * @param DateTime|null $before_date Should use UTC timezone.
	 * @param array         $hooks       Claim only actions with a hook or hooks.
	 * @param string        $group       Claim only actions in the given group.
	 *
	 * @return int The number of actions that were claimed.
	 * @throws RuntimeException  When there is a database error.
	 */
	protected function claim_actions( $claim_id, $limit, ?DateTime $before_date = null, $hooks = array(), $group = '' ) {
		// Set up initial variables.
		$date      = null === $before_date ? as_get_datetime_object() : clone $before_date;
		$limit_ids = ! empty( $group );
		$ids       = $limit_ids ? $this->get_actions_by_group( $group, $limit, $date ) : array();

		// If limiting by IDs and no posts found, then return early since we have nothing to update.
		if ( $limit_ids && 0 === count( $ids ) ) {
			return 0;
		}

		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		/*
		 * Build up custom query to update the affected posts. Parameters are built as a separate array
		 * to make it easier to identify where they are in the query.
		 *
		 * We can't use $wpdb->update() here because of the "ID IN ..." clause.
		 */
		$update = "UPDATE {$wpdb->posts} SET post_password = %s, post_modified_gmt = %s, post_modified = %s";
		$params = array(
			$claim_id,
			current_time( 'mysql', true ),
			current_time( 'mysql' ),
		);

		// Build initial WHERE clause.
		$where    = "WHERE post_type = %s AND post_status = %s AND post_password = ''";
		$params[] = self::POST_TYPE;
		$params[] = ActionScheduler_Store::STATUS_PENDING;

		if ( ! empty( $hooks ) ) {
			$placeholders = array_fill( 0, count( $hooks ), '%s' );
			$where       .= ' AND post_title IN (' . join( ', ', $placeholders ) . ')';
			$params       = array_merge( $params, array_values( $hooks ) );
		}

		/*
		 * Add the IDs to the WHERE clause. IDs not escaped because they came directly from a prior DB query.
		 *
		 * If we're not limiting by IDs, then include the post_date_gmt clause.
		 */
		if ( $limit_ids ) {
			$where .= ' AND ID IN (' . join( ',', $ids ) . ')';
		} else {
			$where   .= ' AND post_date_gmt <= %s';
			$params[] = $date->format( 'Y-m-d H:i:s' );
		}

		// Add the ORDER BY clause and,ms limit.
		$order    = 'ORDER BY menu_order ASC, post_date_gmt ASC, ID ASC LIMIT %d';
		$params[] = $limit;

		// Run the query and gather results.
		$rows_affected = $wpdb->query( $wpdb->prepare( "{$update} {$where} {$order}", $params ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare

		if ( false === $rows_affected ) {
			throw new RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) );
		}

		return (int) $rows_affected;
	}

	/**
	 * Get IDs of actions within a certain group and up to a certain date/time.
	 *
	 * @param string   $group The group to use in finding actions.
	 * @param int      $limit The number of actions to retrieve.
	 * @param DateTime $date  DateTime object representing cutoff time for actions. Actions retrieved will be
	 *                        up to and including this DateTime.
	 *
	 * @return array IDs of actions in the appropriate group and before the appropriate time.
	 * @throws InvalidArgumentException When the group does not exist.
	 */
	protected function get_actions_by_group( $group, $limit, DateTime $date ) {
		// Ensure the group exists before continuing.
		if ( ! term_exists( $group, self::GROUP_TAXONOMY ) ) {
			/* translators: %s is the group name */
			throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) );
		}

		// Set up a query for post IDs to use later.
		$query      = new WP_Query();
		$query_args = array(
			'fields'           => 'ids',
			'post_type'        => self::POST_TYPE,
			'post_status'      => ActionScheduler_Store::STATUS_PENDING,
			'has_password'     => false,
			'posts_per_page'   => $limit * 3,
			'suppress_filters' => true, // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters
			'no_found_rows'    => true,
			'orderby'          => array(
				'menu_order' => 'ASC',
				'date'       => 'ASC',
				'ID'         => 'ASC',
			),
			'date_query'       => array(
				'column'    => 'post_date_gmt',
				'before'    => $date->format( 'Y-m-d H:i' ),
				'inclusive' => true,
			),
			'tax_query'        => array( // phpcs:ignore WordPress.DB.SlowDBQuery
				array(
					'taxonomy'         => self::GROUP_TAXONOMY,
					'field'            => 'slug',
					'terms'            => $group,
					'include_children' => false,
				),
			),
		);

		return $query->query( $query_args );
	}

	/**
	 * Find actions by claim ID.
	 *
	 * @param string $claim_id Claim ID.
	 * @return array
	 */
	public function find_actions_by_claim_id( $claim_id ) {
		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		$action_ids  = array();
		$before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object();
		$cut_off     = $before_date->format( 'Y-m-d H:i:s' );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$results = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT ID, post_date_gmt FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s",
				array(
					self::POST_TYPE,
					$claim_id,
				)
			)
		);

		// Verify that the scheduled date for each action is within the expected bounds (in some unusual
		// cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify).
		foreach ( $results as $claimed_action ) {
			if ( $claimed_action->post_date_gmt <= $cut_off ) {
				$action_ids[] = absint( $claimed_action->ID );
			}
		}

		return $action_ids;
	}

	/**
	 * Release claim.
	 *
	 * @param ActionScheduler_ActionClaim $claim Claim object to release.
	 * @return void
	 * @throws RuntimeException When the claim is not unlocked.
	 */
	public function release_claim( ActionScheduler_ActionClaim $claim ) {
		$action_ids = $this->find_actions_by_claim_id( $claim->get_id() );
		if ( empty( $action_ids ) ) {
			return; // nothing to do.
		}
		$action_id_string = implode( ',', array_map( 'intval', $action_ids ) );
		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$result = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->posts} SET post_password = '' WHERE ID IN ($action_id_string) AND post_password = %s", //phpcs:ignore
				array(
					$claim->get_id(),
				)
			)
		);
		if ( false === $result ) {
			/* translators: %s: claim ID */
			throw new RuntimeException( sprintf( __( 'Unable to unlock claim %s. Database error.', 'action-scheduler' ), $claim->get_id() ) );
		}
	}

	/**
	 * Unclaim action.
	 *
	 * @param string $action_id Action ID.
	 * @throws RuntimeException When unable to unlock claim on action ID.
	 */
	public function unclaim_action( $action_id ) {
		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		//phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$result = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->posts} SET post_password = '' WHERE ID = %d AND post_type = %s",
				$action_id,
				self::POST_TYPE
			)
		);
		if ( false === $result ) {
			/* translators: %s: action ID */
			throw new RuntimeException( sprintf( __( 'Unable to unlock claim on action %s. Database error.', 'action-scheduler' ), $action_id ) );
		}
	}

	/**
	 * Mark failure on action.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return void
	 * @throws RuntimeException When unable to mark failure on action ID.
	 */
	public function mark_failure( $action_id ) {
		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$result = $wpdb->query(
			$wpdb->prepare( "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type = %s", self::STATUS_FAILED, $action_id, self::POST_TYPE )
		);
		if ( false === $result ) {
			/* translators: %s: action ID */
			throw new RuntimeException( sprintf( __( 'Unable to mark failure on action %s. Database error.', 'action-scheduler' ), $action_id ) );
		}
	}

	/**
	 * Return an action's claim ID, as stored in the post password column
	 *
	 * @param int $action_id Action ID.
	 * @return mixed
	 */
	public function get_claim_id( $action_id ) {
		return $this->get_post_column( $action_id, 'post_password' );
	}

	/**
	 * Return an action's status, as stored in the post status column
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return mixed
	 * @throws InvalidArgumentException When the action ID is invalid.
	 */
	public function get_status( $action_id ) {
		$status = $this->get_post_column( $action_id, 'post_status' );

		if ( null === $status ) {
			throw new InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) );
		}

		return $this->get_action_status_by_post_status( $status );
	}

	/**
	 * Get post column
	 *
	 * @param string $action_id Action ID.
	 * @param string $column_name Column Name.
	 *
	 * @return string|null
	 */
	private function get_post_column( $action_id, $column_name ) {
		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->get_var(
			$wpdb->prepare(
				"SELECT {$column_name} FROM {$wpdb->posts} WHERE ID=%d AND post_type=%s", // phpcs:ignore
				$action_id,
				self::POST_TYPE
			)
		);
	}

	/**
	 * Log Execution.
	 *
	 * @throws Exception If the action status cannot be updated to self::STATUS_RUNNING ('in-progress').
	 *
	 * @param string $action_id Action ID.
	 */
	public function log_execution( $action_id ) {
		/**
		 * Global wpdb object.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$status_updated = $wpdb->query(
			$wpdb->prepare(
				"UPDATE {$wpdb->posts} SET menu_order = menu_order+1, post_status=%s, post_modified_gmt = %s, post_modified = %s WHERE ID = %d AND post_type = %s",
				self::STATUS_RUNNING,
				current_time( 'mysql', true ),
				current_time( 'mysql' ),
				$action_id,
				self::POST_TYPE
			)
		);

		if ( ! $status_updated ) {
			throw new Exception(
				sprintf(
					/* translators: 1: action ID. 2: status slug. */
					__( 'Unable to update the status of action %1$d to %2$s.', 'action-scheduler' ),
					$action_id,
					self::STATUS_RUNNING
				)
			);
		}
	}

	/**
	 * Record that an action was completed.
	 *
	 * @param string $action_id ID of the completed action.
	 *
	 * @throws InvalidArgumentException When the action ID is invalid.
	 * @throws RuntimeException         When there was an error executing the action.
	 */
	public function mark_complete( $action_id ) {
		$post = get_post( $action_id );
		if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) {
			/* translators: %s is the action ID */
			throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having completed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
		add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
		$result = wp_update_post(
			array(
				'ID'          => $action_id,
				'post_status' => 'publish',
			),
			true
		);
		remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
		remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
		if ( is_wp_error( $result ) ) {
			throw new RuntimeException( $result->get_error_message() );
		}

		/**
		 * Fires after a scheduled action has been completed.
		 *
		 * @since 3.4.2
		 *
		 * @param int $action_id Action ID.
		 */
		do_action( 'action_scheduler_completed_action', $action_id );
	}

	/**
	 * Mark action as migrated when there is an error deleting the action.
	 *
	 * @param int $action_id Action ID.
	 */
	public function mark_migrated( $action_id ) {
		wp_update_post(
			array(
				'ID'          => $action_id,
				'post_status' => 'migrated',
			)
		);
	}

	/**
	 * Determine whether the post store can be migrated.
	 *
	 * @param [type] $setting - Setting value.
	 * @return bool
	 */
	public function migration_dependencies_met( $setting ) {
		global $wpdb;

		$dependencies_met = get_transient( self::DEPENDENCIES_MET );
		if ( empty( $dependencies_met ) ) {
			$maximum_args_length = apply_filters( 'action_scheduler_maximum_args_length', 191 );
			$found_action        = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$wpdb->prepare(
					"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND CHAR_LENGTH(post_content) > %d LIMIT 1",
					$maximum_args_length,
					self::POST_TYPE
				)
			);
			$dependencies_met    = $found_action ? 'no' : 'yes';
			set_transient( self::DEPENDENCIES_MET, $dependencies_met, DAY_IN_SECONDS );
		}

		return 'yes' === $dependencies_met ? $setting : false;
	}

	/**
	 * InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4.
	 *
	 * Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However,
	 * as we prepare to move to custom tables, and can use an indexed VARCHAR column instead, we want to warn
	 * developers of this impending requirement.
	 *
	 * @param ActionScheduler_Action $action Action object.
	 */
	protected function validate_action( ActionScheduler_Action $action ) {
		try {
			parent::validate_action( $action );
		} catch ( Exception $e ) {
			/* translators: %s is the error message */
			$message = sprintf( __( '%s Support for strings longer than this will be removed in a future version.', 'action-scheduler' ), $e->getMessage() );
			_doing_it_wrong( 'ActionScheduler_Action::$args', esc_html( $message ), '2.1.0' );
		}
	}

	/**
	 * (@codeCoverageIgnore)
	 */
	public function init() {
		add_filter( 'action_scheduler_migration_dependencies_met', array( $this, 'migration_dependencies_met' ) );

		$post_type_registrar = new ActionScheduler_wpPostStore_PostTypeRegistrar();
		$post_type_registrar->register();

		$post_status_registrar = new ActionScheduler_wpPostStore_PostStatusRegistrar();
		$post_status_registrar->register();

		$taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar();
		$taxonomy_registrar->register();
	}
}
data-stores/ActionScheduler_DBLogger.php000066600000010620151137657230014301 0ustar00<?php

/**
 * Class ActionScheduler_DBLogger
 *
 * Action logs data table data store.
 *
 * @since 3.0.0
 */
class ActionScheduler_DBLogger extends ActionScheduler_Logger {

	/**
	 * Add a record to an action log.
	 *
	 * @param int           $action_id Action ID.
	 * @param string        $message Message to be saved in the log entry.
	 * @param DateTime|null $date Timestamp of the log entry.
	 *
	 * @return int     The log entry ID.
	 */
	public function log( $action_id, $message, ?DateTime $date = null ) {
		if ( empty( $date ) ) {
			$date = as_get_datetime_object();
		} else {
			$date = clone $date;
		}

		$date_gmt = $date->format( 'Y-m-d H:i:s' );
		ActionScheduler_TimezoneHelper::set_local_timezone( $date );
		$date_local = $date->format( 'Y-m-d H:i:s' );

		/** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort
		global $wpdb;
		$wpdb->insert(
			$wpdb->actionscheduler_logs,
			array(
				'action_id'      => $action_id,
				'message'        => $message,
				'log_date_gmt'   => $date_gmt,
				'log_date_local' => $date_local,
			),
			array( '%d', '%s', '%s', '%s' )
		);

		return $wpdb->insert_id;
	}

	/**
	 * Retrieve an action log entry.
	 *
	 * @param int $entry_id Log entry ID.
	 *
	 * @return ActionScheduler_LogEntry
	 */
	public function get_entry( $entry_id ) {
		/** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort
		global $wpdb;
		$entry = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE log_id=%d", $entry_id ) );

		return $this->create_entry_from_db_record( $entry );
	}

	/**
	 * Create an action log entry from a database record.
	 *
	 * @param object $record Log entry database record object.
	 *
	 * @return ActionScheduler_LogEntry
	 */
	private function create_entry_from_db_record( $record ) {
		if ( empty( $record ) ) {
			return new ActionScheduler_NullLogEntry();
		}

		if ( is_null( $record->log_date_gmt ) ) {
			$date = as_get_datetime_object( ActionScheduler_StoreSchema::DEFAULT_DATE );
		} else {
			$date = as_get_datetime_object( $record->log_date_gmt );
		}

		return new ActionScheduler_LogEntry( $record->action_id, $record->message, $date );
	}

	/**
	 * Retrieve an action's log entries from the database.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return ActionScheduler_LogEntry[]
	 */
	public function get_logs( $action_id ) {
		/** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort
		global $wpdb;

		$records = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE action_id=%d", $action_id ) );

		return array_map( array( $this, 'create_entry_from_db_record' ), $records );
	}

	/**
	 * Initialize the data store.
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {
		$table_maker = new ActionScheduler_LoggerSchema();
		$table_maker->init();
		$table_maker->register_tables();

		parent::init();

		add_action( 'action_scheduler_deleted_action', array( $this, 'clear_deleted_action_logs' ), 10, 1 );
	}

	/**
	 * Delete the action logs for an action.
	 *
	 * @param int $action_id Action ID.
	 */
	public function clear_deleted_action_logs( $action_id ) {
		/** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort
		global $wpdb;
		$wpdb->delete( $wpdb->actionscheduler_logs, array( 'action_id' => $action_id ), array( '%d' ) );
	}

	/**
	 * Bulk add cancel action log entries.
	 *
	 * @param array $action_ids List of action ID.
	 */
	public function bulk_log_cancel_actions( $action_ids ) {
		if ( empty( $action_ids ) ) {
			return;
		}

		/** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort
		global $wpdb;
		$date     = as_get_datetime_object();
		$date_gmt = $date->format( 'Y-m-d H:i:s' );
		ActionScheduler_TimezoneHelper::set_local_timezone( $date );
		$date_local = $date->format( 'Y-m-d H:i:s' );
		$message    = __( 'action canceled', 'action-scheduler' );
		$format     = '(%d, ' . $wpdb->prepare( '%s, %s, %s', $message, $date_gmt, $date_local ) . ')';
		$sql_query  = "INSERT {$wpdb->actionscheduler_logs} (action_id, message, log_date_gmt, log_date_local) VALUES ";
		$value_rows = array();

		foreach ( $action_ids as $action_id ) {
			$value_rows[] = $wpdb->prepare( $format, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		}
		$sql_query .= implode( ',', $value_rows );

		$wpdb->query( $sql_query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}
}
data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php000066600000003502151137657230021262 0ustar00<?php

/**
 * Class ActionScheduler_wpPostStore_PostStatusRegistrar
 *
 * @codeCoverageIgnore
 */
class ActionScheduler_wpPostStore_PostStatusRegistrar {

	/**
	 * Registrar.
	 */
	public function register() {
		register_post_status( ActionScheduler_Store::STATUS_RUNNING, array_merge( $this->post_status_args(), $this->post_status_running_labels() ) );
		register_post_status( ActionScheduler_Store::STATUS_FAILED, array_merge( $this->post_status_args(), $this->post_status_failed_labels() ) );
	}

	/**
	 * Build the args array for the post type definition
	 *
	 * @return array
	 */
	protected function post_status_args() {
		$args = array(
			'public'                    => false,
			'exclude_from_search'       => false,
			'show_in_admin_all_list'    => true,
			'show_in_admin_status_list' => true,
		);

		return apply_filters( 'action_scheduler_post_status_args', $args );
	}

	/**
	 * Build the args array for the post type definition
	 *
	 * @return array
	 */
	protected function post_status_failed_labels() {
		$labels = array(
			'label'       => _x( 'Failed', 'post', 'action-scheduler' ),
			/* translators: %s: count */
			'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>', 'action-scheduler' ),
		);

		return apply_filters( 'action_scheduler_post_status_failed_labels', $labels );
	}

	/**
	 * Build the args array for the post type definition
	 *
	 * @return array
	 */
	protected function post_status_running_labels() {
		$labels = array(
			'label'       => _x( 'In-Progress', 'post', 'action-scheduler' ),
			/* translators: %s: count */
			'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>', 'action-scheduler' ),
		);

		return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
	}
}
data-stores/ActionScheduler_wpCommentLogger.php000066600000017033151137657230015772 0ustar00<?php

/**
 * Class ActionScheduler_wpCommentLogger
 */
class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger {
	const AGENT = 'ActionScheduler';
	const TYPE  = 'action_log';

	/**
	 * Create log entry.
	 *
	 * @param string        $action_id Action ID.
	 * @param string        $message   Action log's message.
	 * @param DateTime|null $date      Action log's timestamp.
	 *
	 * @return string The log entry ID
	 */
	public function log( $action_id, $message, ?DateTime $date = null ) {
		if ( empty( $date ) ) {
			$date = as_get_datetime_object();
		} else {
			$date = as_get_datetime_object( clone $date );
		}
		$comment_id = $this->create_wp_comment( $action_id, $message, $date );
		return $comment_id;
	}

	/**
	 * Create comment.
	 *
	 * @param int      $action_id Action ID.
	 * @param string   $message Action log's message.
	 * @param DateTime $date Action log entry's timestamp.
	 */
	protected function create_wp_comment( $action_id, $message, DateTime $date ) {

		$comment_date_gmt = $date->format( 'Y-m-d H:i:s' );
		ActionScheduler_TimezoneHelper::set_local_timezone( $date );
		$comment_data = array(
			'comment_post_ID'  => $action_id,
			'comment_date'     => $date->format( 'Y-m-d H:i:s' ),
			'comment_date_gmt' => $comment_date_gmt,
			'comment_author'   => self::AGENT,
			'comment_content'  => $message,
			'comment_agent'    => self::AGENT,
			'comment_type'     => self::TYPE,
		);

		return wp_insert_comment( $comment_data );
	}

	/**
	 * Get single log entry for action.
	 *
	 * @param string $entry_id Entry ID.
	 *
	 * @return ActionScheduler_LogEntry
	 */
	public function get_entry( $entry_id ) {
		$comment = $this->get_comment( $entry_id );

		if ( empty( $comment ) || self::TYPE !== $comment->comment_type ) {
			return new ActionScheduler_NullLogEntry();
		}

		$date = as_get_datetime_object( $comment->comment_date_gmt );
		ActionScheduler_TimezoneHelper::set_local_timezone( $date );
		return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $date );
	}

	/**
	 * Get action's logs.
	 *
	 * @param string $action_id Action ID.
	 *
	 * @return ActionScheduler_LogEntry[]
	 */
	public function get_logs( $action_id ) {
		$status = 'all';
		$logs   = array();

		if ( get_post_status( $action_id ) === 'trash' ) {
			$status = 'post-trashed';
		}

		$comments = get_comments(
			array(
				'post_id' => $action_id,
				'orderby' => 'comment_date_gmt',
				'order'   => 'ASC',
				'type'    => self::TYPE,
				'status'  => $status,
			)
		);

		foreach ( $comments as $c ) {
			$entry = $this->get_entry( $c );

			if ( ! empty( $entry ) ) {
				$logs[] = $entry;
			}
		}

		return $logs;
	}

	/**
	 * Get comment.
	 *
	 * @param int $comment_id Comment ID.
	 */
	protected function get_comment( $comment_id ) {
		return get_comment( $comment_id );
	}

	/**
	 * Filter comment queries.
	 *
	 * @param WP_Comment_Query $query Comment query object.
	 */
	public function filter_comment_queries( $query ) {
		foreach ( array( 'ID', 'parent', 'post_author', 'post_name', 'post_parent', 'type', 'post_type', 'post_id', 'post_ID' ) as $key ) {
			if ( ! empty( $query->query_vars[ $key ] ) ) {
				return; // don't slow down queries that wouldn't include action_log comments anyway.
			}
		}
		$query->query_vars['action_log_filter'] = true;
		add_filter( 'comments_clauses', array( $this, 'filter_comment_query_clauses' ), 10, 2 );
	}

	/**
	 * Filter comment queries.
	 *
	 * @param array            $clauses Query's clauses.
	 * @param WP_Comment_Query $query Query object.
	 *
	 * @return array
	 */
	public function filter_comment_query_clauses( $clauses, $query ) {
		if ( ! empty( $query->query_vars['action_log_filter'] ) ) {
			$clauses['where'] .= $this->get_where_clause();
		}
		return $clauses;
	}

	/**
	 * Make sure Action Scheduler logs are excluded from comment feeds, which use WP_Query, not
	 * the WP_Comment_Query class handled by @see self::filter_comment_queries().
	 *
	 * @param string   $where Query's `where` clause.
	 * @param WP_Query $query Query object.
	 *
	 * @return string
	 */
	public function filter_comment_feed( $where, $query ) {
		if ( is_comment_feed() ) {
			$where .= $this->get_where_clause();
		}
		return $where;
	}

	/**
	 * Return a SQL clause to exclude Action Scheduler comments.
	 *
	 * @return string
	 */
	protected function get_where_clause() {
		global $wpdb;
		return sprintf( " AND {$wpdb->comments}.comment_type != '%s'", self::TYPE );
	}

	/**
	 * Remove action log entries from wp_count_comments()
	 *
	 * @param array $stats   Comment count.
	 * @param int   $post_id Post ID.
	 *
	 * @return object
	 */
	public function filter_comment_count( $stats, $post_id ) {
		global $wpdb;

		if ( 0 === $post_id ) {
			$stats = $this->get_comment_count();
		}

		return $stats;
	}

	/**
	 * Retrieve the comment counts from our cache, or the database if the cached version isn't set.
	 *
	 * @return object
	 */
	protected function get_comment_count() {
		global $wpdb;

		$stats = get_transient( 'as_comment_count' );

		if ( ! $stats ) {
			$stats    = array();
			$count    = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} WHERE comment_type NOT IN('order_note','action_log') GROUP BY comment_approved", ARRAY_A );
			$total    = 0;
			$stats    = array();
			$approved = array(
				'0'            => 'moderated',
				'1'            => 'approved',
				'spam'         => 'spam',
				'trash'        => 'trash',
				'post-trashed' => 'post-trashed',
			);

			foreach ( (array) $count as $row ) {
				// Don't count post-trashed toward totals.
				if ( 'post-trashed' !== $row['comment_approved'] && 'trash' !== $row['comment_approved'] ) {
					$total += $row['num_comments'];
				}
				if ( isset( $approved[ $row['comment_approved'] ] ) ) {
					$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
				}
			}

			$stats['total_comments'] = $total;
			$stats['all']            = $total;

			foreach ( $approved as $key ) {
				if ( empty( $stats[ $key ] ) ) {
					$stats[ $key ] = 0;
				}
			}

			$stats = (object) $stats;
			set_transient( 'as_comment_count', $stats );
		}

		return $stats;
	}

	/**
	 * Delete comment count cache whenever there is new comment or the status of a comment changes. Cache
	 * will be regenerated next time ActionScheduler_wpCommentLogger::filter_comment_count() is called.
	 */
	public function delete_comment_count_cache() {
		delete_transient( 'as_comment_count' );
	}

	/**
	 * Initialize.
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {
		add_action( 'action_scheduler_before_process_queue', array( $this, 'disable_comment_counting' ), 10, 0 );
		add_action( 'action_scheduler_after_process_queue', array( $this, 'enable_comment_counting' ), 10, 0 );

		parent::init();

		add_action( 'pre_get_comments', array( $this, 'filter_comment_queries' ), 10, 1 );
		add_action( 'wp_count_comments', array( $this, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs.
		add_action( 'comment_feed_where', array( $this, 'filter_comment_feed' ), 10, 2 );

		// Delete comments count cache whenever there is a new comment or a comment status changes.
		add_action( 'wp_insert_comment', array( $this, 'delete_comment_count_cache' ) );
		add_action( 'wp_set_comment_status', array( $this, 'delete_comment_count_cache' ) );
	}

	/**
	 * Defer comment counting.
	 */
	public function disable_comment_counting() {
		wp_defer_comment_counting( true );
	}

	/**
	 * Enable comment counting.
	 */
	public function enable_comment_counting() {
		wp_defer_comment_counting( false );
	}

}
data-stores/ActionScheduler_DBStore.php000066600000114765151137657230014175 0ustar00<?php

/**
 * Class ActionScheduler_DBStore
 *
 * Action data table data store.
 *
 * @since 3.0.0
 */
class ActionScheduler_DBStore extends ActionScheduler_Store {

	/**
	 * Used to share information about the before_date property of claims internally.
	 *
	 * This is used in preference to passing the same information as a method param
	 * for backwards-compatibility reasons.
	 *
	 * @var DateTime|null
	 */
	private $claim_before_date = null;

	/**
	 * Maximum length of args.
	 *
	 * @var int
	 */
	protected static $max_args_length = 8000;

	/**
	 * Maximum length of index.
	 *
	 * @var int
	 */
	protected static $max_index_length = 191;

	/**
	 * List of claim filters.
	 *
	 * @var array
	 */
	protected $claim_filters = array(
		'group'          => '',
		'hooks'          => '',
		'exclude-groups' => '',
	);

	/**
	 * Initialize the data store
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {
		$table_maker = new ActionScheduler_StoreSchema();
		$table_maker->init();
		$table_maker->register_tables();
	}

	/**
	 * Save an action, checks if this is a unique action before actually saving.
	 *
	 * @param ActionScheduler_Action $action         Action object.
	 * @param DateTime|null          $scheduled_date Optional schedule date. Default null.
	 *
	 * @return int                  Action ID.
	 * @throws RuntimeException     Throws exception when saving the action fails.
	 */
	public function save_unique_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) {
		return $this->save_action_to_db( $action, $scheduled_date, true );
	}

	/**
	 * Save an action. Can save duplicate action as well, prefer using `save_unique_action` instead.
	 *
	 * @param ActionScheduler_Action $action Action object.
	 * @param DateTime|null          $scheduled_date Optional schedule date. Default null.
	 *
	 * @return int Action ID.
	 * @throws RuntimeException     Throws exception when saving the action fails.
	 */
	public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) {
		return $this->save_action_to_db( $action, $scheduled_date, false );
	}

	/**
	 * Save an action.
	 *
	 * @param ActionScheduler_Action $action Action object.
	 * @param ?DateTime              $date Optional schedule date. Default null.
	 * @param bool                   $unique Whether the action should be unique.
	 *
	 * @return int Action ID.
	 * @throws \RuntimeException     Throws exception when saving the action fails.
	 */
	private function save_action_to_db( ActionScheduler_Action $action, ?DateTime $date = null, $unique = false ) {
		global $wpdb;

		try {
			$this->validate_action( $action );

			$data = array(
				'hook'                 => $action->get_hook(),
				'status'               => ( $action->is_finished() ? self::STATUS_COMPLETE : self::STATUS_PENDING ),
				'scheduled_date_gmt'   => $this->get_scheduled_date_string( $action, $date ),
				'scheduled_date_local' => $this->get_scheduled_date_string_local( $action, $date ),
				'schedule'             => serialize( $action->get_schedule() ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
				'group_id'             => current( $this->get_group_ids( $action->get_group() ) ),
				'priority'             => $action->get_priority(),
			);

			$args = wp_json_encode( $action->get_args() );
			if ( strlen( $args ) <= static::$max_index_length ) {
				$data['args'] = $args;
			} else {
				$data['args']          = $this->hash_args( $args );
				$data['extended_args'] = $args;
			}

			$insert_sql = $this->build_insert_sql( $data, $unique );

			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $insert_sql should be already prepared.
			$wpdb->query( $insert_sql );
			$action_id = $wpdb->insert_id;

			if ( is_wp_error( $action_id ) ) {
				throw new \RuntimeException( $action_id->get_error_message() );
			} elseif ( empty( $action_id ) ) {
				if ( $unique ) {
					return 0;
				}
				throw new \RuntimeException( $wpdb->last_error ? $wpdb->last_error : __( 'Database error.', 'action-scheduler' ) );
			}

			do_action( 'action_scheduler_stored_action', $action_id );

			return $action_id;
		} catch ( \Exception $e ) {
			/* translators: %s: error message */
			throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
		}
	}

	/**
	 * Helper function to build insert query.
	 *
	 * @param array $data Row data for action.
	 * @param bool  $unique Whether the action should be unique.
	 *
	 * @return string Insert query.
	 */
	private function build_insert_sql( array $data, $unique ) {
		global $wpdb;

		$columns      = array_keys( $data );
		$values       = array_values( $data );
		$placeholders = array_map( array( $this, 'get_placeholder_for_column' ), $columns );

		$table_name = ! empty( $wpdb->actionscheduler_actions ) ? $wpdb->actionscheduler_actions : $wpdb->prefix . 'actionscheduler_actions';

		$column_sql      = '`' . implode( '`, `', $columns ) . '`';
		$placeholder_sql = implode( ', ', $placeholders );
		$where_clause    = $this->build_where_clause_for_insert( $data, $table_name, $unique );

		// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare	 -- $column_sql and $where_clause are already prepared. $placeholder_sql is hardcoded.
		$insert_query = $wpdb->prepare(
			"
INSERT INTO $table_name ( $column_sql )
SELECT $placeholder_sql FROM DUAL
WHERE ( $where_clause ) IS NULL",
			$values
		);
		// phpcs:enable

		return $insert_query;
	}

	/**
	 * Helper method to build where clause for action insert statement.
	 *
	 * @param array  $data Row data for action.
	 * @param string $table_name Action table name.
	 * @param bool   $unique Where action should be unique.
	 *
	 * @return string Where clause to be used with insert.
	 */
	private function build_where_clause_for_insert( $data, $table_name, $unique ) {
		global $wpdb;

		if ( ! $unique ) {
			return 'SELECT NULL FROM DUAL';
		}

		$pending_statuses            = array(
			ActionScheduler_Store::STATUS_PENDING,
			ActionScheduler_Store::STATUS_RUNNING,
		);
		$pending_status_placeholders = implode( ', ', array_fill( 0, count( $pending_statuses ), '%s' ) );

		// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $pending_status_placeholders is hardcoded.
		$where_clause = $wpdb->prepare(
			"
SELECT action_id FROM $table_name
WHERE status IN ( $pending_status_placeholders )
AND hook = %s
AND `group_id` = %d
",
			array_merge(
				$pending_statuses,
				array(
					$data['hook'],
					$data['group_id'],
				)
			)
		);
		// phpcs:enable

		return "$where_clause" . ' LIMIT 1';
	}

	/**
	 * Helper method to get $wpdb->prepare placeholder for a given column name.
	 *
	 * @param string $column_name Name of column in actions table.
	 *
	 * @return string Placeholder to use for given column.
	 */
	private function get_placeholder_for_column( $column_name ) {
		$string_columns = array(
			'hook',
			'status',
			'scheduled_date_gmt',
			'scheduled_date_local',
			'args',
			'schedule',
			'last_attempt_gmt',
			'last_attempt_local',
			'extended_args',
		);

		return in_array( $column_name, $string_columns, true ) ? '%s' : '%d';
	}

	/**
	 * Generate a hash from json_encoded $args using MD5 as this isn't for security.
	 *
	 * @param string $args JSON encoded action args.
	 * @return string
	 */
	protected function hash_args( $args ) {
		return md5( $args );
	}

	/**
	 * Get action args query param value from action args.
	 *
	 * @param array $args Action args.
	 * @return string
	 */
	protected function get_args_for_query( $args ) {
		$encoded = wp_json_encode( $args );
		if ( strlen( $encoded ) <= static::$max_index_length ) {
			return $encoded;
		}
		return $this->hash_args( $encoded );
	}
	/**
	 * Get a group's ID based on its name/slug.
	 *
	 * @param string|array $slugs                The string name of a group, or names for several groups.
	 * @param bool         $create_if_not_exists Whether to create the group if it does not already exist. Default, true - create the group.
	 *
	 * @return array The group IDs, if they exist or were successfully created. May be empty.
	 */
	protected function get_group_ids( $slugs, $create_if_not_exists = true ) {
		$slugs     = (array) $slugs;
		$group_ids = array();

		if ( empty( $slugs ) ) {
			return array();
		}

		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		foreach ( $slugs as $slug ) {
			$group_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT group_id FROM {$wpdb->actionscheduler_groups} WHERE slug=%s", $slug ) );

			if ( empty( $group_id ) && $create_if_not_exists ) {
				$group_id = $this->create_group( $slug );
			}

			if ( $group_id ) {
				$group_ids[] = $group_id;
			}
		}

		return $group_ids;
	}

	/**
	 * Create an action group.
	 *
	 * @param string $slug Group slug.
	 *
	 * @return int Group ID.
	 */
	protected function create_group( $slug ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$wpdb->insert( $wpdb->actionscheduler_groups, array( 'slug' => $slug ) );

		return (int) $wpdb->insert_id;
	}

	/**
	 * Retrieve an action.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return ActionScheduler_Action
	 */
	public function fetch_action( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$data = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT a.*, g.slug AS `group` FROM {$wpdb->actionscheduler_actions} a LEFT JOIN {$wpdb->actionscheduler_groups} g ON a.group_id=g.group_id WHERE a.action_id=%d",
				$action_id
			)
		);

		if ( empty( $data ) ) {
			return $this->get_null_action();
		}

		if ( ! empty( $data->extended_args ) ) {
			$data->args = $data->extended_args;
			unset( $data->extended_args );
		}

		// Convert NULL dates to zero dates.
		$date_fields = array(
			'scheduled_date_gmt',
			'scheduled_date_local',
			'last_attempt_gmt',
			'last_attempt_gmt',
		);
		foreach ( $date_fields as $date_field ) {
			if ( is_null( $data->$date_field ) ) {
				$data->$date_field = ActionScheduler_StoreSchema::DEFAULT_DATE;
			}
		}

		try {
			$action = $this->make_action_from_db_record( $data );
		} catch ( ActionScheduler_InvalidActionException $exception ) {
			do_action( 'action_scheduler_failed_fetch_action', $action_id, $exception );
			return $this->get_null_action();
		}

		return $action;
	}

	/**
	 * Create a null action.
	 *
	 * @return ActionScheduler_NullAction
	 */
	protected function get_null_action() {
		return new ActionScheduler_NullAction();
	}

	/**
	 * Create an action from a database record.
	 *
	 * @param object $data Action database record.
	 *
	 * @return ActionScheduler_Action|ActionScheduler_CanceledAction|ActionScheduler_FinishedAction
	 */
	protected function make_action_from_db_record( $data ) {

		$hook     = $data->hook;
		$args     = json_decode( $data->args, true );
		$schedule = unserialize( $data->schedule ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize

		$this->validate_args( $args, $data->action_id );
		$this->validate_schedule( $schedule, $data->action_id );

		if ( empty( $schedule ) ) {
			$schedule = new ActionScheduler_NullSchedule();
		}
		$group = $data->group ? $data->group : '';

		return ActionScheduler::factory()->get_stored_action( $data->status, $data->hook, $args, $schedule, $group, $data->priority );
	}

	/**
	 * Returns the SQL statement to query (or count) actions.
	 *
	 * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status.
	 *
	 * @param array  $query Filtering options.
	 * @param string $select_or_count  Whether the SQL should select and return the IDs or just the row count.
	 *
	 * @return string SQL statement already properly escaped.
	 * @throws \InvalidArgumentException If the query is invalid.
	 * @throws \RuntimeException When "unknown partial args matching value".
	 */
	protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) {

		if ( ! in_array( $select_or_count, array( 'select', 'count' ), true ) ) {
			throw new InvalidArgumentException( __( 'Invalid value for select or count parameter. Cannot query actions.', 'action-scheduler' ) );
		}

		$query = wp_parse_args(
			$query,
			array(
				'hook'                  => '',
				'args'                  => null,
				'partial_args_matching' => 'off', // can be 'like' or 'json'.
				'date'                  => null,
				'date_compare'          => '<=',
				'modified'              => null,
				'modified_compare'      => '<=',
				'group'                 => '',
				'status'                => '',
				'claimed'               => null,
				'per_page'              => 5,
				'offset'                => 0,
				'orderby'               => 'date',
				'order'                 => 'ASC',
			)
		);

		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$db_server_info = is_callable( array( $wpdb, 'db_server_info' ) ) ? $wpdb->db_server_info() : $wpdb->db_version();
		if ( false !== strpos( $db_server_info, 'MariaDB' ) ) {
			$supports_json = version_compare(
				PHP_VERSION_ID >= 80016 ? $wpdb->db_version() : preg_replace( '/[^0-9.].*/', '', str_replace( '5.5.5-', '', $db_server_info ) ),
				'10.2',
				'>='
			);
		} else {
			$supports_json = version_compare( $wpdb->db_version(), '5.7', '>=' );
		}

		$sql        = ( 'count' === $select_or_count ) ? 'SELECT count(a.action_id)' : 'SELECT a.action_id';
		$sql       .= " FROM {$wpdb->actionscheduler_actions} a";
		$sql_params = array();

		if ( ! empty( $query['group'] ) || 'group' === $query['orderby'] ) {
			$sql .= " LEFT JOIN {$wpdb->actionscheduler_groups} g ON g.group_id=a.group_id";
		}

		$sql .= ' WHERE 1=1';

		if ( ! empty( $query['group'] ) ) {
			$sql         .= ' AND g.slug=%s';
			$sql_params[] = $query['group'];
		}

		if ( ! empty( $query['hook'] ) ) {
			$sql         .= ' AND a.hook=%s';
			$sql_params[] = $query['hook'];
		}

		if ( ! is_null( $query['args'] ) ) {
			switch ( $query['partial_args_matching'] ) {
				case 'json':
					if ( ! $supports_json ) {
						throw new \RuntimeException( __( 'JSON partial matching not supported in your environment. Please check your MySQL/MariaDB version.', 'action-scheduler' ) );
					}
					$supported_types = array(
						'integer' => '%d',
						'boolean' => '%s',
						'double'  => '%f',
						'string'  => '%s',
					);
					foreach ( $query['args'] as $key => $value ) {
						$value_type = gettype( $value );
						if ( 'boolean' === $value_type ) {
							$value = $value ? 'true' : 'false';
						}
						$placeholder = isset( $supported_types[ $value_type ] ) ? $supported_types[ $value_type ] : false;
						if ( ! $placeholder ) {
							throw new \RuntimeException(
								sprintf(
									/* translators: %s: provided value type */
									__( 'The value type for the JSON partial matching is not supported. Must be either integer, boolean, double or string. %s type provided.', 'action-scheduler' ),
									$value_type
								)
							);
						}
						$sql         .= ' AND JSON_EXTRACT(a.args, %s)=' . $placeholder;
						$sql_params[] = '$.' . $key;
						$sql_params[] = $value;
					}
					break;
				case 'like':
					foreach ( $query['args'] as $key => $value ) {
						$sql         .= ' AND a.args LIKE %s';
						$json_partial = $wpdb->esc_like( trim( wp_json_encode( array( $key => $value ) ), '{}' ) );
						$sql_params[] = "%{$json_partial}%";
					}
					break;
				case 'off':
					$sql         .= ' AND a.args=%s';
					$sql_params[] = $this->get_args_for_query( $query['args'] );
					break;
				default:
					throw new \RuntimeException( __( 'Unknown partial args matching value.', 'action-scheduler' ) );
			}
		}

		if ( $query['status'] ) {
			$statuses     = (array) $query['status'];
			$placeholders = array_fill( 0, count( $statuses ), '%s' );
			$sql         .= ' AND a.status IN (' . join( ', ', $placeholders ) . ')';
			$sql_params   = array_merge( $sql_params, array_values( $statuses ) );
		}

		if ( $query['date'] instanceof \DateTime ) {
			$date = clone $query['date'];
			$date->setTimezone( new \DateTimeZone( 'UTC' ) );
			$date_string  = $date->format( 'Y-m-d H:i:s' );
			$comparator   = $this->validate_sql_comparator( $query['date_compare'] );
			$sql         .= " AND a.scheduled_date_gmt $comparator %s";
			$sql_params[] = $date_string;
		}

		if ( $query['modified'] instanceof \DateTime ) {
			$modified = clone $query['modified'];
			$modified->setTimezone( new \DateTimeZone( 'UTC' ) );
			$date_string  = $modified->format( 'Y-m-d H:i:s' );
			$comparator   = $this->validate_sql_comparator( $query['modified_compare'] );
			$sql         .= " AND a.last_attempt_gmt $comparator %s";
			$sql_params[] = $date_string;
		}

		if ( true === $query['claimed'] ) {
			$sql .= ' AND a.claim_id != 0';
		} elseif ( false === $query['claimed'] ) {
			$sql .= ' AND a.claim_id = 0';
		} elseif ( ! is_null( $query['claimed'] ) ) {
			$sql         .= ' AND a.claim_id = %d';
			$sql_params[] = $query['claimed'];
		}

		if ( ! empty( $query['search'] ) ) {
			$sql .= ' AND (a.hook LIKE %s OR (a.extended_args IS NULL AND a.args LIKE %s) OR a.extended_args LIKE %s';
			for ( $i = 0; $i < 3; $i++ ) {
				$sql_params[] = sprintf( '%%%s%%', $query['search'] );
			}

			$search_claim_id = (int) $query['search'];
			if ( $search_claim_id ) {
				$sql         .= ' OR a.claim_id = %d';
				$sql_params[] = $search_claim_id;
			}

			$sql .= ')';
		}

		if ( 'select' === $select_or_count ) {
			if ( 'ASC' === strtoupper( $query['order'] ) ) {
				$order = 'ASC';
			} else {
				$order = 'DESC';
			}
			switch ( $query['orderby'] ) {
				case 'hook':
					$sql .= " ORDER BY a.hook $order";
					break;
				case 'group':
					$sql .= " ORDER BY g.slug $order";
					break;
				case 'modified':
					$sql .= " ORDER BY a.last_attempt_gmt $order";
					break;
				case 'none':
					break;
				case 'action_id':
					$sql .= " ORDER BY a.action_id $order";
					break;
				case 'date':
				default:
					$sql .= " ORDER BY a.scheduled_date_gmt $order";
					break;
			}

			if ( $query['per_page'] > 0 ) {
				$sql         .= ' LIMIT %d, %d';
				$sql_params[] = $query['offset'];
				$sql_params[] = $query['per_page'];
			}
		}

		if ( ! empty( $sql_params ) ) {
			$sql = $wpdb->prepare( $sql, $sql_params ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		}

		return $sql;
	}

	/**
	 * Query for action count or list of action IDs.
	 *
	 * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status.
	 *
	 * @see ActionScheduler_Store::query_actions for $query arg usage.
	 *
	 * @param array  $query      Query filtering options.
	 * @param string $query_type Whether to select or count the results. Defaults to select.
	 *
	 * @return string|array|null The IDs of actions matching the query. Null on failure.
	 */
	public function query_actions( $query = array(), $query_type = 'select' ) {
		/**
		 * Global.
		 *
		 * @var wpdb $wpdb
		 */
		global $wpdb;

		$sql = $this->get_query_actions_sql( $query, $query_type );

		return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoSql, WordPress.DB.DirectDatabaseQuery.NoCaching
	}

	/**
	 * Get a count of all actions in the store, grouped by status.
	 *
	 * @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status.
	 */
	public function action_counts() {
		global $wpdb;

		$sql  = "SELECT a.status, count(a.status) as 'count'";
		$sql .= " FROM {$wpdb->actionscheduler_actions} a";
		$sql .= ' GROUP BY a.status';

		$actions_count_by_status = array();
		$action_stati_and_labels = $this->get_status_labels();

		foreach ( $wpdb->get_results( $sql ) as $action_data ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			// Ignore any actions with invalid status.
			if ( array_key_exists( $action_data->status, $action_stati_and_labels ) ) {
				$actions_count_by_status[ $action_data->status ] = $action_data->count;
			}
		}

		return $actions_count_by_status;
	}

	/**
	 * Cancel an action.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return void
	 * @throws \InvalidArgumentException If the action update failed.
	 */
	public function cancel_action( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$updated = $wpdb->update(
			$wpdb->actionscheduler_actions,
			array( 'status' => self::STATUS_CANCELED ),
			array( 'action_id' => $action_id ),
			array( '%s' ),
			array( '%d' )
		);
		if ( false === $updated ) {
			/* translators: %s: action ID */
			throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to cancel this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		do_action( 'action_scheduler_canceled_action', $action_id );
	}

	/**
	 * Cancel pending actions by hook.
	 *
	 * @since 3.0.0
	 *
	 * @param string $hook Hook name.
	 *
	 * @return void
	 */
	public function cancel_actions_by_hook( $hook ) {
		$this->bulk_cancel_actions( array( 'hook' => $hook ) );
	}

	/**
	 * Cancel pending actions by group.
	 *
	 * @param string $group Group slug.
	 *
	 * @return void
	 */
	public function cancel_actions_by_group( $group ) {
		$this->bulk_cancel_actions( array( 'group' => $group ) );
	}

	/**
	 * Bulk cancel actions.
	 *
	 * @since 3.0.0
	 *
	 * @param array $query_args Query parameters.
	 */
	protected function bulk_cancel_actions( $query_args ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		if ( ! is_array( $query_args ) ) {
			return;
		}

		// Don't cancel actions that are already canceled.
		if ( isset( $query_args['status'] ) && self::STATUS_CANCELED === $query_args['status'] ) {
			return;
		}

		$action_ids = true;
		$query_args = wp_parse_args(
			$query_args,
			array(
				'per_page' => 1000,
				'status'   => self::STATUS_PENDING,
				'orderby'  => 'none',
			)
		);

		while ( $action_ids ) {
			$action_ids = $this->query_actions( $query_args );
			if ( empty( $action_ids ) ) {
				break;
			}

			$format     = array_fill( 0, count( $action_ids ), '%d' );
			$query_in   = '(' . implode( ',', $format ) . ')';
			$parameters = $action_ids;
			array_unshift( $parameters, self::STATUS_CANCELED );

			$wpdb->query(
				$wpdb->prepare(
					"UPDATE {$wpdb->actionscheduler_actions} SET status = %s WHERE action_id IN {$query_in}", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
					$parameters
				)
			);

			do_action( 'action_scheduler_bulk_cancel_actions', $action_ids );
		}
	}

	/**
	 * Delete an action.
	 *
	 * @param int $action_id Action ID.
	 * @throws \InvalidArgumentException If the action deletion failed.
	 */
	public function delete_action( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$deleted = $wpdb->delete( $wpdb->actionscheduler_actions, array( 'action_id' => $action_id ), array( '%d' ) );
		if ( empty( $deleted ) ) {
			/* translators: %s is the action ID */
			throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to delete this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		do_action( 'action_scheduler_deleted_action', $action_id );
	}

	/**
	 * Get the schedule date for an action.
	 *
	 * @param string $action_id Action ID.
	 *
	 * @return \DateTime The local date the action is scheduled to run, or the date that it ran.
	 */
	public function get_date( $action_id ) {
		$date = $this->get_date_gmt( $action_id );
		ActionScheduler_TimezoneHelper::set_local_timezone( $date );
		return $date;
	}

	/**
	 * Get the GMT schedule date for an action.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @throws \InvalidArgumentException If action cannot be identified.
	 * @return \DateTime The GMT date the action is scheduled to run, or the date that it ran.
	 */
	protected function get_date_gmt( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$record = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d", $action_id ) );
		if ( empty( $record ) ) {
			/* translators: %s is the action ID */
			throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to determine the date of this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
		if ( self::STATUS_PENDING === $record->status ) {
			return as_get_datetime_object( $record->scheduled_date_gmt );
		} else {
			return as_get_datetime_object( $record->last_attempt_gmt );
		}
	}

	/**
	 * Stake a claim on actions.
	 *
	 * @param int           $max_actions Maximum number of action to include in claim.
	 * @param DateTime|null $before_date Jobs must be schedule before this date. Defaults to now.
	 * @param array         $hooks Hooks to filter for.
	 * @param string        $group Group to filter for.
	 *
	 * @return ActionScheduler_ActionClaim
	 */
	public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ) {
		$claim_id = $this->generate_claim_id();

		$this->claim_before_date = $before_date;
		$this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
		$action_ids              = $this->find_actions_by_claim_id( $claim_id );
		$this->claim_before_date = null;

		return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
	}

	/**
	 * Generate a new action claim.
	 *
	 * @return int Claim ID.
	 */
	protected function generate_claim_id() {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$now = as_get_datetime_object();
		$wpdb->insert( $wpdb->actionscheduler_claims, array( 'date_created_gmt' => $now->format( 'Y-m-d H:i:s' ) ) );

		return $wpdb->insert_id;
	}

	/**
	 * Set a claim filter.
	 *
	 * @param string $filter_name Claim filter name.
	 * @param mixed  $filter_values Values to filter.
	 * @return void
	 */
	public function set_claim_filter( $filter_name, $filter_values ) {
		if ( isset( $this->claim_filters[ $filter_name ] ) ) {
			$this->claim_filters[ $filter_name ] = $filter_values;
		}
	}

	/**
	 * Get the claim filter value.
	 *
	 * @param string $filter_name Claim filter name.
	 * @return mixed
	 */
	public function get_claim_filter( $filter_name ) {
		if ( isset( $this->claim_filters[ $filter_name ] ) ) {
			return $this->claim_filters[ $filter_name ];
		}

		return '';
	}

	/**
	 * Mark actions claimed.
	 *
	 * @param string        $claim_id Claim Id.
	 * @param int           $limit Number of action to include in claim.
	 * @param DateTime|null $before_date Should use UTC timezone.
	 * @param array         $hooks Hooks to filter for.
	 * @param string        $group Group to filter for.
	 *
	 * @return int The number of actions that were claimed.
	 * @throws \InvalidArgumentException Throws InvalidArgumentException if group doesn't exist.
	 * @throws \RuntimeException Throws RuntimeException if unable to claim action.
	 */
	protected function claim_actions( $claim_id, $limit, ?DateTime $before_date = null, $hooks = array(), $group = '' ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$now  = as_get_datetime_object();
		$date = is_null( $before_date ) ? $now : clone $before_date;
		// can't use $wpdb->update() because of the <= condition.
		$update = "UPDATE {$wpdb->actionscheduler_actions} SET claim_id=%d, last_attempt_gmt=%s, last_attempt_local=%s";
		$params = array(
			$claim_id,
			$now->format( 'Y-m-d H:i:s' ),
			current_time( 'mysql' ),
		);

		// Set claim filters.
		if ( ! empty( $hooks ) ) {
			$this->set_claim_filter( 'hooks', $hooks );
		} else {
			$hooks = $this->get_claim_filter( 'hooks' );
		}
		if ( ! empty( $group ) ) {
			$this->set_claim_filter( 'group', $group );
		} else {
			$group = $this->get_claim_filter( 'group' );
		}

		$where    = 'WHERE claim_id = 0 AND scheduled_date_gmt <= %s AND status=%s';
		$params[] = $date->format( 'Y-m-d H:i:s' );
		$params[] = self::STATUS_PENDING;

		if ( ! empty( $hooks ) ) {
			$placeholders = array_fill( 0, count( $hooks ), '%s' );
			$where       .= ' AND hook IN (' . join( ', ', $placeholders ) . ')';
			$params       = array_merge( $params, array_values( $hooks ) );
		}

		$group_operator = 'IN';
		if ( empty( $group ) ) {
			$group          = $this->get_claim_filter( 'exclude-groups' );
			$group_operator = 'NOT IN';
		}

		if ( ! empty( $group ) ) {
			$group_ids = $this->get_group_ids( $group, false );

			// throw exception if no matching group(s) found, this matches ActionScheduler_wpPostStore's behaviour.
			if ( empty( $group_ids ) ) {
				throw new InvalidArgumentException(
					sprintf(
						/* translators: %s: group name(s) */
						_n(
							'The group "%s" does not exist.',
							'The groups "%s" do not exist.',
							is_array( $group ) ? count( $group ) : 1,
							'action-scheduler'
						),
						$group
					)
				);
			}

			$id_list = implode( ',', array_map( 'intval', $group_ids ) );
			$where  .= " AND group_id {$group_operator} ( $id_list )";
		}

		/**
		 * Sets the order-by clause used in the action claim query.
		 *
		 * @since 3.4.0
		 * @since 3.8.3 Made $claim_id and $hooks available.
		 *
		 * @param string $order_by_sql
		 * @param string $claim_id Claim Id.
		 * @param array  $hooks Hooks to filter for.
		 */
		$order    = apply_filters( 'action_scheduler_claim_actions_order_by', 'ORDER BY priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC', $claim_id, $hooks );
		$params[] = $limit;

		$sql           = $wpdb->prepare( "{$update} {$where} {$order} LIMIT %d", $params ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders
		$rows_affected = $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		if ( false === $rows_affected ) {
			$error = empty( $wpdb->last_error )
				? _x( 'unknown', 'database error', 'action-scheduler' )
				: $wpdb->last_error;

			throw new \RuntimeException(
				sprintf(
					/* translators: %s database error. */
					__( 'Unable to claim actions. Database error: %s.', 'action-scheduler' ),
					$error
				)
			);
		}

		return (int) $rows_affected;
	}

	/**
	 * Get the number of active claims.
	 *
	 * @return int
	 */
	public function get_claim_count() {
		global $wpdb;

		$sql = "SELECT COUNT(DISTINCT claim_id) FROM {$wpdb->actionscheduler_actions} WHERE claim_id != 0 AND status IN ( %s, %s)";
		$sql = $wpdb->prepare( $sql, array( self::STATUS_PENDING, self::STATUS_RUNNING ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		return (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}

	/**
	 * Return an action's claim ID, as stored in the claim_id column.
	 *
	 * @param string $action_id Action ID.
	 * @return mixed
	 */
	public function get_claim_id( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$sql = "SELECT claim_id FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d";
		$sql = $wpdb->prepare( $sql, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		return (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
	}

	/**
	 * Retrieve the action IDs of action in a claim.
	 *
	 * @param  int $claim_id Claim ID.
	 * @return int[]
	 */
	public function find_actions_by_claim_id( $claim_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$action_ids  = array();
		$before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object();
		$cut_off     = $before_date->format( 'Y-m-d H:i:s' );

		$sql = $wpdb->prepare(
			"SELECT action_id, scheduled_date_gmt FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d ORDER BY priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC",
			$claim_id
		);

		// Verify that the scheduled date for each action is within the expected bounds (in some unusual
		// cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify).
		foreach ( $wpdb->get_results( $sql ) as $claimed_action ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			if ( $claimed_action->scheduled_date_gmt <= $cut_off ) {
				$action_ids[] = absint( $claimed_action->action_id );
			}
		}

		return $action_ids;
	}

	/**
	 * Release actions from a claim and delete the claim.
	 *
	 * @param ActionScheduler_ActionClaim $claim Claim object.
	 * @throws \RuntimeException When unable to release actions from claim.
	 */
	public function release_claim( ActionScheduler_ActionClaim $claim ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		/**
		 * Deadlock warning: This function modifies actions to release them from claims that have been processed. Earlier, we used to it in a atomic query, i.e. we would update all actions belonging to a particular claim_id with claim_id = 0.
		 * While this was functionally correct, it would cause deadlock, since this update query will hold a lock on the claim_id_.. index on the action table.
		 * This allowed the possibility of a race condition, where the claimer query is also running at the same time, then the claimer query will also try to acquire a lock on the claim_id_.. index, and in this case if claim release query has already progressed to the point of acquiring the lock, but have not updated yet, it would cause a deadlock.
		 *
		 * We resolve this by getting all the actions_id that we want to release claim from in a separate query, and then releasing the claim on each of them. This way, our lock is acquired on the action_id index instead of the claim_id index. Note that the lock on claim_id will still be acquired, but it will only when we actually make the update, rather than when we select the actions.
		 */
		$action_ids = $wpdb->get_col( $wpdb->prepare( "SELECT action_id FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d", $claim->get_id() ) );

		$row_updates = 0;
		if ( count( $action_ids ) > 0 ) {
			$action_id_string = implode( ',', array_map( 'absint', $action_ids ) );
			$row_updates      = $wpdb->query( "UPDATE {$wpdb->actionscheduler_actions} SET claim_id = 0 WHERE action_id IN ({$action_id_string})" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		}

		$wpdb->delete( $wpdb->actionscheduler_claims, array( 'claim_id' => $claim->get_id() ), array( '%d' ) );

		if ( $row_updates < count( $action_ids ) ) {
			throw new RuntimeException(
				sprintf(
					// translators: %d is an id.
					__( 'Unable to release actions from claim id %d.', 'action-scheduler' ),
					$claim->get_id()
				)
			);
		}
	}

	/**
	 * Remove the claim from an action.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return void
	 */
	public function unclaim_action( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$wpdb->update(
			$wpdb->actionscheduler_actions,
			array( 'claim_id' => 0 ),
			array( 'action_id' => $action_id ),
			array( '%s' ),
			array( '%d' )
		);
	}

	/**
	 * Mark an action as failed.
	 *
	 * @param int $action_id Action ID.
	 * @throws \InvalidArgumentException Throw an exception if action was not updated.
	 */
	public function mark_failure( $action_id ) {
		/**
		 * Global.

		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$updated = $wpdb->update(
			$wpdb->actionscheduler_actions,
			array( 'status' => self::STATUS_FAILED ),
			array( 'action_id' => $action_id ),
			array( '%s' ),
			array( '%d' )
		);
		if ( empty( $updated ) ) {
			/* translators: %s is the action ID */
			throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having failed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}
	}

	/**
	 * Add execution message to action log.
	 *
	 * @throws Exception If the action status cannot be updated to self::STATUS_RUNNING ('in-progress').
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return void
	 */
	public function log_execution( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$sql = "UPDATE {$wpdb->actionscheduler_actions} SET attempts = attempts+1, status=%s, last_attempt_gmt = %s, last_attempt_local = %s WHERE action_id = %d";
		$sql = $wpdb->prepare( $sql, self::STATUS_RUNNING, current_time( 'mysql', true ), current_time( 'mysql' ), $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$status_updated = $wpdb->query( $sql );

		if ( ! $status_updated ) {
			throw new Exception(
				sprintf(
					/* translators: 1: action ID. 2: status slug. */
					__( 'Unable to update the status of action %1$d to %2$s.', 'action-scheduler' ),
					$action_id,
					self::STATUS_RUNNING
				)
			);
		}
	}

	/**
	 * Mark an action as complete.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return void
	 * @throws \InvalidArgumentException Throw an exception if action was not updated.
	 */
	public function mark_complete( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$updated = $wpdb->update(
			$wpdb->actionscheduler_actions,
			array(
				'status'             => self::STATUS_COMPLETE,
				'last_attempt_gmt'   => current_time( 'mysql', true ),
				'last_attempt_local' => current_time( 'mysql' ),
			),
			array( 'action_id' => $action_id ),
			array( '%s' ),
			array( '%d' )
		);
		if ( empty( $updated ) ) {
			/* translators: %s is the action ID */
			throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having completed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) );
		}

		/**
		 * Fires after a scheduled action has been completed.
		 *
		 * @since 3.4.2
		 *
		 * @param int $action_id Action ID.
		 */
		do_action( 'action_scheduler_completed_action', $action_id );
	}

	/**
	 * Get an action's status.
	 *
	 * @param int $action_id Action ID.
	 *
	 * @return string
	 * @throws \InvalidArgumentException Throw an exception if not status was found for action_id.
	 * @throws \RuntimeException Throw an exception if action status could not be retrieved.
	 */
	public function get_status( $action_id ) {
		/**
		 * Global.
		 *
		 * @var \wpdb $wpdb
		 */
		global $wpdb;

		$sql    = "SELECT status FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d";
		$sql    = $wpdb->prepare( $sql, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		$status = $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		if ( is_null( $status ) ) {
			throw new \InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) );
		} elseif ( empty( $status ) ) {
			throw new \RuntimeException( __( 'Unknown status found for action.', 'action-scheduler' ) );
		} else {
			return $status;
		}
	}
}
data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php000066600000001372151137657230020752 0ustar00<?php

/**
 * Class ActionScheduler_wpPostStore_TaxonomyRegistrar
 *
 * @codeCoverageIgnore
 */
class ActionScheduler_wpPostStore_TaxonomyRegistrar {

	/**
	 * Registrar.
	 */
	public function register() {
		register_taxonomy( ActionScheduler_wpPostStore::GROUP_TAXONOMY, ActionScheduler_wpPostStore::POST_TYPE, $this->taxonomy_args() );
	}

	/**
	 * Get taxonomy arguments.
	 */
	protected function taxonomy_args() {
		$args = array(
			'label'             => __( 'Action Group', 'action-scheduler' ),
			'public'            => false,
			'hierarchical'      => false,
			'show_admin_column' => true,
			'query_var'         => false,
			'rewrite'           => false,
		);

		$args = apply_filters( 'action_scheduler_taxonomy_args', $args );
		return $args;
	}
}
data-stores/ActionScheduler_HybridStore.php000066600000030557151137657230015125 0ustar00<?php

use ActionScheduler_Store as Store;
use Action_Scheduler\Migration\Runner;
use Action_Scheduler\Migration\Config;
use Action_Scheduler\Migration\Controller;

/**
 * Class ActionScheduler_HybridStore
 *
 * A wrapper around multiple stores that fetches data from both.
 *
 * @since 3.0.0
 */
class ActionScheduler_HybridStore extends Store {
	const DEMARKATION_OPTION = 'action_scheduler_hybrid_store_demarkation';

	/**
	 * Primary store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $primary_store;

	/**
	 * Secondary store instance.
	 *
	 * @var ActionScheduler_Store
	 */
	private $secondary_store;

	/**
	 * Runner instance.
	 *
	 * @var Action_Scheduler\Migration\Runner
	 */
	private $migration_runner;

	/**
	 * The dividing line between IDs of actions created
	 * by the primary and secondary stores.
	 *
	 * @var int
	 *
	 * Methods that accept an action ID will compare the ID against
	 * this to determine which store will contain that ID. In almost
	 * all cases, the ID should come from the primary store, but if
	 * client code is bypassing the API functions and fetching IDs
	 * from elsewhere, then there is a chance that an unmigrated ID
	 * might be requested.
	 */
	private $demarkation_id = 0;

	/**
	 * ActionScheduler_HybridStore constructor.
	 *
	 * @param Config|null $config Migration config object.
	 */
	public function __construct( ?Config $config = null ) {
		$this->demarkation_id = (int) get_option( self::DEMARKATION_OPTION, 0 );
		if ( empty( $config ) ) {
			$config = Controller::instance()->get_migration_config_object();
		}
		$this->primary_store    = $config->get_destination_store();
		$this->secondary_store  = $config->get_source_store();
		$this->migration_runner = new Runner( $config );
	}

	/**
	 * Initialize the table data store tables.
	 *
	 * @codeCoverageIgnore
	 */
	public function init() {
		add_action( 'action_scheduler/created_table', array( $this, 'set_autoincrement' ), 10, 2 );
		$this->primary_store->init();
		$this->secondary_store->init();
		remove_action( 'action_scheduler/created_table', array( $this, 'set_autoincrement' ), 10 );
	}

	/**
	 * When the actions table is created, set its autoincrement
	 * value to be one higher than the posts table to ensure that
	 * there are no ID collisions.
	 *
	 * @param string $table_name Table name.
	 * @param string $table_suffix Suffix of table name.
	 *
	 * @return void
	 * @codeCoverageIgnore
	 */
	public function set_autoincrement( $table_name, $table_suffix ) {
		if ( ActionScheduler_StoreSchema::ACTIONS_TABLE === $table_suffix ) {
			if ( empty( $this->demarkation_id ) ) {
				$this->demarkation_id = $this->set_demarkation_id();
			}

			/**
			 * Global.
			 *
			 * @var \wpdb $wpdb
			 */
			global $wpdb;

			/**
			 * A default date of '0000-00-00 00:00:00' is invalid in MySQL 5.7 when configured with
			 * sql_mode including both STRICT_TRANS_TABLES and NO_ZERO_DATE.
			 */
			$default_date = new DateTime( 'tomorrow' );
			$null_action  = new ActionScheduler_NullAction();
			$date_gmt     = $this->get_scheduled_date_string( $null_action, $default_date );
			$date_local   = $this->get_scheduled_date_string_local( $null_action, $default_date );

			$row_count = $wpdb->insert(
				$wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE},
				array(
					'action_id'            => $this->demarkation_id,
					'hook'                 => '',
					'status'               => '',
					'scheduled_date_gmt'   => $date_gmt,
					'scheduled_date_local' => $date_local,
					'last_attempt_gmt'     => $date_gmt,
					'last_attempt_local'   => $date_local,
				)
			);
			if ( $row_count > 0 ) {
				$wpdb->delete(
					$wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE},
					array( 'action_id' => $this->demarkation_id )
				);
			}
		}
	}

	/**
	 * Store the demarkation id in WP options.
	 *
	 * @param int $id The ID to set as the demarkation point between the two stores
	 *                Leave null to use the next ID from the WP posts table.
	 *
	 * @return int The new ID.
	 *
	 * @codeCoverageIgnore
	 */
	private function set_demarkation_id( $id = null ) {
		if ( empty( $id ) ) {
			/**
			 * Global.
			 *
			 * @var \wpdb $wpdb
			 */
			global $wpdb;

			$id = (int) $wpdb->get_var( "SELECT MAX(ID) FROM $wpdb->posts" );
			$id++;
		}
		update_option( self::DEMARKATION_OPTION, $id );

		return $id;
	}

	/**
	 * Find the first matching action from the secondary store.
	 * If it exists, migrate it to the primary store immediately.
	 * After it migrates, the secondary store will logically contain
	 * the next matching action, so return the result thence.
	 *
	 * @param string $hook Action's hook.
	 * @param array  $params Action's arguments.
	 *
	 * @return string
	 */
	public function find_action( $hook, $params = array() ) {
		$found_unmigrated_action = $this->secondary_store->find_action( $hook, $params );
		if ( ! empty( $found_unmigrated_action ) ) {
			$this->migrate( array( $found_unmigrated_action ) );
		}

		return $this->primary_store->find_action( $hook, $params );
	}

	/**
	 * Find actions matching the query in the secondary source first.
	 * If any are found, migrate them immediately. Then the secondary
	 * store will contain the canonical results.
	 *
	 * @param array  $query Query arguments.
	 * @param string $query_type Whether to select or count the results. Default, select.
	 *
	 * @return int[]
	 */
	public function query_actions( $query = array(), $query_type = 'select' ) {
		$found_unmigrated_actions = $this->secondary_store->query_actions( $query, 'select' );
		if ( ! empty( $found_unmigrated_actions ) ) {
			$this->migrate( $found_unmigrated_actions );
		}

		return $this->primary_store->query_actions( $query, $query_type );
	}

	/**
	 * Get a count of all actions in the store, grouped by status
	 *
	 * @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status.
	 */
	public function action_counts() {
		$unmigrated_actions_count = $this->secondary_store->action_counts();
		$migrated_actions_count   = $this->primary_store->action_counts();
		$actions_count_by_status  = array();

		foreach ( $this->get_status_labels() as $status_key => $status_label ) {

			$count = 0;

			if ( isset( $unmigrated_actions_count[ $status_key ] ) ) {
				$count += $unmigrated_actions_count[ $status_key ];
			}

			if ( isset( $migrated_actions_count[ $status_key ] ) ) {
				$count += $migrated_actions_count[ $status_key ];
			}

			$actions_count_by_status[ $status_key ] = $count;
		}

		$actions_count_by_status = array_filter( $actions_count_by_status );

		return $actions_count_by_status;
	}

	/**
	 * If any actions would have been claimed by the secondary store,
	 * migrate them immediately, then ask the primary store for the
	 * canonical claim.
	 *
	 * @param int           $max_actions Maximum number of actions to claim.
	 * @param null|DateTime $before_date Latest timestamp of actions to claim.
	 * @param string[]      $hooks Hook of actions to claim.
	 * @param string        $group Group of actions to claim.
	 *
	 * @return ActionScheduler_ActionClaim
	 */
	public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ) {
		$claim = $this->secondary_store->stake_claim( $max_actions, $before_date, $hooks, $group );

		$claimed_actions = $claim->get_actions();
		if ( ! empty( $claimed_actions ) ) {
			$this->migrate( $claimed_actions );
		}

		$this->secondary_store->release_claim( $claim );

		return $this->primary_store->stake_claim( $max_actions, $before_date, $hooks, $group );
	}

	/**
	 * Migrate a list of actions to the table data store.
	 *
	 * @param array $action_ids List of action IDs.
	 */
	private function migrate( $action_ids ) {
		$this->migration_runner->migrate_actions( $action_ids );
	}

	/**
	 * Save an action to the primary store.
	 *
	 * @param ActionScheduler_Action $action Action object to be saved.
	 * @param DateTime|null          $date Optional. Schedule date. Default null.
	 *
	 * @return int The action ID
	 */
	public function save_action( ActionScheduler_Action $action, ?DateTime $date = null ) {
		return $this->primary_store->save_action( $action, $date );
	}

	/**
	 * Retrieve an existing action whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function fetch_action( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id, true );
		if ( $store ) {
			return $store->fetch_action( $action_id );
		} else {
			return new ActionScheduler_NullAction();
		}
	}

	/**
	 * Cancel an existing action whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function cancel_action( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			$store->cancel_action( $action_id );
		}
	}

	/**
	 * Delete an existing action whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function delete_action( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			$store->delete_action( $action_id );
		}
	}

	/**
	 * Get the schedule date an existing action whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function get_date( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			return $store->get_date( $action_id );
		} else {
			return null;
		}
	}

	/**
	 * Mark an existing action as failed whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function mark_failure( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			$store->mark_failure( $action_id );
		}
	}

	/**
	 * Log the execution of an existing action whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function log_execution( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			$store->log_execution( $action_id );
		}
	}

	/**
	 * Mark an existing action complete whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function mark_complete( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			$store->mark_complete( $action_id );
		}
	}

	/**
	 * Get an existing action status whether migrated or not.
	 *
	 * @param int $action_id Action ID.
	 */
	public function get_status( $action_id ) {
		$store = $this->get_store_from_action_id( $action_id );
		if ( $store ) {
			return $store->get_status( $action_id );
		}
		return null;
	}

	/**
	 * Return which store an action is stored in.
	 *
	 * @param int  $action_id ID of the action.
	 * @param bool $primary_first Optional flag indicating search the primary store first.
	 * @return ActionScheduler_Store
	 */
	protected function get_store_from_action_id( $action_id, $primary_first = false ) {
		if ( $primary_first ) {
			$stores = array(
				$this->primary_store,
				$this->secondary_store,
			);
		} elseif ( $action_id < $this->demarkation_id ) {
			$stores = array(
				$this->secondary_store,
				$this->primary_store,
			);
		} else {
			$stores = array(
				$this->primary_store,
			);
		}

		foreach ( $stores as $store ) {
			$action = $store->fetch_action( $action_id );
			if ( ! is_a( $action, 'ActionScheduler_NullAction' ) ) {
				return $store;
			}
		}
		return null;
	}

	/**
	 * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * All claim-related functions should operate solely
	 * on the primary store.
	 * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 */

	/**
	 * Get the claim count from the table data store.
	 */
	public function get_claim_count() {
		return $this->primary_store->get_claim_count();
	}

	/**
	 * Retrieve the claim ID for an action from the table data store.
	 *
	 * @param int $action_id Action ID.
	 */
	public function get_claim_id( $action_id ) {
		return $this->primary_store->get_claim_id( $action_id );
	}

	/**
	 * Release a claim in the table data store.
	 *
	 * @param ActionScheduler_ActionClaim $claim Claim object.
	 */
	public function release_claim( ActionScheduler_ActionClaim $claim ) {
		$this->primary_store->release_claim( $claim );
	}

	/**
	 * Release claims on an action in the table data store.
	 *
	 * @param int $action_id Action ID.
	 */
	public function unclaim_action( $action_id ) {
		$this->primary_store->unclaim_action( $action_id );
	}

	/**
	 * Retrieve a list of action IDs by claim.
	 *
	 * @param int $claim_id Claim ID.
	 */
	public function find_actions_by_claim_id( $claim_id ) {
		return $this->primary_store->find_actions_by_claim_id( $claim_id );
	}
}
ActionScheduler_InvalidActionException.php000066600000002717151137657230015041 0ustar00<?php

/**
 * InvalidAction Exception.
 *
 * Used for identifying actions that are invalid in some way.
 *
 * @package ActionScheduler
 */
class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception {

	/**
	 * Create a new exception when the action's schedule cannot be fetched.
	 *
	 * @param string $action_id The action ID with bad args.
	 * @param mixed  $schedule  Passed schedule.
	 * @return static
	 */
	public static function from_schedule( $action_id, $schedule ) {
		$message = sprintf(
			/* translators: 1: action ID 2: schedule */
			__( 'Action [%1$s] has an invalid schedule: %2$s', 'action-scheduler' ),
			$action_id,
			var_export( $schedule, true ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		);

		return new static( $message );
	}

	/**
	 * Create a new exception when the action's args cannot be decoded to an array.
	 *
	 * @param string $action_id The action ID with bad args.
	 * @param mixed  $args      Passed arguments.
	 * @return static
	 */
	public static function from_decoding_args( $action_id, $args = array() ) {
		$message = sprintf(
			/* translators: 1: action ID 2: arguments */
			__( 'Action [%1$s] has invalid arguments. It cannot be JSON decoded to an array. $args = %2$s', 'action-scheduler' ),
			$action_id,
			var_export( $args, true ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
		);

		return new static( $message );
	}
}
ActionScheduler_DateTime.php000066600000004014151137657230012122 0ustar00<?php

/**
 * ActionScheduler DateTime class.
 *
 * This is a custom extension to DateTime that
 */
class ActionScheduler_DateTime extends DateTime {

	/**
	 * UTC offset.
	 *
	 * Only used when a timezone is not set. When a timezone string is
	 * used, this will be set to 0.
	 *
	 * @var int
	 */
	protected $utcOffset = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase

	/**
	 * Get the unix timestamp of the current object.
	 *
	 * Missing in PHP 5.2 so just here so it can be supported consistently.
	 *
	 * @return int
	 */
	#[\ReturnTypeWillChange]
	public function getTimestamp() {
		return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' );
	}

	/**
	 * Set the UTC offset.
	 *
	 * This represents a fixed offset instead of a timezone setting.
	 *
	 * @param string|int $offset UTC offset value.
	 */
	public function setUtcOffset( $offset ) {
		$this->utcOffset = intval( $offset ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
	}

	/**
	 * Returns the timezone offset.
	 *
	 * @return int
	 * @link http://php.net/manual/en/datetime.getoffset.php
	 */
	#[\ReturnTypeWillChange]
	public function getOffset() {
		return $this->utcOffset ? $this->utcOffset : parent::getOffset(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
	}

	/**
	 * Set the TimeZone associated with the DateTime
	 *
	 * @param DateTimeZone $timezone Timezone object.
	 *
	 * @return static
	 * @link http://php.net/manual/en/datetime.settimezone.php
	 */
	#[\ReturnTypeWillChange]
	public function setTimezone( $timezone ) {
		$this->utcOffset = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
		parent::setTimezone( $timezone );

		return $this;
	}

	/**
	 * Get the timestamp with the WordPress timezone offset added or subtracted.
	 *
	 * @since  3.0.0
	 * @return int
	 */
	public function getOffsetTimestamp() {
		return $this->getTimestamp() + $this->getOffset();
	}
}