' .
+ __( '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' ) .
+ '
';
+
+ 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 = '';
+
+ $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 .= '';
+
+ 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
+ * @param DateTimezone $timezone
+ * @return string
+ */
+ protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) {
+ $date = $log_entry->get_date();
+ $date->setTimezone( $timezone );
+ return sprintf( '
%s %s
', 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 ) ) {
+ $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. View actions in-progress »', '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 = '' . $action->get_hook() . '';
+ if ( 1 == $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
+ * @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 ( ! $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 .= ' ';
+
+ 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 array $ids
+ * @param string $ids_sql Inherited and unused
+ */
+ protected function bulk_delete( array $ids, $ids_sql ) {
+ foreach ( $ids as $id ) {
+ $this->store->delete_action( $id );
+ }
+ }
+
+ /**
+ * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
+ * parameters are valid.
+ *
+ * @param int $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
+ */
+ 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
+ * @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';
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_LogEntry.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_LogEntry.php
new file mode 100644
index 0000000..649636d
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_LogEntry.php
@@ -0,0 +1,67 @@
+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;
+ }
+
+ public function get_action_id() {
+ return $this->action_id;
+ }
+
+ public function get_message() {
+ return $this->message;
+ }
+}
+
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_NullLogEntry.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_NullLogEntry.php
new file mode 100644
index 0000000..6f8f218
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_NullLogEntry.php
@@ -0,0 +1,11 @@
+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 ) {
+ return update_option( $this->get_key( $lock_type ), time() + $this->get_duration( $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.
+ */
+ public function get_expiration( $lock_type ) {
+ return get_option( $this->get_key( $lock_type ) );
+ }
+
+ /**
+ * 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 );
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_QueueCleaner.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_QueueCleaner.php
new file mode 100644
index 0000000..49cd44b
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_QueueCleaner.php
@@ -0,0 +1,158 @@
+store = $store ? $store : ActionScheduler_Store::instance();
+ $this->batch_size = $batch_size;
+ }
+
+ public function delete_old_actions() {
+ $lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds );
+ $cutoff = as_get_datetime_object($lifespan.' seconds ago');
+
+ $statuses_to_purge = array(
+ ActionScheduler_Store::STATUS_COMPLETE,
+ ActionScheduler_Store::STATUS_CANCELED,
+ );
+
+ foreach ( $statuses_to_purge as $status ) {
+ $actions_to_delete = $this->store->query_actions( array(
+ 'status' => $status,
+ 'modified' => $cutoff,
+ 'modified_compare' => '<=',
+ 'per_page' => $this->get_batch_size(),
+ 'orderby' => 'none',
+ ) );
+
+ foreach ( $actions_to_delete as $action_id ) {
+ try {
+ $this->store->delete_action( $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.
+ *
+ * @since 2.0.0
+ *
+ * @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
+ */
+ do_action( 'action_scheduler_failed_old_action_deletion', $action_id, $e, $lifespan, count( $actions_to_delete ) );
+ }
+ }
+ }
+ }
+
+ /**
+ * 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 uncatachable 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).
+ * @author Jeremy Pry
+ */
+ 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.
+ *
+ * @author Jeremy Pry
+ * @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 ) );
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_QueueRunner.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_QueueRunner.php
new file mode 100644
index 0000000..b890dca
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_QueueRunner.php
@@ -0,0 +1,220 @@
+store );
+ }
+
+ $this->async_request = $async_request;
+ }
+
+ /**
+ * @codeCoverageIgnore
+ */
+ public function init() {
+
+ add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) );
+
+ // 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() {
+ if ( is_admin() && ! ActionScheduler::lock()->is_locked( 'async-request-runner' ) ) {
+ // Only start an async queue at most once every 60 seconds
+ 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 identifer 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() ) {
+ $batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
+ do {
+ $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 identifer 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() ) ) ) {
+ 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 when it is available (but it was only introduced in WordPress 6.0).
+ */
+ if ( function_exists( 'wp_cache_flush_runtime' ) ) {
+ 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();
+ }
+ }
+
+ public function add_wp_cron_schedule( $schedules ) {
+ $schedules['every_minute'] = array(
+ 'interval' => 60, // in seconds
+ 'display' => __( 'Every minute', 'action-scheduler' ),
+ );
+
+ return $schedules;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_Versions.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_Versions.php
new file mode 100644
index 0000000..915c2e6
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_Versions.php
@@ -0,0 +1,62 @@
+versions[$version_string]) ) {
+ return FALSE;
+ }
+ $this->versions[$version_string] = $initialization_callback;
+ return TRUE;
+ }
+
+ public function get_versions() {
+ return $this->versions;
+ }
+
+ public function latest_version() {
+ $keys = array_keys($this->versions);
+ if ( empty($keys) ) {
+ return false;
+ }
+ uasort( $keys, 'version_compare' );
+ return end($keys);
+ }
+
+ public function latest_version_callback() {
+ $latest = $this->latest_version();
+ if ( empty($latest) || !isset($this->versions[$latest]) ) {
+ return '__return_null';
+ }
+ return $this->versions[$latest];
+ }
+
+ /**
+ * @return ActionScheduler_Versions
+ * @codeCoverageIgnore
+ */
+ public static function instance() {
+ if ( empty(self::$instance) ) {
+ self::$instance = new self();
+ }
+ return self::$instance;
+ }
+
+ /**
+ * @codeCoverageIgnore
+ */
+ public static function initialize_latest_version() {
+ $self = self::instance();
+ call_user_func($self->latest_version_callback());
+ }
+}
+
\ No newline at end of file
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_WPCommentCleaner.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_WPCommentCleaner.php
new file mode 100644
index 0000000..1ba552c
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_WPCommentCleaner.php
@@ -0,0 +1,115 @@
+ 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() {
+ if ( (bool) get_comments( array( 'type' => ActionScheduler_wpCommentLogger::TYPE, 'number' => 1, 'fields' => 'ids' ) ) ) {
+ update_option( self::$has_logs_option_key, 'yes' );
+
+ if ( ! as_next_scheduled_action( self::$cleanup_hook ) ) {
+ as_schedule_single_action( gmdate( 'U' ) + ( 6 * MONTH_IN_SECONDS ), self::$cleanup_hook );
+ }
+ }
+ }
+
+ /**
+ * 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 ) );
+ delete_option( self::$has_logs_option_key );
+ }
+
+ /**
+ * 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 Learn more »', 'action-scheduler' ),
+ $next_cleanup_message,
+ 'https://github.com/woocommerce/action-scheduler/issues/368'
+ );
+
+ echo '
' . wp_kses_post( $notice ) . '
';
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/ActionScheduler_wcSystemStatus.php b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_wcSystemStatus.php
new file mode 100644
index 0000000..bca63e7
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/ActionScheduler_wcSystemStatus.php
@@ -0,0 +1,166 @@
+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' => '–',
+ 'newest' => '–',
+ );
+
+ 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 = '–';
+ }
+
+ 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() );
+ ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ $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(
+ '
';
+ }
+
+ /**
+ * 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 futher 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 '';
+ }
+
+ /**
+ * 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 = '
';
+ }
+ }
+
+ /**
+ * 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 '';
+ }
+
+ /**
+ * 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 '
';
+ }
+
+ /**
+ * 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';
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php
new file mode 100644
index 0000000..3440f00
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php
@@ -0,0 +1,303 @@
+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 identifer 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.
+ */
+ public function process_action( $action_id, $context = '' ) {
+ 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 ( Exception $e ) {
+ if ( $valid_action ) {
+ $this->store->mark_failure( $action_id );
+ do_action( 'action_scheduler_failed_execution', $action_id, $e, $context );
+ } else {
+ do_action( 'action_scheduler_failed_validation', $action_id, $e, $context );
+ }
+ }
+
+ if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
+ $this->schedule_next_instance( $action, $action_id );
+ }
+ }
+
+ /**
+ * Schedule the next instance of the action if necessary.
+ *
+ * @param ActionScheduler_Action $action
+ * @param int $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*ithin the same window.
+ unset( $query_args['status'] );
+ $first_action_id_with_the_same_hook = $this->store->query_actions( $query_args );
+
+ // If the IDs match, then actions for this hook must be consistently failing.
+ return $first_action_id_with_the_same_hook === $first_failing_action_id;
+ }
+
+ /**
+ * Run the queue cleaner.
+ *
+ * @author Jeremy Pry
+ */
+ 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.
+ *
+ * @author Jeremy Pry
+ * @param string $context Optional identifer 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 = '' );
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php
new file mode 100644
index 0000000..131d475
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php
@@ -0,0 +1,102 @@
+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 recurrance 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;
+
+ /**
+ * @param DateTime $date The date & time to run the action.
+ * @param mixed $recurrence The data used to determine the schedule's recurrance.
+ * @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;
+ }
+
+ /**
+ * @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;
+ }
+
+ /**
+ * @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();
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php
new file mode 100644
index 0000000..2631ef5
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php
@@ -0,0 +1,83 @@
+scheduled_date
+ *
+ * @var int
+ */
+ protected $scheduled_timestamp = NULL;
+
+ /**
+ * @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
+ * @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
+ * @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, since DateTime objects can't be serialized
+ * @return array
+ */
+ public function __sleep() {
+ $this->scheduled_timestamp = $this->scheduled_date->getTimestamp();
+ return array(
+ 'scheduled_timestamp',
+ );
+ }
+
+ public function __wakeup() {
+ $this->scheduled_date = as_get_datetime_object( $this->scheduled_timestamp );
+ unset( $this->scheduled_timestamp );
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php
new file mode 100644
index 0000000..2334fda
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php
@@ -0,0 +1,172 @@
+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();
+ }
+ }
+
+ /**
+ * @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 );
+ }
+ }
+ }
+ }
+
+ /**
+ * @param string $table
+ *
+ * @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;
+
+ $existing_tables = $wpdb->get_col( 'SHOW TABLES' );
+ $expected_tables = array_map(
+ function ( $table_name ) use ( $wpdb ) {
+ return $wpdb->prefix . $table_name;
+ },
+ $this->tables
+ );
+
+ return count( array_intersect( $existing_tables, $expected_tables ) ) === count( $expected_tables );
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Lock.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Lock.php
new file mode 100644
index 0000000..86e8528
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Lock.php
@@ -0,0 +1,62 @@
+get_expiration( $lock_type ) >= time() );
+ }
+
+ /**
+ * Set a lock.
+ *
+ * @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 );
+ }
+
+ /**
+ * @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;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Logger.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Logger.php
new file mode 100644
index 0000000..c3afd04
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Logger.php
@@ -0,0 +1,176 @@
+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 );
+ }
+
+ public function hook_stored_action() {
+ add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) );
+ }
+
+ public function unhook_stored_action() {
+ remove_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) );
+ }
+
+ public function log_stored_action( $action_id ) {
+ $this->log( $action_id, __( 'action created', 'action-scheduler' ) );
+ }
+
+ public function log_canceled_action( $action_id ) {
+ $this->log( $action_id, __( 'action canceled', 'action-scheduler' ) );
+ }
+
+ 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 );
+ }
+
+ 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 );
+ }
+
+ 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 );
+ }
+
+ 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 ) );
+ }
+
+ 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'] ) );
+ }
+ }
+
+ public function log_reset_action( $action_id ) {
+ $this->log( $action_id, __( 'action reset', 'action-scheduler' ) );
+ }
+
+ 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 );
+ }
+
+ /**
+ * @param string $action_id
+ * @param Exception|NULL $exception The exception which occured when fetching the action. NULL by default for backward compatibility.
+ *
+ * @return ActionScheduler_LogEntry[]
+ */
+ 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 );
+ }
+
+ 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 );
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Store.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Store.php
new file mode 100644
index 0000000..a555293
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_Store.php
@@ -0,0 +1,450 @@
+ 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 );
+ }
+
+ /**
+ * @param string $action_id
+ */
+ abstract public function cancel_action( $action_id );
+
+ /**
+ * @param string $action_id
+ */
+ abstract public function delete_action( $action_id );
+
+ /**
+ * @param string $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 );
+
+
+ /**
+ * @param int $max_actions
+ * @param DateTime $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 = '' );
+
+ /**
+ * @return int
+ */
+ abstract public function get_claim_count();
+
+ /**
+ * @param ActionScheduler_ActionClaim $claim
+ */
+ abstract public function release_claim( ActionScheduler_ActionClaim $claim );
+
+ /**
+ * @param string $action_id
+ */
+ abstract public function unclaim_action( $action_id );
+
+ /**
+ * @param string $action_id
+ */
+ abstract public function mark_failure( $action_id );
+
+ /**
+ * @param string $action_id
+ */
+ abstract public function log_execution( $action_id );
+
+ /**
+ * @param string $action_id
+ */
+ abstract public function mark_complete( $action_id );
+
+ /**
+ * @param string $action_id
+ *
+ * @return string
+ */
+ abstract public function get_status( $action_id );
+
+ /**
+ * @param string $action_id
+ * @return mixed
+ */
+ abstract public function get_claim_id( $action_id );
+
+ /**
+ * @param string $claim_id
+ * @return array
+ */
+ abstract public function find_actions_by_claim_id( $claim_id );
+
+ /**
+ * @param string $comparison_operator
+ * @return string
+ */
+ protected function validate_sql_comparator( $comparison_operator ) {
+ if ( in_array( $comparison_operator, array('!=', '>', '>=', '<', '<=', '=') ) ) {
+ return $comparison_operator;
+ }
+ return '=';
+ }
+
+ /**
+ * Get the time MySQL formated date/time string for an action's (next) scheduled date.
+ *
+ * @param ActionScheduler_Action $action
+ * @param DateTime $scheduled_date (optional)
+ * @return string
+ */
+ protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
+ $next = 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 formated date/time string for an action's (next) scheduled date.
+ *
+ * @param ActionScheduler_Action $action
+ * @param DateTime $scheduled_date (optional)
+ * @return string
+ */
+ protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
+ $next = 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( json_encode( $action->get_args() ) ) > static::$max_args_length ) {
+ 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' => 'action_id',
+ )
+ );
+
+ $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' => 'action_id',
+ )
+ );
+
+ $this->bulk_cancel_actions( $action_ids );
+ }
+ }
+
+ /**
+ * Cancel a set of action IDs.
+ *
+ * @since 3.0.0
+ *
+ * @param array $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 );
+ }
+
+ /**
+ * @return array
+ */
+ 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.
+ *
+ * @param ActionScheduler_Action $action
+ * @param DateTime $scheduled_date (optional)
+ * @return string
+ */
+ public function has_pending_actions_due() {
+ $pending_actions = $this->query_actions( array(
+ 'date' => as_get_datetime_object(),
+ 'status' => ActionScheduler_Store::STATUS_PENDING,
+ 'orderby' => 'none',
+ ) );
+
+ 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.
+ */
+ public function mark_migrated( $action_id ) {}
+
+ /**
+ * @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;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php
new file mode 100644
index 0000000..fd01449
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php
@@ -0,0 +1,152 @@
+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
+ * @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 ) {
+ 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;
+ }
+ }
+
+ /**
+ * @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 = get_option('gmt_offset');
+ if ( $gmt_offset == 0 ) {
+ $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' );
+ 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 ( 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;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_Action.php b/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_Action.php
new file mode 100644
index 0000000..f538f50
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_Action.php
@@ -0,0 +1,96 @@
+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() ) );
+ }
+
+ /**
+ * @param string $hook
+ */
+ protected function set_hook( $hook ) {
+ $this->hook = $hook;
+ }
+
+ public function get_hook() {
+ return $this->hook;
+ }
+
+ protected function set_schedule( ActionScheduler_Schedule $schedule ) {
+ $this->schedule = $schedule;
+ }
+
+ /**
+ * @return ActionScheduler_Schedule
+ */
+ public function get_schedule() {
+ return $this->schedule;
+ }
+
+ protected function set_args( array $args ) {
+ $this->args = $args;
+ }
+
+ public function get_args() {
+ return $this->args;
+ }
+
+ /**
+ * @param string $group
+ */
+ protected function set_group( $group ) {
+ $this->group = $group;
+ }
+
+ /**
+ * @return string
+ */
+ public function get_group() {
+ return $this->group;
+ }
+
+ /**
+ * @return bool If the action has been finished
+ */
+ public function is_finished() {
+ return FALSE;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_CanceledAction.php b/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_CanceledAction.php
new file mode 100644
index 0000000..8bbc5d1
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_CanceledAction.php
@@ -0,0 +1,23 @@
+set_schedule( new ActionScheduler_NullSchedule() );
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_FinishedAction.php b/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_FinishedAction.php
new file mode 100644
index 0000000..b23a56c
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/actions/ActionScheduler_FinishedAction.php
@@ -0,0 +1,16 @@
+set_schedule( new ActionScheduler_NullSchedule() );
+ }
+
+ public function execute() {
+ // don't execute
+ }
+}
+
\ No newline at end of file
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_DBLogger.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_DBLogger.php
new file mode 100644
index 0000000..37bfd0d
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_DBLogger.php
@@ -0,0 +1,154 @@
+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 the 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
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_DBStore.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_DBStore.php
new file mode 100644
index 0000000..5009454
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_DBStore.php
@@ -0,0 +1,1081 @@
+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 $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 $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' => $this->get_group_id( $action->get_group() ),
+ );
+
+ $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 -- $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 -- $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 ) ? '%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 $slug The string name of a group.
+ * @param bool $create_if_not_exists Whether to create the group if it does not already exist. Default, true - create the group.
+ *
+ * @return int The group's ID, if it exists or is created, or 0 if it does not exist and is not created.
+ */
+ protected function get_group_id( $slug, $create_if_not_exists = true ) {
+ if ( empty( $slug ) ) {
+ return 0;
+ }
+ /** @var \wpdb $wpdb */
+ global $wpdb;
+ $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 );
+ }
+
+ return $group_id;
+ }
+
+ /**
+ * Create an action group.
+ *
+ * @param string $slug Group slug.
+ *
+ * @return int Group ID.
+ */
+ protected function create_group( $slug ) {
+ /** @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 ) {
+ /** @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 );
+ }
+
+ /**
+ * 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.
+ */
+ 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',
+ ) );
+
+ /** @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( 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' ) {
+ /** @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 ) {
+ /** @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', '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 ) {
+ /** @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' => 'action_id',
+ )
+ );
+
+ 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 ) {
+ /** @var \wpdb $wpdb */
+ global $wpdb;
+ $deleted = $wpdb->delete( $wpdb->actionscheduler_actions, array( 'action_id' => $action_id ), array( '%d' ) );
+ if ( empty( $deleted ) ) {
+ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) ); //phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment
+ }
+ 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 ) {
+ /** @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 ) ) {
+ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) ); //phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment
+ }
+ 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 $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() {
+ /** @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;
+ }
+
+ /**
+ * Mark actions claimed.
+ *
+ * @param string $claim_id Claim Id.
+ * @param int $limit Number of action to include in claim.
+ * @param \DateTime $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 = '' ) {
+ /** @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' ),
+ );
+
+ $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 ) );
+ }
+
+ if ( ! empty( $group ) ) {
+
+ $group_id = $this->get_group_id( $group, false );
+
+ // throw exception if no matching group found, this matches ActionScheduler_wpPostStore's behaviour.
+ if ( empty( $group_id ) ) {
+ /* translators: %s: group name */
+ throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) );
+ }
+
+ $where .= ' AND group_id = %d';
+ $params[] = $group_id;
+ }
+
+ /**
+ * Sets the order-by clause used in the action claim query.
+ *
+ * @since 3.4.0
+ *
+ * @param string $order_by_sql
+ */
+ $order = apply_filters( 'action_scheduler_claim_actions_order_by', 'ORDER BY attempts ASC, scheduled_date_gmt ASC, action_id ASC' );
+ $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 ) {
+ throw new \RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) );
+ }
+
+ 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 ) {
+ /** @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 ) {
+ /** @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",
+ $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.
+ */
+ public function release_claim( ActionScheduler_ActionClaim $claim ) {
+ /** @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.NotPrepared
+ }
+
+ $wpdb->delete( $wpdb->actionscheduler_claims, array( 'claim_id' => $claim->get_id() ), array( '%d' ) );
+
+ if ( $row_updates < count( $action_ids ) ) {
+ throw new RuntimeException(
+ sprintf(
+ __( 'Unable to release actions from claim id %d.', 'woocommerce' ),
+ $claim->get_id()
+ )
+ );
+ }
+ }
+
+ /**
+ * Remove the claim from an action.
+ *
+ * @param int $action_id Action ID.
+ *
+ * @return void
+ */
+ public function unclaim_action( $action_id ) {
+ /** @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 ) {
+ /** @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 ) ) {
+ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) ); //phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment
+ }
+ }
+
+ /**
+ * Add execution message to action log.
+ *
+ * @param int $action_id Action ID.
+ *
+ * @return void
+ */
+ public function log_execution( $action_id ) {
+ /** @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
+ $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
+ }
+
+ /**
+ * 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 ) {
+ /** @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 ) ) {
+ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) ); //phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment
+ }
+
+ /**
+ * 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 ) {
+ /** @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 ( 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;
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_HybridStore.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_HybridStore.php
new file mode 100644
index 0000000..22d61a6
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_HybridStore.php
@@ -0,0 +1,426 @@
+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', [ $this, 'set_autoincrement' ], 10, 2 );
+ $this->primary_store->init();
+ $this->secondary_store->init();
+ remove_action( 'action_scheduler/created_table', [ $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
+ * @param string $table_suffix
+ *
+ * @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();
+ }
+ /** @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},
+ [
+ '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},
+ [ '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 ) ) {
+ /** @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
+ * @param array $params
+ *
+ * @return string
+ */
+ public function find_action( $hook, $params = [] ) {
+ $found_unmigrated_action = $this->secondary_store->find_action( $hook, $params );
+ if ( ! empty( $found_unmigrated_action ) ) {
+ $this->migrate( [ $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
+ * @param string $query_type Whether to select or count the results. Default, select.
+ *
+ * @return int[]
+ */
+ public function query_actions( $query = [], $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
+ * @param DateTime|null $before_date
+ *
+ * @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 $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 = [
+ $this->primary_store,
+ $this->secondary_store,
+ ];
+ } elseif ( $action_id < $this->demarkation_id ) {
+ $stores = [
+ $this->secondary_store,
+ $this->primary_store,
+ ];
+ } else {
+ $stores = [
+ $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 );
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php
new file mode 100644
index 0000000..7215ddd
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php
@@ -0,0 +1,240 @@
+create_wp_comment( $action_id, $message, $date );
+ return $comment_id;
+ }
+
+ 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);
+ }
+
+ /**
+ * @param string $entry_id
+ *
+ * @return ActionScheduler_LogEntry
+ */
+ public function get_entry( $entry_id ) {
+ $comment = $this->get_comment( $entry_id );
+ if ( empty($comment) || $comment->comment_type != self::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 );
+ }
+
+ /**
+ * @param string $action_id
+ *
+ * @return ActionScheduler_LogEntry[]
+ */
+ public function get_logs( $action_id ) {
+ $status = 'all';
+ 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,
+ ));
+ $logs = array();
+ foreach ( $comments as $c ) {
+ $entry = $this->get_entry( $c );
+ if ( !empty($entry) ) {
+ $logs[] = $entry;
+ }
+ }
+ return $logs;
+ }
+
+ protected function get_comment( $comment_id ) {
+ return get_comment( $comment_id );
+ }
+
+
+
+ /**
+ * @param WP_Comment_Query $query
+ */
+ 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 );
+ }
+
+ /**
+ * @param array $clauses
+ * @param WP_Comment_Query $query
+ *
+ * @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
+ * @param WP_Query $query
+ *
+ * @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
+ * @param int $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' );
+ }
+
+ /**
+ * @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' ) );
+ }
+
+ public function disable_comment_counting() {
+ wp_defer_comment_counting(true);
+ }
+ public function enable_comment_counting() {
+ wp_defer_comment_counting(false);
+ }
+
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore.php
new file mode 100644
index 0000000..7883ca8
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore.php
@@ -0,0 +1,1075 @@
+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 $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', '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', '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', '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 $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 $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 // 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,
+ '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.
+ *
+ * @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
+ $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
+ )
+ );
+ }
+
+ /**
+ * 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', '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();
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php
new file mode 100644
index 0000000..246bc34
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php
@@ -0,0 +1,58 @@
+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 (%s)', 'Failed (%s)', '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 (%s)', 'In-Progress (%s)', 'action-scheduler' ),
+ );
+
+ return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php
new file mode 100644
index 0000000..8c63bd0
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php
@@ -0,0 +1,50 @@
+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 cetain 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;
+ }
+}
+
\ No newline at end of file
diff --git a/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php
new file mode 100644
index 0000000..367401f
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php
@@ -0,0 +1,26 @@
+taxonomy_args() );
+ }
+
+ 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;
+ }
+}
+
\ No newline at end of file
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/ActionMigrator.php b/inc/Dependencies/ActionScheduler/classes/migration/ActionMigrator.php
new file mode 100644
index 0000000..c77d083
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/ActionMigrator.php
@@ -0,0 +1,109 @@
+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
+ */
+ 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 ) {
+ // 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 );
+
+ return 0;
+ }
+
+ try {
+
+ // Make sure the last attempt date is set correctly for completed and failed actions
+ $last_attempt_date = ( $status !== \ActionScheduler_Store::STATUS_PENDING ) ? $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 );
+
+ 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' ) ) {
+ 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 );
+
+ return $destination_action_id;
+ } catch ( \Exception $e ) {
+ // could not delete from the old store
+ $this->source->mark_migrated( $source_action_id );
+ 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 );
+
+ return $destination_action_id;
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/ActionScheduler_DBStoreMigrator.php b/inc/Dependencies/ActionScheduler/classes/migration/ActionScheduler_DBStoreMigrator.php
new file mode 100644
index 0000000..41c21da
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/ActionScheduler_DBStoreMigrator.php
@@ -0,0 +1,47 @@
+ $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 ) {
+ throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/BatchFetcher.php b/inc/Dependencies/ActionScheduler/classes/migration/BatchFetcher.php
new file mode 100644
index 0000000..4872801
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/BatchFetcher.php
@@ -0,0 +1,86 @@
+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 [];
+ }
+
+ /**
+ * 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 = [
+ 'date' => $now,
+ 'per_page' => $count,
+ 'offset' => 0,
+ 'orderby' => 'date',
+ 'order' => 'ASC',
+ ];
+
+ $priorities = [
+ 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( [
+ 'status' => $status,
+ 'date_compare' => '<=',
+ ], $args );
+ yield wp_parse_args( [
+ 'status' => $status,
+ 'date_compare' => '>=',
+ ], $args );
+ }
+ }
+}
\ No newline at end of file
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/Config.php b/inc/Dependencies/ActionScheduler/classes/migration/Config.php
new file mode 100644
index 0000000..50f41ff
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/Config.php
@@ -0,0 +1,168 @@
+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 loger.
+ *
+ * @return ActionScheduler_Logger
+ */
+ 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
+ */
+ public function set_source_logger( Logger $logger ) {
+ $this->source_logger = $logger;
+ }
+
+ /**
+ * Get the configured destination store.
+ *
+ * @return ActionScheduler_Store
+ */
+ 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
+ */
+ public function set_destination_store( Store $store ) {
+ $this->destination_store = $store;
+ }
+
+ /**
+ * Get the configured destination logger.
+ *
+ * @return ActionScheduler_Logger
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ public function set_progress_bar( ProgressBar $progress_bar ) {
+ $this->progress_bar = $progress_bar;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/Controller.php b/inc/Dependencies/ActionScheduler/classes/migration/Controller.php
new file mode 100644
index 0000000..b2b618d
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/Controller.php
@@ -0,0 +1,226 @@
+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 );
+ }
+
+ /**
+ * 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( '
%s
', 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.
+ *
+ * @author Jeremy Pry
+ */
+ 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;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/DryRun_ActionMigrator.php b/inc/Dependencies/ActionScheduler/classes/migration/DryRun_ActionMigrator.php
new file mode 100644
index 0000000..ffc21c2
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/DryRun_ActionMigrator.php
@@ -0,0 +1,28 @@
+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 ( $log->get_action_id() == $source_action_id ) {
+ $this->destination->log( $destination_action_id, $log->get_message(), $log->get_date() );
+ }
+ }
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/Runner.php b/inc/Dependencies/ActionScheduler/classes/migration/Runner.php
new file mode 100644
index 0000000..867c5de
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/Runner.php
@@ -0,0 +1,136 @@
+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' ), number_format_i18n( $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 );
+
+ \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 );
+ }
+
+ /**
+ * Initialize destination store and logger.
+ */
+ public function init_destination() {
+ $this->destination_store->init();
+ $this->destination_logger->init();
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/migration/Scheduler.php b/inc/Dependencies/ActionScheduler/classes/migration/Scheduler.php
new file mode 100644
index 0000000..dcbe2db
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/migration/Scheduler.php
@@ -0,0 +1,128 @@
+get_migration_runner();
+ $count = $migration_runner->run( $this->get_batch_size() );
+
+ if ( $count === 0 ) {
+ $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' );
+ }
+
+ /**
+ * 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 );
+ }
+
+ /**
+ * 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 );
+ }
+
+ /**
+ * Get migration runner object.
+ *
+ * @return Runner
+ */
+ private function get_migration_runner() {
+ $config = Controller::instance()->get_migration_config_object();
+
+ return new Runner( $config );
+ }
+
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_CanceledSchedule.php b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_CanceledSchedule.php
new file mode 100644
index 0000000..840e482
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_CanceledSchedule.php
@@ -0,0 +1,57 @@
+__wakeup() for details.
+ **/
+ private $timestamp = NULL;
+
+ /**
+ * @param DateTime $after
+ *
+ * @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
+ * @return DateTime|null
+ */
+ public function get_next( DateTime $after ) {
+ return null;
+ }
+
+ /**
+ * @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();
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_CronSchedule.php b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_CronSchedule.php
new file mode 100644
index 0000000..7859307
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_CronSchedule.php
@@ -0,0 +1,102 @@
+__wakeup() for details.
+ **/
+ private $start_timestamp = NULL;
+
+ /**
+ * Deprecated property @see $this->__wakeup() for details.
+ **/
+ 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
+ * @return DateTime
+ */
+ protected function calculate_next( DateTime $after ) {
+ return $this->recurrence->getNextRunDate( $after, 0, false );
+ }
+
+ /**
+ * @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, reccuring 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();
+ }
+}
+
diff --git a/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_IntervalSchedule.php b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_IntervalSchedule.php
new file mode 100644
index 0000000..11a591e
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_IntervalSchedule.php
@@ -0,0 +1,81 @@
+__wakeup() for details.
+ **/
+ private $start_timestamp = NULL;
+
+ /**
+ * Deprecated property @see $this->__wakeup() for details.
+ **/
+ 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
+ * @return DateTime
+ */
+ protected function calculate_next( DateTime $after ) {
+ $after->modify( '+' . (int) $this->get_recurrence() . ' seconds' );
+ return $after;
+ }
+
+ /**
+ * @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, reccuring 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();
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_NullSchedule.php b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_NullSchedule.php
new file mode 100644
index 0000000..1b1afec
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_NullSchedule.php
@@ -0,0 +1,31 @@
+scheduled_date = null;
+ }
+
+ /**
+ * This schedule has no scheduled DateTime, so we need to override the parent __sleep()
+ * @return array
+ */
+ public function __sleep() {
+ return array();
+ }
+
+ public function __wakeup() {
+ $this->scheduled_date = null;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_Schedule.php b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_Schedule.php
new file mode 100644
index 0000000..d61a9f7
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schedules/ActionScheduler_Schedule.php
@@ -0,0 +1,18 @@
+__wakeup() for details.
+ **/
+ private $timestamp = NULL;
+
+ /**
+ * @param DateTime $after
+ *
+ * @return DateTime|null
+ */
+ public function calculate_next( DateTime $after ) {
+ return null;
+ }
+
+ /**
+ * @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();
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/schema/ActionScheduler_LoggerSchema.php b/inc/Dependencies/ActionScheduler/classes/schema/ActionScheduler_LoggerSchema.php
new file mode 100644
index 0000000..c52d37c
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schema/ActionScheduler_LoggerSchema.php
@@ -0,0 +1,90 @@
+tables = [
+ 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 );
+ }
+
+ 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
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/classes/schema/ActionScheduler_StoreSchema.php b/inc/Dependencies/ActionScheduler/classes/schema/ActionScheduler_StoreSchema.php
new file mode 100644
index 0000000..d52f27f
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/classes/schema/ActionScheduler_StoreSchema.php
@@ -0,0 +1,129 @@
+tables = [
+ 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 );
+ }
+
+ protected function get_table_definition( $table ) {
+ global $wpdb;
+ $table_name = $wpdb->$table;
+ $charset_collate = $wpdb->get_charset_collate();
+ $max_index_length = 191; // @see wp_get_db_schema()
+ $default_date = self::DEFAULT_DATE;
+ 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}',
+ 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 (hook($max_index_length)),
+ KEY status (status),
+ 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
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/deprecated/ActionScheduler_Abstract_QueueRunner_Deprecated.php b/inc/Dependencies/ActionScheduler/deprecated/ActionScheduler_Abstract_QueueRunner_Deprecated.php
new file mode 100644
index 0000000..dac17aa
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/deprecated/ActionScheduler_Abstract_QueueRunner_Deprecated.php
@@ -0,0 +1,27 @@
+get_date();
+ $replacement_method = 'get_date()';
+ } else {
+ $return_value = $this->get_next( $after );
+ $replacement_method = 'get_next( $after )';
+ }
+
+ _deprecated_function( __METHOD__, '3.0.0', __CLASS__ . '::' . $replacement_method ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
+
+ return $return_value;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/deprecated/ActionScheduler_Store_Deprecated.php b/inc/Dependencies/ActionScheduler/deprecated/ActionScheduler_Store_Deprecated.php
new file mode 100644
index 0000000..002dc75
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/deprecated/ActionScheduler_Store_Deprecated.php
@@ -0,0 +1,49 @@
+mark_failure( $action_id );
+ }
+
+ /**
+ * Add base hooks
+ *
+ * @since 2.2.6
+ */
+ protected static function hook() {
+ _deprecated_function( __METHOD__, '3.0.0' );
+ }
+
+ /**
+ * Remove base hooks
+ *
+ * @since 2.2.6
+ */
+ protected static function unhook() {
+ _deprecated_function( __METHOD__, '3.0.0' );
+ }
+
+ /**
+ * Get the site's local time.
+ *
+ * @deprecated 2.1.0
+ * @return DateTimeZone
+ */
+ protected function get_local_timezone() {
+ _deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' );
+ return ActionScheduler_TimezoneHelper::get_local_timezone();
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/deprecated/functions.php b/inc/Dependencies/ActionScheduler/deprecated/functions.php
new file mode 100644
index 0000000..f782c4b
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/deprecated/functions.php
@@ -0,0 +1,126 @@
+ '' - the name of the action that will be triggered
+ * 'args' => NULL - the args array that will be passed with the action
+ * 'date' => NULL - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
+ * 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='
+ * 'modified' => NULL - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
+ * 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='
+ * 'group' => '' - the group the action belongs to
+ * 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING
+ * 'claimed' => NULL - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID
+ * 'per_page' => 5 - Number of results to return
+ * 'offset' => 0
+ * 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date'
+ * 'order' => 'ASC'
+ * @param string $return_format OBJECT, ARRAY_A, or ids
+ *
+ * @deprecated 2.1.0
+ *
+ * @return array
+ */
+function wc_get_scheduled_actions( $args = array(), $return_format = OBJECT ) {
+ _deprecated_function( __FUNCTION__, '2.1.0', 'as_get_scheduled_actions()' );
+ return as_get_scheduled_actions( $args, $return_format );
+}
diff --git a/inc/Dependencies/ActionScheduler/functions.php b/inc/Dependencies/ActionScheduler/functions.php
new file mode 100644
index 0000000..09ef353
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/functions.php
@@ -0,0 +1,424 @@
+async_unique( $hook, $args, $group, $unique );
+}
+
+/**
+ * Schedule an action to run one time
+ *
+ * @param int $timestamp When the job will run.
+ * @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.
+ * @param bool $unique Whether the action should be unique.
+ *
+ * @return int The action ID.
+ */
+function as_schedule_single_action( $timestamp, $hook, $args = array(), $group = '', $unique = false ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return 0;
+ }
+
+ /**
+ * Provides an opportunity to short-circuit the default process for enqueuing single
+ * actions.
+ *
+ * Returning a value other than null from the filter will short-circuit the normal
+ * process. The expectation in such a scenario is that callbacks will return an integer
+ * representing the scheduled action ID (scheduled using some alternative process) or else
+ * zero.
+ *
+ * @param int|null $pre_option The value to return instead of the option value.
+ * @param int $timestamp When the action will run.
+ * @param string $hook Action hook.
+ * @param array $args Action arguments.
+ * @param string $group Action group.
+ */
+ $pre = apply_filters( 'pre_as_schedule_single_action', null, $timestamp, $hook, $args, $group );
+ if ( null !== $pre ) {
+ return is_int( $pre ) ? $pre : 0;
+ }
+
+ return ActionScheduler::factory()->single_unique( $hook, $args, $timestamp, $group, $unique );
+}
+
+/**
+ * Schedule a recurring action
+ *
+ * @param int $timestamp When the first instance of the job will run.
+ * @param int $interval_in_seconds How long to wait between runs.
+ * @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.
+ * @param bool $unique Whether the action should be unique.
+ *
+ * @return int The action ID.
+ */
+function as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '', $unique = false ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return 0;
+ }
+
+ /**
+ * Provides an opportunity to short-circuit the default process for enqueuing recurring
+ * actions.
+ *
+ * Returning a value other than null from the filter will short-circuit the normal
+ * process. The expectation in such a scenario is that callbacks will return an integer
+ * representing the scheduled action ID (scheduled using some alternative process) or else
+ * zero.
+ *
+ * @param int|null $pre_option The value to return instead of the option value.
+ * @param int $timestamp When the action will run.
+ * @param int $interval_in_seconds How long to wait between runs.
+ * @param string $hook Action hook.
+ * @param array $args Action arguments.
+ * @param string $group Action group.
+ */
+ $pre = apply_filters( 'pre_as_schedule_recurring_action', null, $timestamp, $interval_in_seconds, $hook, $args, $group );
+ if ( null !== $pre ) {
+ return is_int( $pre ) ? $pre : 0;
+ }
+
+ return ActionScheduler::factory()->recurring_unique( $hook, $args, $timestamp, $interval_in_seconds, $group, $unique );
+}
+
+/**
+ * Schedule an action that recurs on a cron-like schedule.
+ *
+ * @param int $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 string $schedule A cron-link schedule string.
+ * @see http://en.wikipedia.org/wiki/Cron
+ * * * * * * *
+ * ┬ ┬ ┬ ┬ ┬ ┬
+ * | | | | | |
+ * | | | | | + year [optional]
+ * | | | | +----- day of week (0 - 7) (Sunday=0 or 7)
+ * | | | +---------- month (1 - 12)
+ * | | +--------------- day of month (1 - 31)
+ * | +-------------------- hour (0 - 23)
+ * +------------------------- min (0 - 59)
+ * @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.
+ * @param bool $unique Whether the action should be unique.
+ *
+ * @return int The action ID.
+ */
+function as_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '', $unique = false ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return 0;
+ }
+
+ /**
+ * Provides an opportunity to short-circuit the default process for enqueuing cron
+ * actions.
+ *
+ * Returning a value other than null from the filter will short-circuit the normal
+ * process. The expectation in such a scenario is that callbacks will return an integer
+ * representing the scheduled action ID (scheduled using some alternative process) or else
+ * zero.
+ *
+ * @param int|null $pre_option The value to return instead of the option value.
+ * @param int $timestamp When the action will run.
+ * @param string $schedule Cron-like schedule string.
+ * @param string $hook Action hook.
+ * @param array $args Action arguments.
+ * @param string $group Action group.
+ */
+ $pre = apply_filters( 'pre_as_schedule_cron_action', null, $timestamp, $schedule, $hook, $args, $group );
+ if ( null !== $pre ) {
+ return is_int( $pre ) ? $pre : 0;
+ }
+
+ return ActionScheduler::factory()->cron_unique( $hook, $args, $timestamp, $schedule, $group, $unique );
+}
+
+/**
+ * Cancel the next occurrence of a scheduled action.
+ *
+ * While only the next instance of a recurring or cron action is unscheduled by this method, that will also prevent
+ * all future instances of that recurring or cron action from being run. Recurring and cron actions are scheduled in
+ * a sequence instead of all being scheduled at once. Each successive occurrence of a recurring action is scheduled
+ * only after the former action is run. If the next instance is never run, because it's unscheduled by this function,
+ * then the following instance will never be scheduled (or exist), which is effectively the same as being unscheduled
+ * by this method also.
+ *
+ * @param string $hook The hook that the job will trigger.
+ * @param array $args Args that would have been passed to the job.
+ * @param string $group The group the job is assigned to.
+ *
+ * @return int|null The scheduled action ID if a scheduled action was found, or null if no matching action found.
+ */
+function as_unschedule_action( $hook, $args = array(), $group = '' ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return 0;
+ }
+ $params = array(
+ 'hook' => $hook,
+ 'status' => ActionScheduler_Store::STATUS_PENDING,
+ 'orderby' => 'date',
+ 'order' => 'ASC',
+ 'group' => $group,
+ );
+ if ( is_array( $args ) ) {
+ $params['args'] = $args;
+ }
+
+ $action_id = ActionScheduler::store()->query_action( $params );
+
+ if ( $action_id ) {
+ try {
+ ActionScheduler::store()->cancel_action( $action_id );
+ } catch ( Exception $exception ) {
+ ActionScheduler::logger()->log(
+ $action_id,
+ sprintf(
+ /* translators: %s is the name of the hook to be cancelled. */
+ __( 'Caught exception while cancelling action: %s', 'action-scheduler' ),
+ esc_attr( $hook )
+ )
+ );
+
+ $action_id = null;
+ }
+ }
+
+ return $action_id;
+}
+
+/**
+ * Cancel all occurrences of a scheduled action.
+ *
+ * @param string $hook The hook that the job will trigger.
+ * @param array $args Args that would have been passed to the job.
+ * @param string $group The group the job is assigned to.
+ */
+function as_unschedule_all_actions( $hook, $args = array(), $group = '' ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return;
+ }
+ if ( empty( $args ) ) {
+ if ( ! empty( $hook ) && empty( $group ) ) {
+ ActionScheduler_Store::instance()->cancel_actions_by_hook( $hook );
+ return;
+ }
+ if ( ! empty( $group ) && empty( $hook ) ) {
+ ActionScheduler_Store::instance()->cancel_actions_by_group( $group );
+ return;
+ }
+ }
+ do {
+ $unscheduled_action = as_unschedule_action( $hook, $args, $group );
+ } while ( ! empty( $unscheduled_action ) );
+}
+
+/**
+ * Check if there is an existing action in the queue with a given hook, args and group combination.
+ *
+ * An action in the queue could be pending, in-progress or async. If the is pending for a time in
+ * future, its scheduled date will be returned as a timestamp. If it is currently being run, or an
+ * async action sitting in the queue waiting to be processed, in which case boolean true will be
+ * returned. Or there may be no async, in-progress or pending action for this hook, in which case,
+ * boolean false will be the return value.
+ *
+ * @param string $hook Name of the hook to search for.
+ * @param array $args Arguments of the action to be searched.
+ * @param string $group Group of the action to be searched.
+ *
+ * @return int|bool The timestamp for the next occurrence of a pending scheduled action, true for an async or in-progress action or false if there is no matching action.
+ */
+function as_next_scheduled_action( $hook, $args = null, $group = '' ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return false;
+ }
+
+ $params = array(
+ 'hook' => $hook,
+ 'orderby' => 'date',
+ 'order' => 'ASC',
+ 'group' => $group,
+ );
+
+ if ( is_array( $args ) ) {
+ $params['args'] = $args;
+ }
+
+ $params['status'] = ActionScheduler_Store::STATUS_RUNNING;
+ $action_id = ActionScheduler::store()->query_action( $params );
+ if ( $action_id ) {
+ return true;
+ }
+
+ $params['status'] = ActionScheduler_Store::STATUS_PENDING;
+ $action_id = ActionScheduler::store()->query_action( $params );
+ if ( null === $action_id ) {
+ return false;
+ }
+
+ $action = ActionScheduler::store()->fetch_action( $action_id );
+ $scheduled_date = $action->get_schedule()->get_date();
+ if ( $scheduled_date ) {
+ return (int) $scheduled_date->format( 'U' );
+ } elseif ( null === $scheduled_date ) { // pending async action with NullSchedule.
+ return true;
+ }
+
+ return false;
+}
+
+/**
+ * Check if there is a scheduled action in the queue but more efficiently than as_next_scheduled_action().
+ *
+ * It's recommended to use this function when you need to know whether a specific action is currently scheduled
+ * (pending or in-progress).
+ *
+ * @since 3.3.0
+ *
+ * @param string $hook The hook of the action.
+ * @param array $args Args that have been passed to the action. Null will matches any args.
+ * @param string $group The group the job is assigned to.
+ *
+ * @return bool True if a matching action is pending or in-progress, false otherwise.
+ */
+function as_has_scheduled_action( $hook, $args = null, $group = '' ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return false;
+ }
+
+ $query_args = array(
+ 'hook' => $hook,
+ 'status' => array( ActionScheduler_Store::STATUS_RUNNING, ActionScheduler_Store::STATUS_PENDING ),
+ 'group' => $group,
+ 'orderby' => 'none',
+ );
+
+ if ( null !== $args ) {
+ $query_args['args'] = $args;
+ }
+
+ $action_id = ActionScheduler::store()->query_action( $query_args );
+
+ return null !== $action_id;
+}
+
+/**
+ * Find scheduled actions
+ *
+ * @param array $args Possible arguments, with their default values.
+ * 'hook' => '' - the name of the action that will be triggered.
+ * 'args' => NULL - the args array that will be passed with the action.
+ * 'date' => NULL - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
+ * 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='.
+ * 'modified' => NULL - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
+ * 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='.
+ * 'group' => '' - the group the action belongs to.
+ * 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING.
+ * 'claimed' => NULL - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID.
+ * 'per_page' => 5 - Number of results to return.
+ * 'offset' => 0.
+ * 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', 'date' or 'none'.
+ * 'order' => 'ASC'.
+ *
+ * @param string $return_format OBJECT, ARRAY_A, or ids.
+ *
+ * @return array
+ */
+function as_get_scheduled_actions( $args = array(), $return_format = OBJECT ) {
+ if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) {
+ return array();
+ }
+ $store = ActionScheduler::store();
+ foreach ( array( 'date', 'modified' ) as $key ) {
+ if ( isset( $args[ $key ] ) ) {
+ $args[ $key ] = as_get_datetime_object( $args[ $key ] );
+ }
+ }
+ $ids = $store->query_actions( $args );
+
+ if ( 'ids' === $return_format || 'int' === $return_format ) {
+ return $ids;
+ }
+
+ $actions = array();
+ foreach ( $ids as $action_id ) {
+ $actions[ $action_id ] = $store->fetch_action( $action_id );
+ }
+
+ if ( ARRAY_A == $return_format ) {
+ foreach ( $actions as $action_id => $action_object ) {
+ $actions[ $action_id ] = get_object_vars( $action_object );
+ }
+ }
+
+ return $actions;
+}
+
+/**
+ * Helper function to create an instance of DateTime based on a given
+ * string and timezone. By default, will return the current date/time
+ * in the UTC timezone.
+ *
+ * Needed because new DateTime() called without an explicit timezone
+ * will create a date/time in PHP's timezone, but we need to have
+ * assurance that a date/time uses the right timezone (which we almost
+ * always want to be UTC), which means we need to always include the
+ * timezone when instantiating datetimes rather than leaving it up to
+ * the PHP default.
+ *
+ * @param mixed $date_string A date/time string. Valid formats are explained in http://php.net/manual/en/datetime.formats.php.
+ * @param string $timezone A timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available http://php.net/manual/en/timezones.php.
+ *
+ * @return ActionScheduler_DateTime
+ */
+function as_get_datetime_object( $date_string = null, $timezone = 'UTC' ) {
+ if ( is_object( $date_string ) && $date_string instanceof DateTime ) {
+ $date = new ActionScheduler_DateTime( $date_string->format( 'Y-m-d H:i:s' ), new DateTimeZone( $timezone ) );
+ } elseif ( is_numeric( $date_string ) ) {
+ $date = new ActionScheduler_DateTime( '@' . $date_string, new DateTimeZone( $timezone ) );
+ } else {
+ $date = new ActionScheduler_DateTime( null === $date_string ? 'now' : $date_string, new DateTimeZone( $timezone ) );
+ }
+ return $date;
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/WP_Async_Request.php b/inc/Dependencies/ActionScheduler/lib/WP_Async_Request.php
new file mode 100644
index 0000000..ff5e29b
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/WP_Async_Request.php
@@ -0,0 +1,191 @@
+identifier = $this->prefix . '_' . $this->action;
+
+ add_action( 'wp_ajax_' . $this->identifier, array( $this, 'maybe_handle' ) );
+ add_action( 'wp_ajax_nopriv_' . $this->identifier, array( $this, 'maybe_handle' ) );
+ }
+
+ /**
+ * Set data used during the request
+ *
+ * @param array $data Data.
+ *
+ * @return $this
+ */
+ public function data( $data ) {
+ $this->data = $data;
+
+ return $this;
+ }
+
+ /**
+ * Dispatch the async request
+ *
+ * @return array|WP_Error
+ */
+ public function dispatch() {
+ $url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
+ $args = $this->get_post_args();
+
+ return wp_remote_post( esc_url_raw( $url ), $args );
+ }
+
+ /**
+ * Get query args
+ *
+ * @return array
+ */
+ protected function get_query_args() {
+ if ( property_exists( $this, 'query_args' ) ) {
+ return $this->query_args;
+ }
+
+ $args = array(
+ 'action' => $this->identifier,
+ 'nonce' => wp_create_nonce( $this->identifier ),
+ );
+
+ /**
+ * Filters the post arguments used during an async request.
+ *
+ * @param array $url
+ */
+ return apply_filters( $this->identifier . '_query_args', $args );
+ }
+
+ /**
+ * Get query URL
+ *
+ * @return string
+ */
+ protected function get_query_url() {
+ if ( property_exists( $this, 'query_url' ) ) {
+ return $this->query_url;
+ }
+
+ $url = admin_url( 'admin-ajax.php' );
+
+ /**
+ * Filters the post arguments used during an async request.
+ *
+ * @param string $url
+ */
+ return apply_filters( $this->identifier . '_query_url', $url );
+ }
+
+ /**
+ * Get post args
+ *
+ * @return array
+ */
+ protected function get_post_args() {
+ if ( property_exists( $this, 'post_args' ) ) {
+ return $this->post_args;
+ }
+
+ $args = array(
+ 'timeout' => 0.01,
+ 'blocking' => false,
+ 'body' => $this->data,
+ 'cookies' => $_COOKIE,
+ 'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
+ );
+
+ /**
+ * Filters the post arguments used during an async request.
+ *
+ * @param array $args
+ */
+ return apply_filters( $this->identifier . '_post_args', $args );
+ }
+
+ /**
+ * Maybe handle
+ *
+ * Check for correct nonce and pass to handler.
+ */
+ public function maybe_handle() {
+ // Don't lock up other requests while processing
+ session_write_close();
+
+ check_ajax_referer( $this->identifier, 'nonce' );
+
+ $this->handle();
+
+ wp_die();
+ }
+
+ /**
+ * Handle
+ *
+ * Override this method to perform any actions required
+ * during the async request.
+ */
+ abstract protected function handle();
+
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression.php
new file mode 100644
index 0000000..7f33c37
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression.php
@@ -0,0 +1,318 @@
+
+ * @link http://en.wikipedia.org/wiki/Cron
+ */
+class CronExpression
+{
+ const MINUTE = 0;
+ const HOUR = 1;
+ const DAY = 2;
+ const MONTH = 3;
+ const WEEKDAY = 4;
+ const YEAR = 5;
+
+ /**
+ * @var array CRON expression parts
+ */
+ private $cronParts;
+
+ /**
+ * @var CronExpression_FieldFactory CRON field factory
+ */
+ private $fieldFactory;
+
+ /**
+ * @var array Order in which to test of cron parts
+ */
+ private static $order = array(self::YEAR, self::MONTH, self::DAY, self::WEEKDAY, self::HOUR, self::MINUTE);
+
+ /**
+ * Factory method to create a new CronExpression.
+ *
+ * @param string $expression The CRON expression to create. There are
+ * several special predefined values which can be used to substitute the
+ * CRON expression:
+ *
+ * @yearly, @annually) - Run once a year, midnight, Jan. 1 - 0 0 1 1 *
+ * @monthly - Run once a month, midnight, first of month - 0 0 1 * *
+ * @weekly - Run once a week, midnight on Sun - 0 0 * * 0
+ * @daily - Run once a day, midnight - 0 0 * * *
+ * @hourly - Run once an hour, first minute - 0 * * * *
+ *
+*@param CronExpression_FieldFactory $fieldFactory (optional) Field factory to use
+ *
+ * @return CronExpression
+ */
+ public static function factory($expression, CronExpression_FieldFactory $fieldFactory = null)
+ {
+ $mappings = array(
+ '@yearly' => '0 0 1 1 *',
+ '@annually' => '0 0 1 1 *',
+ '@monthly' => '0 0 1 * *',
+ '@weekly' => '0 0 * * 0',
+ '@daily' => '0 0 * * *',
+ '@hourly' => '0 * * * *'
+ );
+
+ if (isset($mappings[$expression])) {
+ $expression = $mappings[$expression];
+ }
+
+ return new self($expression, $fieldFactory ? $fieldFactory : new CronExpression_FieldFactory());
+ }
+
+ /**
+ * Parse a CRON expression
+ *
+ * @param string $expression CRON expression (e.g. '8 * * * *')
+ * @param CronExpression_FieldFactory $fieldFactory Factory to create cron fields
+ */
+ public function __construct($expression, CronExpression_FieldFactory $fieldFactory)
+ {
+ $this->fieldFactory = $fieldFactory;
+ $this->setExpression($expression);
+ }
+
+ /**
+ * Set or change the CRON expression
+ *
+ * @param string $value CRON expression (e.g. 8 * * * *)
+ *
+ * @return CronExpression
+ * @throws InvalidArgumentException if not a valid CRON expression
+ */
+ public function setExpression($value)
+ {
+ $this->cronParts = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY);
+ if (count($this->cronParts) < 5) {
+ throw new InvalidArgumentException(
+ $value . ' is not a valid CRON expression'
+ );
+ }
+
+ foreach ($this->cronParts as $position => $part) {
+ $this->setPart($position, $part);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Set part of the CRON expression
+ *
+ * @param int $position The position of the CRON expression to set
+ * @param string $value The value to set
+ *
+ * @return CronExpression
+ * @throws InvalidArgumentException if the value is not valid for the part
+ */
+ public function setPart($position, $value)
+ {
+ if (!$this->fieldFactory->getField($position)->validate($value)) {
+ throw new InvalidArgumentException(
+ 'Invalid CRON field value ' . $value . ' as position ' . $position
+ );
+ }
+
+ $this->cronParts[$position] = $value;
+
+ return $this;
+ }
+
+ /**
+ * Get a next run date relative to the current date or a specific date
+ *
+ * @param string|DateTime $currentTime (optional) Relative calculation date
+ * @param int $nth (optional) Number of matches to skip before returning a
+ * matching next run date. 0, the default, will return the current
+ * date and time if the next run date falls on the current date and
+ * time. Setting this value to 1 will skip the first match and go to
+ * the second match. Setting this value to 2 will skip the first 2
+ * matches and so on.
+ * @param bool $allowCurrentDate (optional) Set to TRUE to return the
+ * current date if it matches the cron expression
+ *
+ * @return DateTime
+ * @throws RuntimeException on too many iterations
+ */
+ public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
+ {
+ return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate);
+ }
+
+ /**
+ * Get a previous run date relative to the current date or a specific date
+ *
+ * @param string|DateTime $currentTime (optional) Relative calculation date
+ * @param int $nth (optional) Number of matches to skip before returning
+ * @param bool $allowCurrentDate (optional) Set to TRUE to return the
+ * current date if it matches the cron expression
+ *
+ * @return DateTime
+ * @throws RuntimeException on too many iterations
+ * @see CronExpression::getNextRunDate
+ */
+ public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
+ {
+ return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate);
+ }
+
+ /**
+ * Get multiple run dates starting at the current date or a specific date
+ *
+ * @param int $total Set the total number of dates to calculate
+ * @param string|DateTime $currentTime (optional) Relative calculation date
+ * @param bool $invert (optional) Set to TRUE to retrieve previous dates
+ * @param bool $allowCurrentDate (optional) Set to TRUE to return the
+ * current date if it matches the cron expression
+ *
+ * @return array Returns an array of run dates
+ */
+ public function getMultipleRunDates($total, $currentTime = 'now', $invert = false, $allowCurrentDate = false)
+ {
+ $matches = array();
+ for ($i = 0; $i < max(0, $total); $i++) {
+ $matches[] = $this->getRunDate($currentTime, $i, $invert, $allowCurrentDate);
+ }
+
+ return $matches;
+ }
+
+ /**
+ * Get all or part of the CRON expression
+ *
+ * @param string $part (optional) Specify the part to retrieve or NULL to
+ * get the full cron schedule string.
+ *
+ * @return string|null Returns the CRON expression, a part of the
+ * CRON expression, or NULL if the part was specified but not found
+ */
+ public function getExpression($part = null)
+ {
+ if (null === $part) {
+ return implode(' ', $this->cronParts);
+ } elseif (array_key_exists($part, $this->cronParts)) {
+ return $this->cronParts[$part];
+ }
+
+ return null;
+ }
+
+ /**
+ * Helper method to output the full expression.
+ *
+ * @return string Full CRON expression
+ */
+ public function __toString()
+ {
+ return $this->getExpression();
+ }
+
+ /**
+ * Determine if the cron is due to run based on the current date or a
+ * specific date. This method assumes that the current number of
+ * seconds are irrelevant, and should be called once per minute.
+ *
+ * @param string|DateTime $currentTime (optional) Relative calculation date
+ *
+ * @return bool Returns TRUE if the cron is due to run or FALSE if not
+ */
+ public function isDue($currentTime = 'now')
+ {
+ if ('now' === $currentTime) {
+ $currentDate = date('Y-m-d H:i');
+ $currentTime = strtotime($currentDate);
+ } elseif ($currentTime instanceof DateTime) {
+ $currentDate = $currentTime->format('Y-m-d H:i');
+ $currentTime = strtotime($currentDate);
+ } else {
+ $currentTime = new DateTime($currentTime);
+ $currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0);
+ $currentDate = $currentTime->format('Y-m-d H:i');
+ $currentTime = (int)($currentTime->getTimestamp());
+ }
+
+ return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime;
+ }
+
+ /**
+ * Get the next or previous run date of the expression relative to a date
+ *
+ * @param string|DateTime $currentTime (optional) Relative calculation date
+ * @param int $nth (optional) Number of matches to skip before returning
+ * @param bool $invert (optional) Set to TRUE to go backwards in time
+ * @param bool $allowCurrentDate (optional) Set to TRUE to return the
+ * current date if it matches the cron expression
+ *
+ * @return DateTime
+ * @throws RuntimeException on too many iterations
+ */
+ protected function getRunDate($currentTime = null, $nth = 0, $invert = false, $allowCurrentDate = false)
+ {
+ if ($currentTime instanceof DateTime) {
+ $currentDate = $currentTime;
+ } else {
+ $currentDate = new DateTime($currentTime ? $currentTime : 'now');
+ $currentDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
+ }
+
+ $currentDate->setTime($currentDate->format('H'), $currentDate->format('i'), 0);
+ $nextRun = clone $currentDate;
+ $nth = (int) $nth;
+
+ // Set a hard limit to bail on an impossible date
+ for ($i = 0; $i < 1000; $i++) {
+
+ foreach (self::$order as $position) {
+ $part = $this->getExpression($position);
+ if (null === $part) {
+ continue;
+ }
+
+ $satisfied = false;
+ // Get the field object used to validate this part
+ $field = $this->fieldFactory->getField($position);
+ // Check if this is singular or a list
+ if (strpos($part, ',') === false) {
+ $satisfied = $field->isSatisfiedBy($nextRun, $part);
+ } else {
+ foreach (array_map('trim', explode(',', $part)) as $listPart) {
+ if ($field->isSatisfiedBy($nextRun, $listPart)) {
+ $satisfied = true;
+ break;
+ }
+ }
+ }
+
+ // If the field is not satisfied, then start over
+ if (!$satisfied) {
+ $field->increment($nextRun, $invert);
+ continue 2;
+ }
+ }
+
+ // Skip this match if needed
+ if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) {
+ $this->fieldFactory->getField(0)->increment($nextRun, $invert);
+ continue;
+ }
+
+ return $nextRun;
+ }
+
+ // @codeCoverageIgnoreStart
+ throw new RuntimeException('Impossible CRON expression');
+ // @codeCoverageIgnoreEnd
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_AbstractField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_AbstractField.php
new file mode 100644
index 0000000..f8d5c00
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_AbstractField.php
@@ -0,0 +1,100 @@
+
+ */
+abstract class CronExpression_AbstractField implements CronExpression_FieldInterface
+{
+ /**
+ * Check to see if a field is satisfied by a value
+ *
+ * @param string $dateValue Date value to check
+ * @param string $value Value to test
+ *
+ * @return bool
+ */
+ public function isSatisfied($dateValue, $value)
+ {
+ if ($this->isIncrementsOfRanges($value)) {
+ return $this->isInIncrementsOfRanges($dateValue, $value);
+ } elseif ($this->isRange($value)) {
+ return $this->isInRange($dateValue, $value);
+ }
+
+ return $value == '*' || $dateValue == $value;
+ }
+
+ /**
+ * Check if a value is a range
+ *
+ * @param string $value Value to test
+ *
+ * @return bool
+ */
+ public function isRange($value)
+ {
+ return strpos($value, '-') !== false;
+ }
+
+ /**
+ * Check if a value is an increments of ranges
+ *
+ * @param string $value Value to test
+ *
+ * @return bool
+ */
+ public function isIncrementsOfRanges($value)
+ {
+ return strpos($value, '/') !== false;
+ }
+
+ /**
+ * Test if a value is within a range
+ *
+ * @param string $dateValue Set date value
+ * @param string $value Value to test
+ *
+ * @return bool
+ */
+ public function isInRange($dateValue, $value)
+ {
+ $parts = array_map('trim', explode('-', $value, 2));
+
+ return $dateValue >= $parts[0] && $dateValue <= $parts[1];
+ }
+
+ /**
+ * Test if a value is within an increments of ranges (offset[-to]/step size)
+ *
+ * @param string $dateValue Set date value
+ * @param string $value Value to test
+ *
+ * @return bool
+ */
+ public function isInIncrementsOfRanges($dateValue, $value)
+ {
+ $parts = array_map('trim', explode('/', $value, 2));
+ $stepSize = isset($parts[1]) ? $parts[1] : 0;
+ if ($parts[0] == '*' || $parts[0] === '0') {
+ return (int) $dateValue % $stepSize == 0;
+ }
+
+ $range = explode('-', $parts[0], 2);
+ $offset = $range[0];
+ $to = isset($range[1]) ? $range[1] : $dateValue;
+ // Ensure that the date value is within the range
+ if ($dateValue < $offset || $dateValue > $to) {
+ return false;
+ }
+
+ for ($i = $offset; $i <= $to; $i+= $stepSize) {
+ if ($i == $dateValue) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_DayOfMonthField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_DayOfMonthField.php
new file mode 100644
index 0000000..40c1d6c
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_DayOfMonthField.php
@@ -0,0 +1,110 @@
+
+ */
+class CronExpression_DayOfMonthField extends CronExpression_AbstractField
+{
+ /**
+ * Get the nearest day of the week for a given day in a month
+ *
+ * @param int $currentYear Current year
+ * @param int $currentMonth Current month
+ * @param int $targetDay Target day of the month
+ *
+ * @return DateTime Returns the nearest date
+ */
+ private static function getNearestWeekday($currentYear, $currentMonth, $targetDay)
+ {
+ $tday = str_pad($targetDay, 2, '0', STR_PAD_LEFT);
+ $target = new DateTime("$currentYear-$currentMonth-$tday");
+ $currentWeekday = (int) $target->format('N');
+
+ if ($currentWeekday < 6) {
+ return $target;
+ }
+
+ $lastDayOfMonth = $target->format('t');
+
+ foreach (array(-1, 1, -2, 2) as $i) {
+ $adjusted = $targetDay + $i;
+ if ($adjusted > 0 && $adjusted <= $lastDayOfMonth) {
+ $target->setDate($currentYear, $currentMonth, $adjusted);
+ if ($target->format('N') < 6 && $target->format('m') == $currentMonth) {
+ return $target;
+ }
+ }
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function isSatisfiedBy(DateTime $date, $value)
+ {
+ // ? states that the field value is to be skipped
+ if ($value == '?') {
+ return true;
+ }
+
+ $fieldValue = $date->format('d');
+
+ // Check to see if this is the last day of the month
+ if ($value == 'L') {
+ return $fieldValue == $date->format('t');
+ }
+
+ // Check to see if this is the nearest weekday to a particular value
+ if (strpos($value, 'W')) {
+ // Parse the target day
+ $targetDay = substr($value, 0, strpos($value, 'W'));
+ // Find out if the current day is the nearest day of the week
+ return $date->format('j') == self::getNearestWeekday(
+ $date->format('Y'),
+ $date->format('m'),
+ $targetDay
+ )->format('j');
+ }
+
+ return $this->isSatisfied($date->format('d'), $value);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function increment(DateTime $date, $invert = false)
+ {
+ if ($invert) {
+ $date->modify('previous day');
+ $date->setTime(23, 59);
+ } else {
+ $date->modify('next day');
+ $date->setTime(0, 0);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value)
+ {
+ return (bool) preg_match('/[\*,\/\-\?LW0-9A-Za-z]+/', $value);
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_DayOfWeekField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_DayOfWeekField.php
new file mode 100644
index 0000000..e9f68a7
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_DayOfWeekField.php
@@ -0,0 +1,124 @@
+
+ */
+class CronExpression_DayOfWeekField extends CronExpression_AbstractField
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function isSatisfiedBy(DateTime $date, $value)
+ {
+ if ($value == '?') {
+ return true;
+ }
+
+ // Convert text day of the week values to integers
+ $value = str_ireplace(
+ array('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'),
+ range(0, 6),
+ $value
+ );
+
+ $currentYear = $date->format('Y');
+ $currentMonth = $date->format('m');
+ $lastDayOfMonth = $date->format('t');
+
+ // Find out if this is the last specific weekday of the month
+ if (strpos($value, 'L')) {
+ $weekday = str_replace('7', '0', substr($value, 0, strpos($value, 'L')));
+ $tdate = clone $date;
+ $tdate->setDate($currentYear, $currentMonth, $lastDayOfMonth);
+ while ($tdate->format('w') != $weekday) {
+ $tdate->setDate($currentYear, $currentMonth, --$lastDayOfMonth);
+ }
+
+ return $date->format('j') == $lastDayOfMonth;
+ }
+
+ // Handle # hash tokens
+ if (strpos($value, '#')) {
+ list($weekday, $nth) = explode('#', $value);
+ // Validate the hash fields
+ if ($weekday < 1 || $weekday > 5) {
+ throw new InvalidArgumentException("Weekday must be a value between 1 and 5. {$weekday} given");
+ }
+ if ($nth > 5) {
+ throw new InvalidArgumentException('There are never more than 5 of a given weekday in a month');
+ }
+ // The current weekday must match the targeted weekday to proceed
+ if ($date->format('N') != $weekday) {
+ return false;
+ }
+
+ $tdate = clone $date;
+ $tdate->setDate($currentYear, $currentMonth, 1);
+ $dayCount = 0;
+ $currentDay = 1;
+ while ($currentDay < $lastDayOfMonth + 1) {
+ if ($tdate->format('N') == $weekday) {
+ if (++$dayCount >= $nth) {
+ break;
+ }
+ }
+ $tdate->setDate($currentYear, $currentMonth, ++$currentDay);
+ }
+
+ return $date->format('j') == $currentDay;
+ }
+
+ // Handle day of the week values
+ if (strpos($value, '-')) {
+ $parts = explode('-', $value);
+ if ($parts[0] == '7') {
+ $parts[0] = '0';
+ } elseif ($parts[1] == '0') {
+ $parts[1] = '7';
+ }
+ $value = implode('-', $parts);
+ }
+
+ // Test to see which Sunday to use -- 0 == 7 == Sunday
+ $format = in_array(7, str_split($value)) ? 'N' : 'w';
+ $fieldValue = $date->format($format);
+
+ return $this->isSatisfied($fieldValue, $value);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function increment(DateTime $date, $invert = false)
+ {
+ if ($invert) {
+ $date->modify('-1 day');
+ $date->setTime(23, 59, 0);
+ } else {
+ $date->modify('+1 day');
+ $date->setTime(0, 0, 0);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value)
+ {
+ return (bool) preg_match('/[\*,\/\-0-9A-Z]+/', $value);
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_FieldFactory.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_FieldFactory.php
new file mode 100644
index 0000000..556ba1a
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_FieldFactory.php
@@ -0,0 +1,55 @@
+
+ * @link http://en.wikipedia.org/wiki/Cron
+ */
+class CronExpression_FieldFactory
+{
+ /**
+ * @var array Cache of instantiated fields
+ */
+ private $fields = array();
+
+ /**
+ * Get an instance of a field object for a cron expression position
+ *
+ * @param int $position CRON expression position value to retrieve
+ *
+ * @return CronExpression_FieldInterface
+ * @throws InvalidArgumentException if a position is not valid
+ */
+ public function getField($position)
+ {
+ if (!isset($this->fields[$position])) {
+ switch ($position) {
+ case 0:
+ $this->fields[$position] = new CronExpression_MinutesField();
+ break;
+ case 1:
+ $this->fields[$position] = new CronExpression_HoursField();
+ break;
+ case 2:
+ $this->fields[$position] = new CronExpression_DayOfMonthField();
+ break;
+ case 3:
+ $this->fields[$position] = new CronExpression_MonthField();
+ break;
+ case 4:
+ $this->fields[$position] = new CronExpression_DayOfWeekField();
+ break;
+ case 5:
+ $this->fields[$position] = new CronExpression_YearField();
+ break;
+ default:
+ throw new InvalidArgumentException(
+ $position . ' is not a valid position'
+ );
+ }
+ }
+
+ return $this->fields[$position];
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_FieldInterface.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_FieldInterface.php
new file mode 100644
index 0000000..5d5109b
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_FieldInterface.php
@@ -0,0 +1,39 @@
+
+ */
+interface CronExpression_FieldInterface
+{
+ /**
+ * Check if the respective value of a DateTime field satisfies a CRON exp
+ *
+ * @param DateTime $date DateTime object to check
+ * @param string $value CRON expression to test against
+ *
+ * @return bool Returns TRUE if satisfied, FALSE otherwise
+ */
+ public function isSatisfiedBy(DateTime $date, $value);
+
+ /**
+ * When a CRON expression is not satisfied, this method is used to increment
+ * or decrement a DateTime object by the unit of the cron field
+ *
+ * @param DateTime $date DateTime object to change
+ * @param bool $invert (optional) Set to TRUE to decrement
+ *
+ * @return CronExpression_FieldInterface
+ */
+ public function increment(DateTime $date, $invert = false);
+
+ /**
+ * Validates a CRON expression for a given field
+ *
+ * @param string $value CRON expression value to validate
+ *
+ * @return bool Returns TRUE if valid, FALSE otherwise
+ */
+ public function validate($value);
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_HoursField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_HoursField.php
new file mode 100644
index 0000000..088ca73
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_HoursField.php
@@ -0,0 +1,47 @@
+
+ */
+class CronExpression_HoursField extends CronExpression_AbstractField
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function isSatisfiedBy(DateTime $date, $value)
+ {
+ return $this->isSatisfied($date->format('H'), $value);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function increment(DateTime $date, $invert = false)
+ {
+ // Change timezone to UTC temporarily. This will
+ // allow us to go back or forwards and hour even
+ // if DST will be changed between the hours.
+ $timezone = $date->getTimezone();
+ $date->setTimezone(new DateTimeZone('UTC'));
+ if ($invert) {
+ $date->modify('-1 hour');
+ $date->setTime($date->format('H'), 59);
+ } else {
+ $date->modify('+1 hour');
+ $date->setTime($date->format('H'), 0);
+ }
+ $date->setTimezone($timezone);
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value)
+ {
+ return (bool) preg_match('/[\*,\/\-0-9]+/', $value);
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_MinutesField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_MinutesField.php
new file mode 100644
index 0000000..436acf2
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_MinutesField.php
@@ -0,0 +1,39 @@
+
+ */
+class CronExpression_MinutesField extends CronExpression_AbstractField
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function isSatisfiedBy(DateTime $date, $value)
+ {
+ return $this->isSatisfied($date->format('i'), $value);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function increment(DateTime $date, $invert = false)
+ {
+ if ($invert) {
+ $date->modify('-1 minute');
+ } else {
+ $date->modify('+1 minute');
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value)
+ {
+ return (bool) preg_match('/[\*,\/\-0-9]+/', $value);
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_MonthField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_MonthField.php
new file mode 100644
index 0000000..d3deb12
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_MonthField.php
@@ -0,0 +1,55 @@
+
+ */
+class CronExpression_MonthField extends CronExpression_AbstractField
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function isSatisfiedBy(DateTime $date, $value)
+ {
+ // Convert text month values to integers
+ $value = str_ireplace(
+ array(
+ 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
+ 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
+ ),
+ range(1, 12),
+ $value
+ );
+
+ return $this->isSatisfied($date->format('m'), $value);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function increment(DateTime $date, $invert = false)
+ {
+ if ($invert) {
+ // $date->modify('last day of previous month'); // remove for php 5.2 compat
+ $date->modify('previous month');
+ $date->modify($date->format('Y-m-t'));
+ $date->setTime(23, 59);
+ } else {
+ //$date->modify('first day of next month'); // remove for php 5.2 compat
+ $date->modify('next month');
+ $date->modify($date->format('Y-m-01'));
+ $date->setTime(0, 0);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value)
+ {
+ return (bool) preg_match('/[\*,\/\-0-9A-Z]+/', $value);
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_YearField.php b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_YearField.php
new file mode 100644
index 0000000..f11562e
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/lib/cron-expression/CronExpression_YearField.php
@@ -0,0 +1,43 @@
+
+ */
+class CronExpression_YearField extends CronExpression_AbstractField
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function isSatisfiedBy(DateTime $date, $value)
+ {
+ return $this->isSatisfied($date->format('Y'), $value);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function increment(DateTime $date, $invert = false)
+ {
+ if ($invert) {
+ $date->modify('-1 year');
+ $date->setDate($date->format('Y'), 12, 31);
+ $date->setTime(23, 59, 0);
+ } else {
+ $date->modify('+1 year');
+ $date->setDate($date->format('Y'), 1, 1);
+ $date->setTime(0, 0, 0);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value)
+ {
+ return (bool) preg_match('/[\*,\/\-0-9]+/', $value);
+ }
+}
diff --git a/inc/Dependencies/ActionScheduler/license.txt b/inc/Dependencies/ActionScheduler/license.txt
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/license.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/inc/Dependencies/ActionScheduler/readme.txt b/inc/Dependencies/ActionScheduler/readme.txt
new file mode 100644
index 0000000..3518b15
--- /dev/null
+++ b/inc/Dependencies/ActionScheduler/readme.txt
@@ -0,0 +1,125 @@
+=== Action Scheduler ===
+Contributors: Automattic, wpmuguru, claudiosanches, peterfabian1000, vedjain, jamosova, obliviousharmony, konamiman, sadowski, royho, barryhughes-1
+Tags: scheduler, cron
+Requires at least: 5.2
+Tested up to: 6.0
+Stable tag: 3.5.4
+License: GPLv3
+Requires PHP: 5.6
+
+Action Scheduler - Job Queue for WordPress
+
+== Description ==
+
+Action Scheduler is a scalable, traceable job queue for background processing large sets of actions in WordPress. It's specially designed to be distributed in WordPress plugins.
+
+Action Scheduler works by triggering an action hook to run at some time in the future. Each hook can be scheduled with unique data, to allow callbacks to perform operations on that data. The hook can also be scheduled to run on one or more occassions.
+
+Think of it like an extension to `do_action()` which adds the ability to delay and repeat a hook.
+
+## Battle-Tested Background Processing
+
+Every month, Action Scheduler processes millions of payments for [Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/), webhooks for [WooCommerce](https://wordpress.org/plugins/woocommerce/), as well as emails and other events for a range of other plugins.
+
+It's been seen on live sites processing queues in excess of 50,000 jobs and doing resource intensive operations, like processing payments and creating orders, at a sustained rate of over 10,000 / hour without negatively impacting normal site operations.
+
+This is all on infrastructure and WordPress sites outside the control of the plugin author.
+
+If your plugin needs background processing, especially of large sets of tasks, Action Scheduler can help.
+
+## Learn More
+
+To learn more about how to Action Scheduler works, and how to use it in your plugin, check out the docs on [ActionScheduler.org](https://actionscheduler.org).
+
+There you will find:
+
+* [Usage guide](https://actionscheduler.org/usage/): instructions on installing and using Action Scheduler
+* [WP CLI guide](https://actionscheduler.org/wp-cli/): instructions on running Action Scheduler at scale via WP CLI
+* [API Reference](https://actionscheduler.org/api/): complete reference guide for all API functions
+* [Administration Guide](https://actionscheduler.org/admin/): guide to managing scheduled actions via the administration screen
+* [Guide to Background Processing at Scale](https://actionscheduler.org/perf/): instructions for running Action Scheduler at scale via the default WP Cron queue runner
+
+## Credits
+
+Action Scheduler is developed and maintained by [Automattic](http://automattic.com/) with significant early development completed by [Flightless](https://flightless.us/).
+
+Collaboration is cool. We'd love to work with you to improve Action Scheduler. [Pull Requests](https://github.com/woocommerce/action-scheduler/pulls) welcome.
+
+== Changelog ==
+
+= 3.5.4 - 2023-01-17 =
+* Add pre filters during action registration.
+* Async scheduling.
+* Calculate timeouts based on total actions.
+* Correctly order the parameters for `ActionScheduler_ActionFactory`'s calls to `single_unique`.
+* Fetch action in memory first before releasing claim to avoid deadlock.
+* PHP 8.2: declare property to fix creation of dynamic property warning.
+* PHP 8.2: fix "Using ${var} in strings is deprecated, use {$var} instead".
+* Prevent `undefined variable` warning for `$num_pastdue_actions`.
+
+= 3.5.3 - 2022-11-09 =
+* Query actions with partial match.
+
+= 3.5.2 - 2022-09-16 =
+* Fix - erroneous 3.5.1 release.
+
+= 3.5.1 - 2022-09-13 =
+* Maintenance on A/S docs.
+* fix: PHP 8.2 deprecated notice.
+
+= 3.5.0 - 2022-08-25 =
+* Add - The active view link within the "Tools > Scheduled Actions" screen is now clickable.
+* Add - A warning when there are past-due actions.
+* Enhancement - Added the ability to schedule unique actions via an atomic operation.
+* Enhancement - Improvements to cache invalidation when processing batches (when running on WordPress 6.0+).
+* Enhancement - If a recurring action is found to be consistently failing, it will stop being rescheduled.
+* Enhancement - Adds a new "Past Due" view to the scheduled actions list table.
+
+= 3.4.2 - 2022-06-08 =
+* Fix - Change the include for better linting.
+* Fix - update: Added Action scheduler completed action hook.
+
+= 3.4.1 - 2022-05-24 =
+* Fix - Change the include for better linting.
+* Fix - Fix the documented return type.
+
+= 3.4.0 - 2021-10-29 =
+* Enhancement - Number of items per page can now be set for the Scheduled Actions view (props @ovidiul). #771
+* Fix - Do not lower the max_execution_time if it is already set to 0 (unlimited) (props @barryhughes). #755
+* Fix - Avoid triggering autoloaders during the version resolution process (props @olegabr). #731 & #776
+* Dev - ActionScheduler_wcSystemStatus PHPCS fixes (props @ovidiul). #761
+* Dev - ActionScheduler_DBLogger.php PHPCS fixes (props @ovidiul). #768
+* Dev - Fixed phpcs for ActionScheduler_Schedule_Deprecated (props @ovidiul). #762
+* Dev - Improve actions table indicies (props @glagonikas). #774 & #777
+* Dev - PHPCS fixes for ActionScheduler_DBStore.php (props @ovidiul). #769 & #778
+* Dev - PHPCS Fixes for ActionScheduler_Abstract_ListTable (props @ovidiul). #763 & #779
+* Dev - Adds new filter action_scheduler_claim_actions_order_by to allow tuning of the claim query (props @glagonikas). #773
+* Dev - PHPCS fixes for ActionScheduler_WpPostStore class (props @ovidiul). #780
+
+= 3.3.0 - 2021-09-15 =
+* Enhancement - Adds as_has_scheduled_action() to provide a performant way to test for existing actions. #645
+* Fix - Improves compatibility with environments where NO_ZERO_DATE is enabled. #519
+* Fix - Adds safety checks to guard against errors when our database tables cannot be created. #645
+* Dev - Now supports queries that use multiple statuses. #649
+* Dev - Minimum requirements for WordPress and PHP bumped (to 5.2 and 5.6 respectively). #723
+
+= 3.2.1 - 2021-06-21 =
+* Fix - Add extra safety/account for different versions of AS and different loading patterns. #714
+* Fix - Handle hidden columns (Tools → Scheduled Actions) | #600.
+
+= 3.2.0 - 2021-06-03 =
+* Fix - Add "no ordering" option to as_next_scheduled_action().
+* Fix - Add secondary scheduled date checks when claiming actions (DBStore) | #634.
+* Fix - Add secondary scheduled date checks when claiming actions (wpPostStore) | #634.
+* Fix - Adds a new index to the action table, reducing the potential for deadlocks (props: @glagonikas).
+* Fix - Fix unit tests infrastructure and adapt tests to PHP 8.
+* Fix - Identify in-use data store.
+* Fix - Improve test_migration_is_scheduled.
+* Fix - PHP notice on list table.
+* Fix - Speed up clean up and batch selects.
+* Fix - Update pending dependencies.
+* Fix - [PHP 8.0] Only pass action arg values through to do_action_ref_array().
+* Fix - [PHP 8] Set the PHP version to 7.1 in composer.json for PHP 8 compatibility.
+* Fix - add is_initialized() to docs.
+* Fix - fix file permissions.
+* Fix - fixes #664 by replacing __ with esc_html__.
diff --git a/inc/Dependencies/Database/Base.php b/inc/Dependencies/Database/Base.php
new file mode 100644
index 0000000..20fcdb5
--- /dev/null
+++ b/inc/Dependencies/Database/Base.php
@@ -0,0 +1,344 @@
+{$key};
+ }
+
+ // Return null if not exists
+ return null;
+ }
+
+ /**
+ * Converts the given object to an array.
+ *
+ * @since 1.0.0
+ *
+ * @return array Array version of the given object.
+ */
+ public function to_array() {
+ return get_object_vars( $this );
+ }
+
+ /** Protected *************************************************************/
+
+ /**
+ * Maybe append the prefix to string.
+ *
+ * @since 1.0.0
+ *
+ * @param string $string
+ * @param string $sep
+ * @return string
+ */
+ protected function apply_prefix( $string = '', $sep = '_' ) {
+ return ! empty( $this->prefix )
+ ? "{$this->prefix}{$sep}{$string}"
+ : $string;
+ }
+
+ /**
+ * Return the first letters of a string of words with a separator.
+ *
+ * Used primarily to guess at table aliases when none is manually set.
+ *
+ * Applies the following formatting to a string:
+ * - Trim whitespace
+ * - No accents
+ * - No trailing underscores
+ *
+ * @since 1.0.0
+ *
+ * @param string $string
+ * @param string $sep
+ * @return string
+ */
+ protected function first_letters( $string = '', $sep = '_' ) {
+
+ // Set empty default return value
+ $retval = '';
+
+ // Bail if empty or not a string
+ if ( empty( $string ) || ! is_string( $string ) ) {
+ return $retval;
+ }
+
+ // Trim spaces off the ends
+ $unspace = trim( $string );
+
+ // Only non-accented table names (avoid truncation)
+ $accents = remove_accents( $unspace );
+
+ // Only lowercase letters are allowed
+ $lower = strtolower( $accents );
+
+ // Explode into parts
+ $parts = explode( $sep, $lower );
+
+ // Loop through parts and concatenate the first letters together
+ foreach ( $parts as $part ) {
+ $retval .= substr( $part, 0, 1 );
+ }
+
+ // Return the result
+ return $retval;
+ }
+
+ /**
+ * Sanitize a table name string.
+ *
+ * Used to make sure that a table name value meets MySQL expectations.
+ *
+ * Applies the following formatting to a string:
+ * - Trim whitespace
+ * - No accents
+ * - No special characters
+ * - No hyphens
+ * - No double underscores
+ * - No trailing underscores
+ *
+ * @since 1.0.0
+ *
+ * @param string $name The name of the database table
+ *
+ * @return string Sanitized database table name
+ */
+ protected function sanitize_table_name( $name = '' ) {
+
+ // Bail if empty or not a string
+ if ( empty( $name ) || ! is_string( $name ) ) {
+ return false;
+ }
+
+ // Trim spaces off the ends
+ $unspace = trim( $name );
+
+ // Only non-accented table names (avoid truncation)
+ $accents = remove_accents( $unspace );
+
+ // Only lowercase characters, hyphens, and dashes (avoid index corruption)
+ $lower = sanitize_key( $accents );
+
+ // Replace hyphens with single underscores
+ $under = str_replace( '-', '_', $lower );
+
+ // Single underscores only
+ $single = str_replace( '__', '_', $under );
+
+ // Remove trailing underscores
+ $clean = trim( $single, '_' );
+
+ // Bail if table name was garbaged
+ if ( empty( $clean ) ) {
+ return false;
+ }
+
+ // Return the cleaned table name
+ return $clean;
+ }
+
+ /**
+ * Set class variables from arguments.
+ *
+ * @since 1.0.0
+ * @param array $args
+ */
+ protected function set_vars( $args = array() ) {
+
+ // Bail if empty or not an array
+ if ( empty( $args ) ) {
+ return;
+ }
+
+ // Cast to an array
+ if ( ! is_array( $args ) ) {
+ $args = (array) $args;
+ }
+
+ // Set all properties
+ foreach ( $args as $key => $value ) {
+ $this->{$key} = $value;
+ }
+ }
+
+ /**
+ * Return the global database interface.
+ *
+ * See: https://core.trac.wordpress.org/ticket/31556
+ *
+ * @since 1.0.0
+ *
+ * @return \wpdb Database interface, or False if not set
+ */
+ protected function get_db() {
+
+ // Default database return value (might change)
+ $retval = false;
+
+ // Look for a commonly used global database interface
+ if ( isset( $GLOBALS[ $this->db_global ] ) ) {
+ $retval = $GLOBALS[ $this->db_global ];
+ }
+
+ /*
+ * Developer note:
+ *
+ * It should be impossible for a database table to be interacted with
+ * before the primary database interface is setup.
+ *
+ * However, because applications are complicated, it is unsafe to assume
+ * anything, so this silently returns false instead of halting everything.
+ *
+ * If you are here because this method is returning false for you, that
+ * means the database table is being invoked too early in the lifecycle
+ * of the application.
+ *
+ * In WordPress, that means before the $wpdb global is created; in other
+ * environments, you will need to adjust accordingly.
+ */
+
+ // Return the database interface
+ return $retval;
+ }
+
+ /**
+ * Check if an operation succeeded.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $result
+ * @return bool
+ */
+ protected function is_success( $result = false ) {
+
+ // Bail if no row exists
+ if ( empty( $result ) ) {
+ $retval = false;
+
+ // Bail if an error occurred
+ } elseif ( is_wp_error( $result ) ) {
+ $this->last_error = $result;
+ $retval = false;
+
+ // No errors
+ } else {
+ $retval = true;
+ }
+
+ // Return the result
+ return (bool) $retval;
+ }
+}
diff --git a/inc/Dependencies/Database/Column.php b/inc/Dependencies/Database/Column.php
new file mode 100644
index 0000000..97cedaa
--- /dev/null
+++ b/inc/Dependencies/Database/Column.php
@@ -0,0 +1,965 @@
+parse_args( $args );
+
+ // Maybe set variables from arguments
+ if ( ! empty( $r ) ) {
+ $this->set_vars( $r );
+ }
+ }
+
+ /** Argument Handlers *****************************************************/
+
+ /**
+ * Parse column arguments
+ *
+ * @since 1.0.0
+ * @param array $args Default empty array.
+ * @return array
+ */
+ private function parse_args( $args = array() ) {
+
+ // Parse arguments
+ $r = wp_parse_args( $args, array(
+
+ // Table
+ 'name' => '',
+ 'type' => '',
+ 'length' => '',
+ 'unsigned' => false,
+ 'zerofill' => false,
+ 'binary' => false,
+ 'allow_null' => false,
+ 'default' => '',
+ 'extra' => '',
+ 'encoding' => $this->get_db()->charset,
+ 'collation' => $this->get_db()->collate,
+ 'comment' => '',
+
+ // Query
+ 'pattern' => false,
+ 'searchable' => false,
+ 'sortable' => false,
+ 'date_query' => false,
+ 'transition' => false,
+ 'in' => true,
+ 'not_in' => true,
+
+ // Special
+ 'primary' => false,
+ 'created' => false,
+ 'modified' => false,
+ 'uuid' => false,
+
+ // Cache
+ 'cache_key' => false,
+
+ // Validation
+ 'validate' => '',
+
+ // Capabilities
+ 'caps' => array(),
+
+ // Backwards Compatibility
+ 'aliases' => array(),
+
+ // Column Relationships
+ 'relationships' => array()
+ ) );
+
+ // Force some arguments for special column types
+ $r = $this->special_args( $r );
+
+ // Set the args before they are sanitized
+ $this->set_vars( $r );
+
+ // Return array
+ return $this->validate_args( $r );
+ }
+
+ /**
+ * Validate arguments after they are parsed.
+ *
+ * @since 1.0.0
+ * @param array $args Default empty array.
+ * @return array
+ */
+ private function validate_args( $args = array() ) {
+
+ // Sanitization callbacks
+ $callbacks = array(
+ 'name' => 'sanitize_key',
+ 'type' => 'strtoupper',
+ 'length' => 'intval',
+ 'unsigned' => 'wp_validate_boolean',
+ 'zerofill' => 'wp_validate_boolean',
+ 'binary' => 'wp_validate_boolean',
+ 'allow_null' => 'wp_validate_boolean',
+ 'default' => array( $this, 'sanitize_default' ),
+ 'extra' => 'wp_kses_data',
+ 'encoding' => 'wp_kses_data',
+ 'collation' => 'wp_kses_data',
+ 'comment' => 'wp_kses_data',
+
+ 'primary' => 'wp_validate_boolean',
+ 'created' => 'wp_validate_boolean',
+ 'modified' => 'wp_validate_boolean',
+ 'uuid' => 'wp_validate_boolean',
+
+ 'searchable' => 'wp_validate_boolean',
+ 'sortable' => 'wp_validate_boolean',
+ 'date_query' => 'wp_validate_boolean',
+ 'transition' => 'wp_validate_boolean',
+ 'in' => 'wp_validate_boolean',
+ 'not_in' => 'wp_validate_boolean',
+ 'cache_key' => 'wp_validate_boolean',
+
+ 'pattern' => array( $this, 'sanitize_pattern' ),
+ 'validate' => array( $this, 'sanitize_validation' ),
+ 'caps' => array( $this, 'sanitize_capabilities' ),
+ 'aliases' => array( $this, 'sanitize_aliases' ),
+ 'relationships' => array( $this, 'sanitize_relationships' )
+ );
+
+ // Default args array
+ $r = array();
+
+ // Loop through and try to execute callbacks
+ foreach ( $args as $key => $value ) {
+
+ // Callback is callable
+ if ( isset( $callbacks[ $key ] ) && is_callable( $callbacks[ $key ] ) ) {
+ $r[ $key ] = call_user_func( $callbacks[ $key ], $value );
+
+ // Callback is malformed so just let it through to avoid breakage
+ } else {
+ $r[ $key ] = $value;
+ }
+ }
+
+ // Return sanitized arguments
+ return $r;
+ }
+
+ /**
+ * Force column arguments for special column types
+ *
+ * @since 1.0.0
+ * @param array $args Default empty array.
+ * @return array
+ */
+ private function special_args( $args = array() ) {
+
+ // Primary key columns are always used as cache keys
+ if ( ! empty( $args['primary'] ) ) {
+ $args['cache_key'] = true;
+
+ // All UUID columns need to follow a very specific pattern
+ } elseif ( ! empty( $args['uuid'] ) ) {
+ $args['name'] = 'uuid';
+ $args['type'] = 'varchar';
+ $args['length'] = '100';
+ $args['in'] = false;
+ $args['not_in'] = false;
+ $args['searchable'] = false;
+ $args['sortable'] = false;
+ }
+
+ // Return args
+ return (array) $args;
+ }
+
+ /** Public Helpers ********************************************************/
+
+ /**
+ * Return if a column type is numeric or not.
+ *
+ * @since 1.0.0
+ * @return bool
+ */
+ public function is_numeric() {
+ return $this->is_type( array(
+ 'tinyint',
+ 'int',
+ 'mediumint',
+ 'bigint'
+ ) );
+ }
+
+ /** Private Helpers *******************************************************/
+
+ /**
+ * Return if this column is of a certain type.
+ *
+ * @since 1.0.0
+ * @param mixed $type Default empty string. The type to check. Also accepts an array.
+ * @return bool True if of type, False if not
+ */
+ private function is_type( $type = '' ) {
+
+ // If string, cast to array
+ if ( is_string( $type ) ) {
+ $type = (array) $type;
+ }
+
+ // Make them lowercase
+ $types = array_map( 'strtolower', $type );
+
+ // Return if match or not
+ return (bool) in_array( strtolower( $this->type ), $types, true );
+ }
+
+ /** Private Sanitizers ****************************************************/
+
+ /**
+ * Sanitize capabilities array
+ *
+ * @since 1.0.0
+ * @param array $caps Default empty array.
+ * @return array
+ */
+ private function sanitize_capabilities( $caps = array() ) {
+ return wp_parse_args( $caps, array(
+ 'select' => 'exist',
+ 'insert' => 'exist',
+ 'update' => 'exist',
+ 'delete' => 'exist'
+ ) );
+ }
+
+ /**
+ * Sanitize aliases array using `sanitize_key()`
+ *
+ * @since 1.0.0
+ * @param array $aliases Default empty array.
+ * @return array
+ */
+ private function sanitize_aliases( $aliases = array() ) {
+ return array_map( 'sanitize_key', $aliases );
+ }
+
+ /**
+ * Sanitize relationships array
+ *
+ * @todo
+ * @since 1.0.0
+ * @param array $relationships Default empty array.
+ * @return array
+ */
+ private function sanitize_relationships( $relationships = array() ) {
+ return array_filter( $relationships );
+ }
+
+ /**
+ * Sanitize the default value
+ *
+ * @since 1.0.0
+ * @param string $default
+ * @return string|null
+ */
+ private function sanitize_default( $default = '' ) {
+
+ // Null
+ if ( ( true === $this->allow_null ) && is_null( $default ) ) {
+ return null;
+
+ // String
+ } elseif ( is_string( $default ) ) {
+ return wp_kses_data( $default );
+
+ // Integer
+ } elseif ( $this->is_numeric() ) {
+ return (int) $default;
+ }
+
+ // @todo datetime, decimal, and other column types
+
+ // Unknown, so return the default's default
+ return '';
+ }
+
+ /**
+ * Sanitize the pattern
+ *
+ * @since 1.0.0
+ * @param string $pattern
+ * @return string
+ */
+ private function sanitize_pattern( $pattern = '%s' ) {
+
+ // Allowed patterns
+ $allowed_patterns = array( '%s', '%d', '%f' );
+
+ // Return pattern if allowed
+ if ( in_array( $pattern, $allowed_patterns, true ) ) {
+ return $pattern;
+ }
+
+ // Fallback to digit or string
+ return $this->is_numeric()
+ ? '%d'
+ : '%s';
+ }
+
+ /**
+ * Sanitize the validation callback
+ *
+ * @since 1.0.0
+ * @param string $callback Default empty string. A callable PHP function name or method
+ * @return string The most appropriate callback function for the value
+ */
+ private function sanitize_validation( $callback = '' ) {
+
+ // Return callback if it's callable
+ if ( is_callable( $callback ) ) {
+ return $callback;
+ }
+
+ // UUID special column
+ if ( true === $this->uuid ) {
+ $callback = array( $this, 'validate_uuid' );
+
+ // Datetime fallback
+ } elseif ( $this->is_type( 'datetime' ) ) {
+ $callback = array( $this, 'validate_datetime' );
+
+ // Decimal fallback
+ } elseif ( $this->is_type( 'decimal' ) ) {
+ $callback = array( $this, 'validate_decimal' );
+
+ // Intval fallback
+ } elseif ( $this->is_numeric() ) {
+ $callback = 'intval';
+ }
+
+ // Return the callback
+ return $callback;
+ }
+
+ /** Public Validators *****************************************************/
+
+ /**
+ * Fallback to validate a datetime value if no other is set.
+ *
+ * This assumes NO_ZERO_DATES is off or overridden.
+ *
+ * If MySQL drops support for zero dates, this method will need to be
+ * updated to support different default values based on the environment.
+ *
+ * @since 1.0.0
+ * @param string $value Default ''. A datetime value that needs validating
+ * @return string A valid datetime value
+ */
+ public function validate_datetime( $value = '' ) {
+
+ // Handle "empty" values
+ if ( empty( $value ) || ( '0000-00-00 00:00:00' === $value ) ) {
+ $value = ! empty( $this->default )
+ ? $this->default
+ : '';
+
+ // Convert to MySQL datetime format via gmdate() && strtotime
+ } elseif ( function_exists( 'gmdate' ) ) {
+ $value = gmdate( 'Y-m-d H:i:s', strtotime( $value ) );
+ }
+
+ // Return the validated value
+ return $value;
+ }
+
+ /**
+ * Validate a decimal
+ *
+ * (Recommended decimal column length is '18,9'.)
+ *
+ * This is used to validate a mixed value before it is saved into a decimal
+ * column in a database table.
+ *
+ * Uses number_format() which does rounding to the last decimal if your
+ * value is longer than specified.
+ *
+ * @since 1.0.0
+ * @param mixed $value Default empty string. The decimal value to validate
+ * @param int $decimals Default 9. The number of decimal points to accept
+ * @return float
+ */
+ public function validate_decimal( $value = 0, $decimals = 9 ) {
+
+ // Protect against non-numeric values
+ if ( ! is_numeric( $value ) ) {
+ $value = 0;
+ }
+
+ // Protect against non-numeric decimals
+ if ( ! is_numeric( $decimals ) ) {
+ $decimals = 9;
+ }
+
+ // Is the value negative?
+ $negative_exponent = ( $value < 0 )
+ ? -1
+ : 1;
+
+ // Only numbers and period
+ $value = preg_replace( '/[^0-9\.]/', '', (string) $value );
+
+ // Format to number of decimals, and cast as float
+ $formatted = number_format( $value, $decimals, '.', '' );
+
+ // Adjust for negative values
+ $retval = $formatted * $negative_exponent;
+
+ // Return
+ return $retval;
+ }
+
+ /**
+ * Validate a UUID.
+ *
+ * This uses the v4 algorithm to generate a UUID that is used to uniquely
+ * and universally identify a given database row without any direct
+ * connection or correlation to the data in that row.
+ *
+ * From http://php.net/manual/en/function.uniqid.php#94959
+ *
+ * @since 1.0.0
+ * @param string $value The UUID value (empty on insert, string on update)
+ * @return string Generated UUID.
+ */
+ public function validate_uuid( $value = '' ) {
+
+ // Default URN UUID prefix
+ $prefix = 'urn:uuid:';
+
+ // Bail if not empty and correctly prefixed
+ // (UUIDs should _never_ change once they are set)
+ if ( ! empty( $value ) && ( 0 === strpos( $value, $prefix ) ) ) {
+ return $value;
+ }
+
+ // Put the pieces together
+ $value = sprintf( "{$prefix}%04x%04x-%04x-%04x-%04x-%04x%04x%04x",
+
+ // 32 bits for "time_low"
+ mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
+
+ // 16 bits for "time_mid"
+ mt_rand( 0, 0xffff ),
+
+ // 16 bits for "time_hi_and_version",
+ // four most significant bits holds version number 4
+ mt_rand( 0, 0x0fff ) | 0x4000,
+
+ // 16 bits, 8 bits for "clk_seq_hi_res",
+ // 8 bits for "clk_seq_low",
+ // two most significant bits holds zero and one for variant DCE1.1
+ mt_rand( 0, 0x3fff ) | 0x8000,
+
+ // 48 bits for "node"
+ mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
+ );
+
+ // Return the new UUID
+ return $value;
+ }
+
+ /** Table Helpers *********************************************************/
+
+ /**
+ * Return a string representation of what this column's properties look like
+ * in a MySQL.
+ *
+ * @todo
+ * @since 1.0.0
+ * @return string
+ */
+ public function get_create_string() {
+
+ // Default return val
+ $retval = '';
+
+ // Bail if no name
+ if ( ! empty( $this->name ) ) {
+ $retval .= $this->name;
+ }
+
+ // Type
+ if ( ! empty( $this->type ) ) {
+ $retval .= " {$this->type}";
+ }
+
+ // Length
+ if ( ! empty( $this->length ) ) {
+ $retval .= '(' . $this->length . ')';
+ }
+
+ // Unsigned
+ if ( ! empty( $this->unsigned ) ) {
+ $retval .= " unsigned";
+ }
+
+ // Zerofill
+ if ( ! empty( $this->zerofill ) ) {
+ // TBD
+ }
+
+ // Binary
+ if ( ! empty( $this->binary ) ) {
+ // TBD
+ }
+
+ // Allow null
+ if ( ! empty( $this->allow_null ) ) {
+ $retval .= " NOT NULL ";
+ }
+
+ // Default
+ if ( ! empty( $this->default ) ) {
+ $retval .= " default '{$this->default}'";
+
+ // A literal false means no default value
+ } elseif ( false !== $this->default ) {
+
+ // Numeric
+ if ( $this->is_numeric() ) {
+ $retval .= " default '0'";
+ } elseif ( $this->is_type( 'datetime' ) ) {
+ $retval .= " default '0000-00-00 00:00:00'";
+ } else {
+ $retval .= " default ''";
+ }
+ }
+
+ // Extra
+ if ( ! empty( $this->extra ) ) {
+ $retval .= " {$this->extra}";
+ }
+
+ // Encoding
+ if ( ! empty( $this->encoding ) ) {
+
+ } else {
+
+ }
+
+ // Collation
+ if ( ! empty( $this->collation ) ) {
+
+ } else {
+
+ }
+
+ // Return the create string
+ return $retval;
+ }
+}
diff --git a/inc/Dependencies/Database/Queries/Compare.php b/inc/Dependencies/Database/Queries/Compare.php
new file mode 100644
index 0000000..4091af0
--- /dev/null
+++ b/inc/Dependencies/Database/Queries/Compare.php
@@ -0,0 +1,180 @@
+',
+ '>=',
+ '<',
+ '<=',
+ 'LIKE',
+ 'NOT LIKE',
+ 'IN',
+ 'NOT IN',
+ 'BETWEEN',
+ 'NOT BETWEEN',
+ 'EXISTS',
+ 'NOT EXISTS',
+ 'REGEXP',
+ 'NOT REGEXP',
+ 'RLIKE',
+ );
+
+ // IN and BETWEEN
+ const IN_BETWEEN_COMPARES = array(
+ 'IN',
+ 'NOT IN',
+ 'BETWEEN',
+ 'NOT BETWEEN'
+ );
+
+ /**
+ * Generate SQL WHERE clauses for a first-order query clause.
+ *
+ * "First-order" means that it's an array with a 'key' or 'value'.
+ *
+ * @since 1.0.0
+ *
+ * @param array $clause Query clause (passed by reference).
+ * @param array $parent_query Parent query array.
+ * @param string $clause_key Optional. The array key used to name the clause in the original `$meta_query`
+ * parameters. If not provided, a key will be generated automatically.
+ * @return array {
+ * Array containing WHERE SQL clauses to append to a first-order query.
+ *
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
+ global $wpdb;
+
+ // Default chunks
+ $sql_chunks = array(
+ 'where' => array(),
+ 'join' => array(),
+ );
+
+ // Maybe format compare clause
+ if ( isset( $clause['compare'] ) ) {
+ $clause['compare'] = strtoupper( $clause['compare'] );
+
+ // Or set compare clause based on value
+ } else {
+ $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] )
+ ? 'IN'
+ : '=';
+ }
+
+ // Fallback to equals
+ if ( ! in_array( $clause['compare'], self::ALL_COMPARES, true ) ) {
+ $clause['compare'] = '=';
+ }
+
+ // Uppercase or equals
+ if ( isset( $clause['compare_key'] ) && ( 'LIKE' === strtoupper( $clause['compare_key'] ) ) ) {
+ $clause['compare_key'] = strtoupper( $clause['compare_key'] );
+ } else {
+ $clause['compare_key'] = '=';
+ }
+
+ // Get comparison from clause
+ $compare = $clause['compare'];
+
+ /** Build the WHERE clause ********************************************/
+
+ // Column name and value.
+ if ( array_key_exists( 'key', $clause ) && array_key_exists( 'value', $clause ) ) {
+ $column = sanitize_key( $clause['key'] );
+ $value = $clause['value'];
+
+ // IN or BETWEEN
+ if ( in_array( $compare, self::IN_BETWEEN_COMPARES, true ) ) {
+ if ( ! is_array( $value ) ) {
+ $value = preg_split( '/[,\s]+/', $value );
+ }
+
+ // Anything else
+ } else {
+ $value = trim( $value );
+ }
+
+ // Format WHERE from compare value(s)
+ switch ( $compare ) {
+ case 'IN':
+ case 'NOT IN':
+ $compare_string = '(' . substr( str_repeat( ',%s', count( $value ) ), 1 ) . ')';
+ $where = $wpdb->prepare( $compare_string, $value );
+ break;
+
+ case 'BETWEEN':
+ case 'NOT BETWEEN':
+ $value = array_slice( $value, 0, 2 );
+ $where = $wpdb->prepare( '%s AND %s', $value );
+ break;
+
+ case 'LIKE':
+ case 'NOT LIKE':
+ $value = '%' . $wpdb->esc_like( $value ) . '%';
+ $where = $wpdb->prepare( '%s', $value );
+ break;
+
+ // EXISTS with a value is interpreted as '='.
+ case 'EXISTS':
+ $compare = '=';
+ $where = $wpdb->prepare( '%s', $value );
+ break;
+
+ // 'value' is ignored for NOT EXISTS.
+ case 'NOT EXISTS':
+ $where = '';
+ break;
+
+ default:
+ $where = $wpdb->prepare( '%s', $value );
+ break;
+
+ }
+
+ // Maybe add column, compare, & where to chunks
+ if ( ! empty( $where ) ) {
+ $sql_chunks['where'][] = "{$column} {$compare} {$where}";
+ }
+ }
+
+ /*
+ * Multiple WHERE clauses (for meta_key and meta_value) should
+ * be joined in parentheses.
+ */
+ if ( 1 < count( $sql_chunks['where'] ) ) {
+ $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
+ }
+
+ // Return
+ return $sql_chunks;
+ }
+}
\ No newline at end of file
diff --git a/inc/Dependencies/Database/Queries/Date.php b/inc/Dependencies/Database/Queries/Date.php
new file mode 100644
index 0000000..d67223e
--- /dev/null
+++ b/inc/Dependencies/Database/Queries/Date.php
@@ -0,0 +1,1317 @@
+',
+ '>=',
+ '<',
+ '<=',
+ 'IN',
+ 'NOT IN',
+ 'BETWEEN',
+ 'NOT BETWEEN'
+ );
+
+ /**
+ * Supported multi-value comparison types
+ *
+ * @since 1.1.0
+ * @var array
+ */
+ public $multi_value_keys = array(
+ 'IN',
+ 'NOT IN',
+ 'BETWEEN',
+ 'NOT BETWEEN'
+ );
+
+ /**
+ * Supported relation types
+ *
+ * @since 1.1.0
+ * @var array
+ */
+ public $relation_keys = array(
+ 'OR',
+ 'AND'
+ );
+
+ /**
+ * Constructor.
+ *
+ * Time-related parameters that normally require integer values ('year', 'month', 'week', 'dayofyear', 'day',
+ * 'dayofweek', 'dayofweek_iso', 'hour', 'minute', 'second') accept arrays of integers for some values of
+ * 'compare'. When 'compare' is 'IN' or 'NOT IN', arrays are accepted; when 'compare' is 'BETWEEN' or 'NOT
+ * BETWEEN', arrays of two valid values are required. See individual argument descriptions for accepted values.
+ *
+ * @since 1.0.0
+ *
+ * @param array $date_query {
+ * Array of date query clauses.
+ *
+ * @type array ...$0 {
+ * @type string $column Optional. The column to query against. If undefined, inherits the value of
+ * 'date_created'. Accepts 'date_created', 'date_created_gmt',
+ * 'post_modified','post_modified_gmt', 'comment_date', 'comment_date_gmt'.
+ * Default 'date_created'.
+ * @type string $compare Optional. The comparison operator. Accepts '=', '!=', '>', '>=', '<', '<=',
+ * 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default '='.
+ * @type string $relation Optional. The boolean relationship between the date queries. Accepts 'OR' or 'AND'.
+ * Default 'OR'.
+ * @type int|array $start_of_week Optional. Day that week starts on. Accepts numbers 0-6
+ * (0 = Sunday, 1 is Monday). Default 0.
+ * @type array ...$0 {
+ * Optional. An array of first-order clause parameters, or another fully-formed date query.
+ *
+ * @type string|array $before {
+ * Optional. Date to retrieve posts before. Accepts `strtotime()`-compatible string,
+ * or array of 'year', 'month', 'day' values.
+ *
+ * @type string $year The four-digit year. Default empty. Accepts any four-digit year.
+ * @type string $month Optional when passing array.The month of the year.
+ * Default (string:empty)|(array:1). Accepts numbers 1-12.
+ * @type string $day Optional when passing array.The day of the month.
+ * Default (string:empty)|(array:1). Accepts numbers 1-31.
+ * }
+ * @type string|array $after {
+ * Optional. Date to retrieve posts after. Accepts `strtotime()`-compatible string,
+ * or array of 'year', 'month', 'day' values.
+ *
+ * @type string $year The four-digit year. Accepts any four-digit year. Default empty.
+ * @type string $month Optional when passing array. The month of the year. Accepts numbers 1-12.
+ * Default (string:empty)|(array:12).
+ * @type string $day Optional when passing array.The day of the month. Accepts numbers 1-31.
+ * Default (string:empty)|(array:last day of month).
+ * }
+ * @type string $column Optional. Used to add a clause comparing a column other than the
+ * column specified in the top-level `$column` parameter. Accepts
+ * 'date_created', 'date_created_gmt', 'post_modified', 'post_modified_gmt',
+ * 'comment_date', 'comment_date_gmt'. Default is the value of
+ * top-level `$column`.
+ * @type string $compare Optional. The comparison operator. Accepts '=', '!=', '>', '>=',
+ * '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. 'IN',
+ * 'NOT IN', 'BETWEEN', and 'NOT BETWEEN'. Comparisons support
+ * arrays in some time-related parameters. Default '='.
+ * @type int|array $start_of_week Optional. Day that week starts on. Accepts numbers 0-6
+ * (0 = Sunday, 1 is Monday). Default 0.
+ * @type bool $inclusive Optional. Include results from dates specified in 'before' or
+ * 'after'. Default false.
+ * @type int|array $year Optional. The four-digit year number. Accepts any four-digit year
+ * or an array of years if `$compare` supports it. Default empty.
+ * @type int|array $month Optional. The two-digit month number. Accepts numbers 1-12 or an
+ * array of valid numbers if `$compare` supports it. Default empty.
+ * @type int|array $week Optional. The week number of the year. Accepts numbers 0-53 or an
+ * array of valid numbers if `$compare` supports it. Default empty.
+ * @type int|array $dayofyear Optional. The day number of the year. Accepts numbers 1-366 or an
+ * array of valid numbers if `$compare` supports it.
+ * @type int|array $day Optional. The day of the month. Accepts numbers 1-31 or an array
+ * of valid numbers if `$compare` supports it. Default empty.
+ * @type int|array $dayofweek Optional. The day number of the week. Accepts numbers 1-7 (1 is
+ * Sunday) or an array of valid numbers if `$compare` supports it.
+ * Default empty.
+ * @type int|array $dayofweek_iso Optional. The day number of the week (ISO). Accepts numbers 1-7
+ * (1 is Monday) or an array of valid numbers if `$compare` supports it.
+ * Default empty.
+ * @type int|array $hour Optional. The hour of the day. Accepts numbers 0-23 or an array
+ * of valid numbers if `$compare` supports it. Default empty.
+ * @type int|array $minute Optional. The minute of the hour. Accepts numbers 0-60 or an array
+ * of valid numbers if `$compare` supports it. Default empty.
+ * @type int|array $second Optional. The second of the minute. Accepts numbers 0-60 or an
+ * array of valid numbers if `$compare` supports it. Default empty.
+ * }
+ * }
+ * }
+ */
+ public function __construct( $date_query = array() ) {
+
+ // Bail if empty or not an array.
+ if ( empty( $date_query ) || ! is_array( $date_query ) ) {
+ return;
+ }
+
+ // Set now, column, compare, relation, and start_of_week.
+ $this->now = $this->get_now( $date_query );
+ $this->column = $this->get_column( $date_query );
+ $this->compare = $this->get_compare( $date_query );
+ $this->relation = $this->get_relation( $date_query );
+ $this->start_of_week = $this->get_start_of_week( $date_query );
+
+ // Support for passing time-based keys in the top level of the array.
+ if ( ! isset( $date_query[0] ) ) {
+ $date_query = array( $date_query );
+ }
+
+ // Set the queries
+ $this->queries = $this->sanitize_query( $date_query );
+ }
+
+ /**
+ * Recursive-friendly query sanitizer.
+ *
+ * Ensures that each query-level clause has a 'relation' key, and that
+ * each first-order clause contains all the necessary keys from
+ * `$defaults`.
+ *
+ * @since 1.0.0
+ *
+ * @param array $queries
+ * @param array $parent_query
+ *
+ * @return array Sanitized queries.
+ */
+ public function sanitize_query( $queries = array(), $parent_query = array() ) {
+
+ // Default return value.
+ $retval = array();
+
+ // Setup defaults.
+ $defaults = array(
+ 'now' => $this->get_now(),
+ 'column' => $this->get_column(),
+ 'compare' => $this->get_compare(),
+ 'relation' => $this->get_relation(),
+ 'start_of_week' => $this->get_start_of_week()
+ );
+
+ // Numeric keys should always have array values.
+ foreach ( $queries as $qkey => $qvalue ) {
+ if ( is_numeric( $qkey ) && ! is_array( $qvalue ) ) {
+ unset( $queries[ $qkey ] );
+ }
+ }
+
+ // Each query should have a value for each default key.
+ // Inherit from the parent when possible.
+ foreach ( $defaults as $dkey => $dvalue ) {
+
+ // Skip if already set.
+ if ( isset( $queries[ $dkey ] ) ) {
+ continue;
+ }
+
+ // Set the query.
+ if ( isset( $parent_query[ $dkey ] ) ) {
+ $queries[ $dkey ] = $parent_query[ $dkey ];
+ } else {
+ $queries[ $dkey ] = $dvalue;
+ }
+ }
+
+ // Validate the dates passed in the query.
+ if ( $this->is_first_order_clause( $queries ) ) {
+ $this->validate_date_values( $queries );
+ }
+
+ // Add queries to return array.
+ foreach ( $queries as $key => $q ) {
+
+ // This is a first-order query. Trust the values and sanitize when building SQL.
+ if ( ! is_array( $q ) || in_array( $key, $this->time_keys, true ) ) {
+ $retval[ $key ] = $q;
+
+ // Any array without a time key is another query, so we recurse.
+ } else {
+ $retval[] = $this->sanitize_query( $q, $queries );
+ }
+ }
+
+ // Return sanitized queries.
+ return $retval;
+ }
+
+ /**
+ * Determine whether this is a first-order clause.
+ *
+ * Checks to see if the current clause has any time-related keys.
+ * If so, it's first-order.
+ *
+ * @since 1.0.0
+ *
+ * @param array $query Query clause.
+ *
+ * @return bool True if this is a first-order clause.
+ */
+ protected function is_first_order_clause( $query = array() ) {
+ $time_keys = array_intersect( $this->time_keys, array_keys( $query ) );
+
+ return ! empty( $time_keys );
+ }
+
+ /**
+ * Determines and validates what the current unix timestamp is.
+ *
+ * @since 1.1.0
+ *
+ * @param array $query A date query or a date subquery.
+ *
+ * @return string The current unix timestamp.
+ */
+ public function get_now( $query = array() ) {
+
+ // Use now if passed
+ $retval = ! empty( $query['now'] ) && is_numeric( $query['now'] )
+ ? absint( $query['now'] )
+ : time();
+
+ return $retval;
+ }
+
+ /**
+ * Determines and validates what comparison operator to use.
+ *
+ * @since 1.0.0
+ *
+ * @param array $query A date query or a date subquery.
+ *
+ * @return string The comparison operator.
+ */
+ public function get_column( $query = array() ) {
+
+ // Use column if passed
+ $retval = ! empty( $query['column'] )
+ ? esc_sql( $this->validate_column( $query['column'] ) )
+ : $this->column;
+
+ return $retval;
+ }
+
+ /**
+ * Determines and validates what comparison operator to use.
+ *
+ * @since 1.0.0
+ *
+ * @param array $query A date query or a date subquery.
+ *
+ * @return string The comparison operator.
+ */
+ public function get_compare( $query = array() ) {
+
+ // Compare must be in the allowed array
+ $retval = ! empty( $query['compare'] ) && in_array( $query['compare'], $this->comparison_keys, true )
+ ? strtoupper( $query['compare'] )
+ : $this->compare;
+
+ return $retval;
+ }
+
+ /**
+ * Determines and validates what relation to use.
+ *
+ * @since 1.0.0
+ *
+ * @param array $query A date query or a date subquery.
+ * @return string The relation operator.
+ */
+ public function get_relation( $query = array() ) {
+
+ // Relation must be in the allowed array
+ $retval = ! empty( $query['relation'] ) && in_array( $query['relation'], $this->relation_keys, true )
+ ? strtoupper( $query['relation'] )
+ : $this->relation;
+
+ return $retval;
+ }
+
+ /**
+ * Determines and validates what start_of_week to use.
+ *
+ * @since 1.1.0
+ *
+ * @param array $query A date query or a date subquery.
+ *
+ * @return string The comparison operator.
+ */
+ public function get_start_of_week( $query = array() ) {
+
+ // Use start of week if passed and valid
+ $retval = isset( $query['start_of_week'] ) && ( 6 >= (int) $query['start_of_week'] ) && ( 0 <= (int) $query['start_of_week'] )
+ ? $query['start_of_week']
+ : $this->start_of_week;
+
+ return (int) $retval;
+ }
+
+ /**
+ * Validates the given date_query values.
+ *
+ * Note that date queries with invalid date ranges are allowed to
+ * continue (though of course no items will be found for impossible dates).
+ * This method only generates debug notices for these cases.
+ *
+ * @since 1.0.0
+ *
+ * @param array $date_query The date_query array.
+ *
+ * @return bool True if all values in the query are valid, false if one or more fail.
+ */
+ public function validate_date_values( $date_query = array() ) {
+
+ // Bail if empty.
+ if ( empty( $date_query ) ) {
+ return false;
+ }
+
+ $valid = true;
+
+ /*
+ * Validate 'before' and 'after' up front, then let the
+ * validation routine continue to be sure that all invalid
+ * values generate errors too.
+ */
+ if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ) {
+ $valid = $this->validate_date_values( $date_query['before'] );
+ }
+
+ if ( array_key_exists( 'after', $date_query ) && is_array( $date_query['after'] ) ) {
+ $valid = $this->validate_date_values( $date_query['after'] );
+ }
+
+ // Values are passthroughs.
+ if ( array_key_exists( 'value', $date_query ) ) {
+ $valid = true;
+ }
+
+ // Array containing all min-max checks.
+ $min_max_checks = array();
+
+ // Days per year.
+ if ( array_key_exists( 'year', $date_query ) ) {
+ /*
+ * If a year exists in the date query, we can use it to get the days.
+ * If multiple years are provided (as in a BETWEEN), use the first one.
+ */
+ if ( is_array( $date_query['year'] ) ) {
+ $_year = reset( $date_query['year'] );
+ } else {
+ $_year = $date_query['year'];
+ }
+
+ $max_days_of_year = gmdate( 'z', gmmktime( 0, 0, 0, 12, 31, $_year ) ) + 1;
+
+ // Otherwise we use the max of 366 (leap-year)
+ } else {
+ $max_days_of_year = 366;
+ }
+
+ // Days of year.
+ $min_max_checks['dayofyear'] = array(
+ 'min' => 1,
+ 'max' => $max_days_of_year,
+ );
+
+ // Days per week.
+ $min_max_checks['dayofweek'] = array(
+ 'min' => 1,
+ 'max' => 7,
+ );
+
+ // Days per week.
+ $min_max_checks['dayofweek_iso'] = array(
+ 'min' => 1,
+ 'max' => 7,
+ );
+
+ // Months per year.
+ $min_max_checks['month'] = array(
+ 'min' => 1,
+ 'max' => 12,
+ );
+
+ // Weeks per year.
+ if ( isset( $_year ) ) {
+ /*
+ * If we have a specific year, use it to calculate number of weeks.
+ * Note: the number of weeks in a year is the date in which Dec 28 appears.
+ */
+ $week_count = gmdate( 'W', gmmktime( 0, 0, 0, 12, 28, $_year ) );
+
+ // Otherwise set the week-count to a maximum of 53.
+ } else {
+ $week_count = 53;
+ }
+
+ // Weeks per year.
+ $min_max_checks['week'] = array(
+ 'min' => 1,
+ 'max' => $week_count,
+ );
+
+ // Days per month.
+ $min_max_checks['day'] = array(
+ 'min' => 1,
+ 'max' => 31,
+ );
+
+ // Hours per day.
+ $min_max_checks['hour'] = array(
+ 'min' => 0,
+ 'max' => 23,
+ );
+
+ // Minutes per hour.
+ $min_max_checks['minute'] = array(
+ 'min' => 0,
+ 'max' => 59,
+ );
+
+ // Seconds per minute.
+ $min_max_checks['second'] = array(
+ 'min' => 0,
+ 'max' => 59,
+ );
+
+ // Loop through min/max checks.
+ foreach ( $min_max_checks as $key => $check ) {
+
+ // Skip if not in query.
+ if ( ! array_key_exists( $key, $date_query ) ) {
+ continue;
+ }
+
+ // Check for invalid values.
+ foreach ( (array) $date_query[ $key ] as $_value ) {
+ $is_between = ( $_value >= $check['min'] ) && ( $_value <= $check['max'] );
+
+ if ( ! is_numeric( $_value ) || empty( $is_between ) ) {
+ $valid = false;
+ }
+ }
+ }
+
+ // Bail if invalid query.
+ if ( false === $valid ) {
+ return $valid;
+ }
+
+ // Check what kinds of dates are being queried for.
+ $day_exists = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] );
+ $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] );
+ $year_exists = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] );
+
+ // Checking at least day & month.
+ if ( ! empty( $day_exists ) && ! empty( $month_exists ) ) {
+
+ // Check for year query, or fallback to 2012 (for flexibility).
+ $year = ! empty( $year_exists )
+ ? $date_query['year']
+ : '2012';
+
+ // Parse the date to check.
+ $to_check = sprintf( '%s-%s-%s', $year, $date_query['month'], $date_query['day'] );
+
+ // Check the date.
+ if ( ! $this->checkdate( $date_query['month'], $date_query['day'], $year, $to_check ) ) {
+ $valid = false;
+ }
+ }
+
+ // Return if valid or not
+ return $valid;
+ }
+
+ /**
+ * Validates a column name parameter.
+ *
+ * @since 1.0.0
+ *
+ * @param string $column The user-supplied column name.
+ *
+ * @return string A validated column name value.
+ */
+ public function validate_column( $column = '' ) {
+ return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column );
+ }
+
+ /**
+ * Generate WHERE clause to be appended to a main query.
+ *
+ * @since 1.0.0
+ *
+ * @return string MySQL WHERE clauses.
+ */
+ public function get_sql() {
+ $sql = $this->get_sql_clauses();
+
+ /**
+ * Filters the date query clauses.
+ *
+ * @since 1.0.0
+ *
+ * @param string $sql Clauses of the date query.
+ * @param Date $this The Date query instance.
+ */
+ return apply_filters( 'get_date_sql', $sql, $this );
+ }
+
+ /**
+ * Generate SQL clauses to be appended to a main query.
+ *
+ * Called by the public Date::get_sql(), this method is abstracted
+ * out to maintain parity with the other Query classes.
+ *
+ * @since 1.0.0
+ *
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to the main query.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ protected function get_sql_clauses() {
+ $sql = $this->get_sql_for_query( $this->queries );
+
+ if ( ! empty( $sql['where'] ) ) {
+ $sql['where'] = ' AND ' . $sql['where'];
+ }
+
+ return apply_filters( 'get_date_sql_clauses', $sql, $this );
+ }
+
+ /**
+ * Generate SQL clauses for a single query array.
+ *
+ * If nested subqueries are found, this method recurses the tree to
+ * produce the properly nested SQL.
+ *
+ * @since 1.0.0
+ *
+ * @param array $query Query to parse.
+ * @param int $depth Optional. Number of tree levels deep we currently are.
+ * Used to calculate indentation. Default 0.
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to a single query array.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ protected function get_sql_for_query( $query = array(), $depth = 0 ) {
+ $sql_chunks = array(
+ 'join' => array(),
+ 'where' => array(),
+ );
+
+ $sql = array(
+ 'join' => '',
+ 'where' => '',
+ );
+
+ $indent = '';
+ for ( $i = 0; $i < $depth; $i++ ) {
+ $indent .= ' ';
+ }
+
+ foreach ( $query as $key => $clause ) {
+
+ if ( 'relation' === $key ) {
+ $relation = $query['relation'];
+
+ } elseif ( is_array( $clause ) ) {
+
+ // This is a first-order clause.
+ if ( $this->is_first_order_clause( $clause ) ) {
+
+ // Get clauses & where count
+ $clause_sql = $this->get_sql_for_clause( $clause, $query );
+ $where_count = count( $clause_sql['where'] );
+
+ if ( 0 === $where_count ) {
+ $sql_chunks['where'][] = '';
+
+ } elseif ( 1 === $where_count ) {
+ $sql_chunks['where'][] = $clause_sql['where'][0];
+
+ } else {
+ $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
+ }
+
+ $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
+
+ // This is a subquery, so we recurse.
+ } else {
+ $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
+
+ $sql_chunks['where'][] = $clause_sql['where'];
+ $sql_chunks['join'][] = $clause_sql['join'];
+ }
+ }
+ }
+
+ // Filter to remove empties.
+ $sql_chunks['join'] = array_filter( $sql_chunks['join'] );
+ $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
+
+ if ( empty( $relation ) ) {
+ $relation = 'AND';
+ }
+
+ // Filter duplicate JOIN clauses and combine into a single string.
+ if ( ! empty( $sql_chunks['join'] ) ) {
+ $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
+ }
+
+ // Generate a single WHERE clause with proper brackets and indentation.
+ if ( ! empty( $sql_chunks['where'] ) ) {
+ $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
+ }
+
+ // Filter and return
+ return apply_filters( 'get_date_sql_for_query', $sql, $query, $depth, $this );
+ }
+
+ /**
+ * Turns a first-order date query into SQL for a WHERE clause.
+ *
+ * @since 1.0.0
+ *
+ * @param array $query Date query clause.
+ * @param array $parent_query Parent query of the current date query.
+ *
+ * @return array {
+ * Array containing JOIN and WHERE SQL clauses to append to the main query.
+ *
+ * @type string $join SQL fragment to append to the main JOIN clause.
+ * @type string $where SQL fragment to append to the main WHERE clause.
+ * }
+ */
+ protected function get_sql_for_clause( $query = array(), $parent_query = array() ) {
+
+ // The sub-parts of a $where part.
+ $where_parts = array();
+
+ // Get first-order clauses
+ $now = $this->get_now( $query );
+ $column = $this->get_column( $query );
+ $compare = $this->get_compare( $query );
+ $start_of_week = $this->get_start_of_week( $query );
+ $inclusive = ! empty( $query['inclusive'] );
+
+ // Assign greater-than and less-than values.
+ $lt = '<';
+ $gt = '>';
+
+ if ( true === $inclusive ) {
+ $lt .= '=';
+ $gt .= '=';
+ }
+
+ // Range queries.
+ if ( ! empty( $query['after'] ) ) {
+ $where_parts[] = $this->get_db()->prepare( "{$column} {$gt} %s", $this->build_mysql_datetime( $query['after'], ! $inclusive, $now ) );
+ }
+
+ if ( ! empty( $query['before'] ) ) {
+ $where_parts[] = $this->get_db()->prepare( "{$column} {$lt} %s", $this->build_mysql_datetime( $query['before'], $inclusive, $now ) );
+ }
+
+ // Specific value queries.
+ if ( isset( $query['year'] ) && $value = $this->build_numeric_value( $compare, $query['year'] ) ) {
+ $where_parts[] = "YEAR( {$column} ) {$compare} {$value}";
+ }
+
+ if ( isset( $query['month'] ) && $value = $this->build_numeric_value( $compare, $query['month'] ) ) {
+ $where_parts[] = "MONTH( {$column} ) {$compare} {$value}";
+ } elseif ( isset( $query['monthnum'] ) && $value = $this->build_numeric_value( $compare, $query['monthnum'] ) ) {
+ $where_parts[] = "MONTH( {$column} ) {$compare} {$value}";
+ }
+
+ if ( isset( $query['week'] ) && false !== ( $value = $this->build_numeric_value( $compare, $query['week'] ) ) ) {
+ $where_parts[] = $this->build_mysql_week( $column, $start_of_week ) . " {$compare} {$value}";
+ } elseif ( isset( $query['w'] ) && false !== ( $value = $this->build_numeric_value( $compare, $query['w'] ) ) ) {
+ $where_parts[] = $this->build_mysql_week( $column, $start_of_week ) . " {$compare} {$value}";
+ }
+
+ if ( isset( $query['dayofyear'] ) && $value = $this->build_numeric_value( $compare, $query['dayofyear'] ) ) {
+ $where_parts[] = "DAYOFYEAR( {$column} ) {$compare} {$value}";
+ }
+
+ if ( isset( $query['day'] ) && $value = $this->build_numeric_value( $compare, $query['day'] ) ) {
+ $where_parts[] = "DAYOFMONTH( {$column} ) {$compare} {$value}";
+ }
+
+ if ( isset( $query['dayofweek'] ) && $value = $this->build_numeric_value( $compare, $query['dayofweek'] ) ) {
+ $where_parts[] = "DAYOFWEEK( {$column} ) {$compare} {$value}";
+ }
+
+ if ( isset( $query['dayofweek_iso'] ) && $value = $this->build_numeric_value( $compare, $query['dayofweek_iso'] ) ) {
+ $where_parts[] = "WEEKDAY( {$column} ) + 1 {$compare} {$value}";
+ }
+
+ // Straight value compare
+ if ( isset( $query['value'] ) ) {
+ $value = $this->build_value( $compare, $query['value'] );
+ $where_parts[] = "{$column} {$compare} $value";
+ }
+
+ // Hour/Minute/Second
+ if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) {
+
+ // Avoid notices.
+ foreach ( array( 'hour', 'minute', 'second' ) as $unit ) {
+ if ( ! isset( $query[ $unit ] ) ) {
+ $query[ $unit ] = null;
+ }
+ }
+
+ $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] );
+
+ if ( ! empty( $time_query ) ) {
+ $where_parts[] = $time_query;
+ }
+ }
+
+ /*
+ * Return an array of 'join' and 'where' for compatibility
+ * with other query classes.
+ */
+ return array(
+ 'where' => $where_parts,
+ 'join' => array(),
+ );
+ }
+
+ /**
+ * Builds and validates a value string based on the comparison operator.
+ *
+ * @since 1.0.0
+ *
+ * @param string $compare The compare operator to use
+ * @param string|array $value The value
+ *
+ * @return string|false|int The value to be used in SQL or false on error.
+ */
+ public function build_numeric_value( $compare = '=', $value = null ) {
+
+ // Bail if null value
+ if ( is_null( $value ) ) {
+ return false;
+ }
+
+ switch ( $compare ) {
+ case 'IN':
+ case 'NOT IN':
+ $value = (array) $value;
+
+ // Remove non-numeric values.
+ $value = array_filter( $value, 'is_numeric' );
+
+ if ( empty( $value ) ) {
+ return false;
+ }
+
+ return '(' . implode( ',', array_map( 'intval', $value ) ) . ')';
+
+ case 'BETWEEN':
+ case 'NOT BETWEEN':
+ if ( ! is_array( $value ) || ( 2 !== count( $value ) ) ) {
+ $value = array( $value, $value );
+ } else {
+ $value = array_values( $value );
+ }
+
+ // If either value is non-numeric, bail.
+ foreach ( $value as $v ) {
+ if ( ! is_numeric( $v ) ) {
+ return false;
+ }
+ }
+
+ $value = array_map( 'intval', $value );
+
+ return $value[0] . ' AND ' . $value[1];
+
+ default:
+ if ( ! is_numeric( $value ) ) {
+ return false;
+ }
+
+ return (int) $value;
+ }
+ }
+
+ /**
+ * Builds and validates a value string based on the comparison operator.
+ *
+ * @since 1.0.0
+ *
+ * @param string $compare The compare operator to use
+ * @param string|array $value The value
+ *
+ * @return string|false|int The value to be used in SQL or false on error.
+ */
+ public function build_value( $compare = '=', $value = null ) {
+
+ if ( in_array( $compare, $this->multi_value_keys, true ) ) {
+ if ( ! is_array( $value ) ) {
+ $value = preg_split( '/[,\s]+/', $value );
+ }
+ } else {
+ $value = trim( $value );
+ }
+
+ switch ( $compare ) {
+ case 'IN':
+ case 'NOT IN':
+ $compare_string = '(' . substr( str_repeat( ',%s', count( $value ) ), 1 ) . ')';
+ $where = $this->get_db()->prepare( $compare_string, $value );
+ break;
+
+ case 'BETWEEN':
+ case 'NOT BETWEEN':
+ $value = array_slice( $value, 0, 2 );
+ $where = $this->get_db()->prepare( '%s AND %s', $value );
+ break;
+
+ case 'LIKE':
+ case 'NOT LIKE':
+ $value = '%' . $this->get_db()->esc_like( $value ) . '%';
+ $where = $this->get_db()->prepare( '%s', $value );
+ break;
+
+ // EXISTS with a value is interpreted as '='.
+ case 'EXISTS':
+ $compare = '=';
+ $where = $this->get_db()->prepare( '%s', $value );
+ break;
+
+ // 'value' is ignored for NOT EXISTS.
+ case 'NOT EXISTS':
+ $where = '';
+ break;
+
+ default:
+ $where = $this->get_db()->prepare( '%s', $value );
+ break;
+ }
+
+ return $where;
+ }
+
+ /**
+ * Builds a MySQL format date/time based on some query parameters.
+ *
+ * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to
+ * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can
+ * pass a string that will be run through strtotime().
+ *
+ * @since 1.0.0
+ *
+ * @param string|array $datetime An array of parameters or a strtotime() string
+ * @param bool $default_to_max Whether to round up incomplete dates. Supported by values
+ * of $datetime that are arrays, or string values that are a
+ * subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i').
+ * Default: false.
+ * @param string|int $now The current unix timestamp.
+ *
+ * @return string|false A MySQL format date/time or false on failure
+ */
+ public function build_mysql_datetime( $datetime = '', $default_to_max = false, $now = 0 ) {
+
+ // Datetime is string
+ if ( is_string( $datetime ) ) {
+
+ // Define matches so linters don't complain
+ $matches = array();
+
+ /*
+ * Try to parse some common date formats, so we can detect
+ * the level of precision and support the 'inclusive' parameter.
+ */
+
+ // Y
+ if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) {
+ $datetime = array(
+ 'year' => intval( $matches[1] ),
+ );
+
+ // Y-m
+ } elseif ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) {
+ $datetime = array(
+ 'year' => intval( $matches[1] ),
+ 'month' => intval( $matches[2] ),
+ );
+
+ // Y-m-d
+ } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) {
+ $datetime = array(
+ 'year' => intval( $matches[1] ),
+ 'month' => intval( $matches[2] ),
+ 'day' => intval( $matches[3] ),
+ );
+
+ // Y-m-d H:i
+ } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) {
+ $datetime = array(
+ 'year' => intval( $matches[1] ),
+ 'month' => intval( $matches[2] ),
+ 'day' => intval( $matches[3] ),
+ 'hour' => intval( $matches[4] ),
+ 'minute' => intval( $matches[5] ),
+ );
+
+ // Y-m-d H:i:s
+ } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/', $datetime, $matches ) ) {
+ $datetime = array(
+ 'year' => intval( $matches[1] ),
+ 'month' => intval( $matches[2] ),
+ 'day' => intval( $matches[3] ),
+ 'hour' => intval( $matches[4] ),
+ 'minute' => intval( $matches[5] ),
+ 'second' => intval( $matches[6] ),
+ );
+ }
+ }
+
+ // No match; may be int or string
+ if ( ! is_array( $datetime ) ) {
+
+ // Maybe format or use as-is
+ $datetime = ! is_int( $datetime )
+ ? strtotime( $datetime, $now )
+ : absint( $datetime );
+
+ // Return formatted
+ return gmdate( 'Y-m-d H:i:s', $datetime );
+ }
+
+ // Map to ints
+ $datetime = array_map( 'absint', $datetime );
+
+ // Year
+ if ( ! isset( $datetime['year'] ) ) {
+ $datetime['year'] = gmdate( 'Y', $now );
+ }
+
+ // Month
+ if ( ! isset( $datetime['month'] ) ) {
+ $datetime['month'] = ! empty( $default_to_max )
+ ? 12
+ : 1;
+ }
+
+ // Day
+ if ( ! isset( $datetime['day'] ) ) {
+ $datetime['day'] = ! empty( $default_to_max )
+ ? (int) gmdate( 't', gmmktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) )
+ : 1;
+ }
+
+ // Hour
+ if ( ! isset( $datetime['hour'] ) ) {
+ $datetime['hour'] = ! empty( $default_to_max )
+ ? 23
+ : 0;
+ }
+
+ // Minute
+ if ( ! isset( $datetime['minute'] ) ) {
+ $datetime['minute'] = ! empty( $default_to_max )
+ ? 59
+ : 0;
+ }
+
+ // Second
+ if ( ! isset( $datetime['second'] ) ) {
+ $datetime['second'] = ! empty( $default_to_max )
+ ? 59
+ : 0;
+ }
+
+ // Combine and return
+ return sprintf(
+ '%04d-%02d-%02d %02d:%02d:%02d',
+ $datetime['year'],
+ $datetime['month'],
+ $datetime['day'],
+ $datetime['hour'],
+ $datetime['minute'],
+ $datetime['second']
+ );
+ }
+
+ /**
+ * Return a MySQL expression for selecting the week number based on the
+ * day that the week starts.
+ *
+ * Uses the WordPress site option, if set.
+ *
+ * @since 1.0.0
+ *
+ * @param string $column Database column.
+ * @param int $start_of_week Day that week starts on. 0 = Sunday.
+ *
+ * @return string SQL clause.
+ */
+ public function build_mysql_week( $column = '', $start_of_week = 0 ) {
+
+ // When does the week start?
+ switch ( $start_of_week ) {
+
+ // Monday
+ case 1:
+ $retval = "WEEK( {$column}, 1 )";
+ break;
+
+ // Tuesday - Saturday
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ $retval = "WEEK( DATE_SUB( {$column}, INTERVAL {$start_of_week} DAY ), 0 )";
+ break;
+
+ // Sunday
+ case 0:
+ default:
+ $retval = "WEEK( {$column}, 0 )";
+ break;
+ }
+
+ // Return SQL
+ return $retval;
+ }
+
+ /**
+ * Builds a query string for comparing time values (hour, minute, second).
+ *
+ * If just hour, minute, or second is set than a normal comparison will be done.
+ * However if multiple values are passed, a pseudo-decimal time will be created
+ * in order to be able to accurately compare against.
+ *
+ * @since 1.0.0
+ *
+ * @param string $column The column to query against. Needs to be pre-validated!
+ * @param string $compare The comparison operator. Needs to be pre-validated!
+ * @param int|null $hour Optional. An hour value (0-23).
+ * @param int|null $minute Optional. A minute value (0-59).
+ * @param int|null $second Optional. A second value (0-59).
+ *
+ * @return string|false A query part or false on failure.
+ */
+ public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) {
+
+ // Have to have at least one
+ if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) {
+ return false;
+ }
+
+ // Complex combined queries aren't supported for multi-value queries
+ if ( in_array( $compare, $this->multi_value_keys, true ) ) {
+ $retval = array();
+
+ // Hour
+ if ( isset( $hour ) && false !== ( $value = $this->build_numeric_value( $compare, $hour ) ) ) {
+ $retval[] = "HOUR( {$column} ) {$compare} {$value}";
+ }
+
+ // Minute
+ if ( isset( $minute ) && false !== ( $value = $this->build_numeric_value( $compare, $minute ) ) ) {
+ $retval[] = "MINUTE( {$column} ) {$compare} {$value}";
+ }
+
+ // Second
+ if ( isset( $second ) && false !== ( $value = $this->build_numeric_value( $compare, $second ) ) ) {
+ $retval[] = "SECOND( {$column} ) {$compare} {$value}";
+ }
+
+ return implode( ' AND ', $retval );
+ }
+
+ // Cases where just one unit is set
+
+ // Hour
+ if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_numeric_value( $compare, $hour ) ) ) {
+ return "HOUR( {$column} ) {$compare} {$value}";
+
+ // Minute
+ } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) && false !== ( $value = $this->build_numeric_value( $compare, $minute ) ) ) {
+ return "MINUTE( {$column} ) {$compare} {$value}";
+
+ // Second
+ } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) && false !== ( $value = $this->build_numeric_value( $compare, $second ) ) ) {
+ return "SECOND( {$column} ) {$compare} {$value}";
+ }
+
+ // Single units were already handled. Since hour & second isn't allowed,
+ // minute must to be set.
+ if ( ! isset( $minute ) ) {
+ return false;
+ }
+
+ // Defaults
+ $format = $time = '';
+
+ // Hour
+ if ( null !== $hour ) {
+ $format .= '%H.';
+ $time .= sprintf( '%02d', $hour ) . '.';
+ } else {
+ $format .= '0.';
+ $time .= '0.';
+ }
+
+ // Minute
+ $format .= '%i';
+ $time .= sprintf( '%02d', $minute );
+
+ // Second
+ if ( isset( $second ) ) {
+ $format .= '%s';
+ $time .= sprintf( '%02d', $second );
+ }
+
+ // Build the SQL
+ $query = "DATE_FORMAT( {$column}, %s ) {$compare} %f";
+
+ // Return the prepared SQL
+ return $this->get_db()->prepare( $query, $format, $time );
+ }
+
+ /**
+ * Test if the supplied date is valid for the Gregorian calendar.
+ *
+ * @since 1.0.0
+ *
+ * @link https://www.php.net/manual/en/function.checkdate.php
+ *
+ * @param int $month Month number.
+ * @param int $day Day number.
+ * @param int $year Year number.
+ * @param string $source_date The date to filter.
+ *
+ * @return bool True if valid date, false if not valid date.
+ */
+ public function checkdate( $month = 0, $day = 0, $year = 0, $source_date = '' ) {
+
+ // Check the date
+ $retval = checkdate( $month, $day, $year );
+
+ /**
+ * Filters whether the given date is valid for the Gregorian calendar.
+ *
+ * @since 1.0.0
+ *
+ * @param bool $checkdate Whether the given date is valid.
+ * @param string $source_date Date to check.
+ */
+ return (bool) apply_filters( 'wp_checkdate', $retval, $source_date );
+ }
+}
diff --git a/inc/Dependencies/Database/Queries/Meta.php b/inc/Dependencies/Database/Queries/Meta.php
new file mode 100644
index 0000000..07aaa85
--- /dev/null
+++ b/inc/Dependencies/Database/Queries/Meta.php
@@ -0,0 +1,29 @@
+ '',
+ 'from' => '',
+ 'where' => array(),
+ 'groupby' => '',
+ 'orderby' => '',
+ 'limits' => ''
+ );
+
+ /**
+ * Request clauses.
+ *
+ * @since 1.0.0
+ * @var array
+ */
+ protected $request_clauses = array(
+ 'select' => '',
+ 'from' => '',
+ 'where' => '',
+ 'groupby' => '',
+ 'orderby' => '',
+ 'limits' => ''
+ );
+
+ /**
+ * Meta query container.
+ *
+ * @since 1.0.0
+ * @var object|Queries\Meta
+ */
+ protected $meta_query = false;
+
+ /**
+ * Date query container.
+ *
+ * @since 1.0.0
+ * @var object|Queries\Date
+ */
+ protected $date_query = false;
+
+ /**
+ * Compare query container.
+ *
+ * @since 1.0.0
+ * @var object|Queries\Compare
+ */
+ protected $compare_query = false;
+
+ /** Query Variables *******************************************************/
+
+ /**
+ * Parsed query vars set by the application, possibly filtered and changed.
+ *
+ * This is specifically marked as public, to allow byref actions to change
+ * them from outside the class methods proper and inside filter functions.
+ *
+ * @since 1.0.0
+ * @var array
+ */
+ public $query_vars = array();
+
+ /**
+ * Original query vars set by the application.
+ *
+ * These are the original query variables before any filters are applied,
+ * and are the results of merging $query_var_defaults with $query_vars.
+ *
+ * @since 1.0.0
+ * @var array
+ */
+ protected $query_var_originals = array();
+
+ /**
+ * Default values for query vars.
+ *
+ * These are computed at runtime based on the registered columns for the
+ * database table this query relates to.
+ *
+ * @since 1.0.0
+ * @var array
+ */
+ protected $query_var_defaults = array();
+
+ /**
+ * This private variable temporarily holds onto a random string used as the
+ * default query var value. This is used internally when performing
+ * comparisons, and allows for querying by falsy values.
+ *
+ * @since 1.1.0
+ * @var string
+ */
+ protected $query_var_default_value = '';
+
+ /** Results ***************************************************************/
+
+ /**
+ * List of items located by the query.
+ *
+ * @since 1.0.0
+ * @var array
+ */
+ public $items = array();
+
+ /**
+ * The amount of found items for the current query.
+ *
+ * @since 1.0.0
+ * @var int
+ */
+ protected $found_items = 0;
+
+ /**
+ * The number of pages.
+ *
+ * @since 1.0.0
+ * @var int
+ */
+ protected $max_num_pages = 0;
+
+ /**
+ * SQL for database query.
+ *
+ * @since 1.0.0
+ * @var string
+ */
+ protected $request = '';
+
+ /** Methods ***************************************************************/
+
+ /**
+ * Sets up the item query, based on the query vars passed.
+ *
+ * @since 1.0.0
+ *
+ * @param string|array $query {
+ * Optional. Array or query string of item query parameters.
+ * Default empty.
+ *
+ * @type string $fields Site fields to return. Accepts 'ids' (returns an array of item IDs)
+ * or empty (returns an array of complete item objects). Default empty.
+ * To do a date query against a field, append the field name with _query
+ * @type bool $count Whether to return a item count (true) or array of item objects.
+ * Default false.
+ * @type int $number Limit number of items to retrieve. Use 0 for no limit.
+ * Default 100.
+ * @type int $offset Number of items to offset the query. Used to build LIMIT clause.
+ * Default 0.
+ * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
+ * Default true.
+ * @type string|array $orderby Accepts false, an empty array, or 'none' to disable `ORDER BY` clause.
+ * Default '', to primary column ID.
+ * @type string $order How to order retrieved items. Accepts 'ASC', 'DESC'.
+ * Default 'DESC'.
+ * @type string $search Search term(s) to retrieve matching items for.
+ * Default empty.
+ * @type array $search_columns Array of column names to be searched.
+ * Default empty array.
+ * @type bool $update_item_cache Whether to prime the cache for found items.
+ * Default false.
+ * @type bool $update_meta_cache Whether to prime the meta cache for found items.
+ * Default false.
+ * }
+ */
+ public function __construct( $query = array() ) {
+
+ // Setup
+ $this->set_alias();
+ $this->set_prefix();
+ $this->set_columns();
+ $this->set_item_shape();
+ $this->set_query_var_defaults();
+
+ // Maybe execute a query if arguments were passed
+ if ( ! empty( $query ) ) {
+ $this->query( $query );
+ }
+ }
+
+ /**
+ * Queries the database and retrieves items or counts.
+ *
+ * This method is public to allow subclasses to perform JIT manipulation
+ * of the parameters passed into it.
+ *
+ * @since 1.0.0
+ *
+ * @param string|array $query Array or URL query string of parameters.
+ * @param bool $use_cache Use DB cache or not. (custom parameter added by us!)
+ * @return array|int List of items, or number of items when 'count' is passed as a query var.
+ */
+ public function query( $query = array(), bool $use_cache = true ) {
+ $this->parse_query( $query );
+
+ return $this->get_items( $use_cache );
+ }
+
+ /** Private Setters *******************************************************/
+
+ /**
+ * Set the time when items were last changed.
+ *
+ * We set this locally to avoid inconsistencies between method calls.
+ *
+ * @since 1.0.0
+ */
+ private function set_last_changed() {
+ $this->last_changed = microtime();
+ }
+
+ /**
+ * Set up the table alias if not already set in the class.
+ *
+ * This happens before prefixes are applied.
+ *
+ * @since 1.0.0
+ */
+ private function set_alias() {
+ if ( empty( $this->table_alias ) ) {
+ $this->table_alias = $this->first_letters( $this->table_name );
+ }
+ }
+
+ /**
+ * Prefix table names, cache groups, and other things.
+ *
+ * This is to avoid conflicts with other plugins or themes that might be
+ * doing their own things.
+ *
+ * @since 1.0.0
+ */
+ private function set_prefix() {
+ $this->table_name = $this->apply_prefix( $this->table_name );
+ $this->table_alias = $this->apply_prefix( $this->table_alias );
+ $this->cache_group = $this->apply_prefix( $this->cache_group, '-' );
+ }
+
+ /**
+ * Set columns objects.
+ *
+ * @since 1.0.0
+ */
+ private function set_columns() {
+
+ // Bail if no table schema
+ if ( ! class_exists( $this->table_schema ) ) {
+ return;
+ }
+
+ // Invoke a new table schema class
+ $schema = new $this->table_schema;
+
+ // Maybe get the column objects
+ if ( ! empty( $schema->columns ) ) {
+ $this->columns = $schema->columns;
+ }
+ }
+
+ /**
+ * Set the default item shape if none exists.
+ *
+ * @since 1.0.0
+ */
+ private function set_item_shape() {
+ if ( empty( $this->item_shape ) || ! class_exists( $this->item_shape ) ) {
+ $this->item_shape = __NAMESPACE__ . '\\Row';
+ }
+ }
+
+ /**
+ * Set default query vars based on columns.
+ *
+ * @since 1.0.0
+ */
+ private function set_query_var_defaults() {
+
+ // Default query variable value
+ $this->query_var_default_value = function_exists( 'random_bytes' )
+ ? $this->apply_prefix( bin2hex( random_bytes( 18 ) ) )
+ : $this->apply_prefix( uniqid( '_', true ) );
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Default query variables
+ $this->query_var_defaults = array(
+ 'fields' => '',
+ 'number' => 100,
+ 'offset' => '',
+ 'orderby' => $primary,
+ 'order' => 'DESC',
+ 'groupby' => '',
+ 'search' => '',
+ 'search_columns' => array(),
+ 'count' => false,
+
+ // Disable SQL_CALC_FOUND_ROWS?
+ 'no_found_rows' => true,
+
+ // Queries
+ 'meta_query' => null, // See Queries\Meta
+ 'date_query' => null, // See Queries\Date
+ 'compare_query' => null, // See Queries\Compare
+
+ // Caching
+ 'update_item_cache' => true,
+ 'update_meta_cache' => true
+ );
+
+ // Bail if no columns
+ if ( empty( $this->columns ) ) {
+ return;
+ }
+
+ // Direct column names
+ $names = wp_list_pluck( $this->columns, 'name' );
+ foreach ( $names as $name ) {
+ $this->query_var_defaults[ $name ] = $this->query_var_default_value;
+ }
+
+ // Possible ins
+ $possible_ins = $this->get_columns( array( 'in' => true ), 'and', 'name' );
+ foreach ( $possible_ins as $in ) {
+ $key = "{$in}__in";
+ $this->query_var_defaults[ $key ] = false;
+ }
+
+ // Possible not ins
+ $possible_not_ins = $this->get_columns( array( 'not_in' => true ), 'and', 'name' );
+ foreach ( $possible_not_ins as $in ) {
+ $key = "{$in}__not_in";
+ $this->query_var_defaults[ $key ] = false;
+ }
+
+ // Possible dates
+ $possible_dates = $this->get_columns( array( 'date_query' => true ), 'and', 'name' );
+ foreach ( $possible_dates as $date ) {
+ $key = "{$date}_query";
+ $this->query_var_defaults[ $key ] = false;
+ }
+ }
+
+ /**
+ * Set the request clauses.
+ *
+ * @since 1.0.0
+ *
+ * @param array $clauses
+ */
+ private function set_request_clauses( $clauses = array() ) {
+
+ // Found rows
+ $found_rows = empty( $this->query_vars['no_found_rows'] )
+ ? 'SQL_CALC_FOUND_ROWS'
+ : '';
+
+ // Fields
+ $fields = ! empty( $clauses['fields'] )
+ ? $clauses['fields']
+ : '';
+
+ // Join
+ $join = ! empty( $clauses['join'] )
+ ? $clauses['join']
+ : '';
+
+ // Where
+ $where = ! empty( $clauses['where'] )
+ ? "WHERE {$clauses['where']}"
+ : '';
+
+ // Group by
+ $groupby = ! empty( $clauses['groupby'] )
+ ? "GROUP BY {$clauses['groupby']}"
+ : '';
+
+ // Order by
+ $orderby = ! empty( $clauses['orderby'] )
+ ? "ORDER BY {$clauses['orderby']}"
+ : '';
+
+ // Limits
+ $limits = ! empty( $clauses['limits'] )
+ ? $clauses['limits']
+ : '';
+
+ // Select & From
+ $table = $this->get_table_name();
+ $select = "SELECT {$found_rows} {$fields}";
+ $from = "FROM {$table} {$this->table_alias} {$join}";
+
+ // Put query into clauses array
+ $this->request_clauses['select'] = $select;
+ $this->request_clauses['from'] = $from;
+ $this->request_clauses['where'] = $where;
+ $this->request_clauses['groupby'] = $groupby;
+ $this->request_clauses['orderby'] = $orderby;
+ $this->request_clauses['limits'] = $limits;
+ }
+
+ /**
+ * Set the request.
+ *
+ * @since 1.0.0
+ */
+ private function set_request() {
+ $filtered = array_filter( $this->request_clauses );
+ $clauses = array_map( 'trim', $filtered );
+ $this->request = implode( ' ', $clauses );
+ }
+
+ /**
+ * Set items by mapping them through the single item callback.
+ *
+ * @since 1.0.0
+ * @param array $item_ids
+ */
+ private function set_items( $item_ids = array() ) {
+
+ // Bail if counting, to avoid shaping items
+ if ( ! empty( $this->query_vars['count'] ) ) {
+ $this->items = $item_ids;
+ return;
+ }
+
+ // Cast to integers
+ $item_ids = array_map( 'intval', $item_ids );
+
+ // Prime item caches
+ $this->prime_item_caches( $item_ids );
+
+ // Shape the items
+ $this->items = $this->shape_items( $item_ids );
+ }
+
+ /**
+ * Populates found_items and max_num_pages properties for the current query
+ * if the limit clause was used.
+ *
+ * @since 1.0.0
+ *
+ * @param array $item_ids Optional array of item IDs
+ */
+ private function set_found_items( $item_ids = array() ) {
+
+ // Items were not found
+ if ( empty( $item_ids ) ) {
+ return;
+ }
+
+ // Default to number of item IDs
+ $this->found_items = count( (array) $item_ids );
+
+ // Count query
+ if ( ! empty( $this->query_vars['count'] ) ) {
+
+ // Not grouped
+ if ( is_numeric( $item_ids ) && empty( $this->query_vars['groupby'] ) ) {
+ $this->found_items = intval( $item_ids );
+ }
+
+ // Not a count query
+ } elseif ( is_array( $item_ids ) && ( ! empty( $this->query_vars['number'] ) && empty( $this->query_vars['no_found_rows'] ) ) ) {
+
+ /**
+ * Filters the query used to retrieve found item count.
+ *
+ * @since 1.0.0
+ *
+ * @param string $found_items_query SQL query. Default 'SELECT FOUND_ROWS()'.
+ * @param object $item_query The object instance.
+ */
+ $found_items_query = (string) apply_filters_ref_array( $this->apply_prefix( "found_{$this->item_name_plural}_query" ), array( 'SELECT FOUND_ROWS()', &$this ) );
+
+ // Maybe query for found items
+ if ( ! empty( $found_items_query ) ) {
+ $this->found_items = (int) $this->get_db()->get_var( $found_items_query );
+ }
+ }
+ }
+
+ /** Public Setters ********************************************************/
+
+ /**
+ * Set a query var, to both defaults and request arrays.
+ *
+ * This method is used to expose the private query_vars array to hooks,
+ * allowing them to manipulate query vars just-in-time.
+ *
+ * @since 1.0.0
+ *
+ * @param string $key
+ * @param string $value
+ */
+ public function set_query_var( $key = '', $value = '' ) {
+ $this->query_var_defaults[ $key ] = $value;
+ $this->query_vars[ $key ] = $value;
+ }
+
+ /**
+ * Check whether a query variable strictly equals the unique default
+ * starting value.
+ *
+ * @since 1.1.0
+ * @param string $key
+ * @return bool
+ */
+ public function is_query_var_default( $key = '' ) {
+ return (bool) ( $this->query_vars[ $key ] === $this->query_var_default_value );
+ }
+
+ /** Private Getters *******************************************************/
+
+ /**
+ * Pass-through method to return a new Meta object.
+ *
+ * @since 1.0.0
+ *
+ * @param array $args See Queries\Meta
+ *
+ * @return Queries\Meta
+ */
+ private function get_meta_query( $args = array() ) {
+ return new Queries\Meta( $args );
+ }
+
+ /**
+ * Pass-through method to return a new Compare object.
+ *
+ * @since 1.0.0
+ *
+ * @param array $args See Queries\Compare
+ *
+ * @return Queries\Compare
+ */
+ private function get_compare_query( $args = array() ) {
+ return new Queries\Compare( $args );
+ }
+
+ /**
+ * Pass-through method to return a new Queries\Date object.
+ *
+ * @since 1.0.0
+ *
+ * @param array $args See Queries\Date
+ *
+ * @return Queries\Date
+ */
+ private function get_date_query( $args = array() ) {
+ return new Queries\Date( $args );
+ }
+
+ /**
+ * Return the current time as a UTC timestamp.
+ *
+ * This is used by add_item() and update_item()
+ *
+ * @since 1.0.0
+ *
+ * @return string
+ */
+ private function get_current_time() {
+ return gmdate( "Y-m-d\TH:i:s\Z" );
+ }
+
+ /**
+ * Return the literal table name (with prefix) from the database interface.
+ *
+ * @since 1.0.0
+ *
+ * @return string
+ */
+ private function get_table_name() {
+ return $this->get_db()->{$this->table_name};
+ }
+
+ /**
+ * Return array of column names.
+ *
+ * @since 1.0.0
+ *
+ * @return array
+ */
+ private function get_column_names() {
+ return array_flip( $this->get_columns( array(), 'and', 'name' ) );
+ }
+
+ /**
+ * Return the primary database column name.
+ *
+ * @since 1.0.0
+ *
+ * @return string Default "id", Primary column name if not empty
+ */
+ private function get_primary_column_name() {
+ return $this->get_column_field( array( 'primary' => true ), 'name', 'id' );
+ }
+
+ /**
+ * Get a column from an array of arguments.
+ *
+ * @since 1.0.0
+ *
+ * @param array $args Arguments to get a column by.
+ * @param string $field Field to get from a column.
+ * @param mixed $default Default to use if no field is set.
+ * @return mixed Column object, or false
+ */
+ private function get_column_field( $args = array(), $field = '', $default = false ) {
+
+ // Get the column
+ $column = $this->get_column_by( $args );
+
+ // Return field, or default
+ return isset( $column->{$field} )
+ ? $column->{$field}
+ : $default;
+ }
+
+ /**
+ * Get a column from an array of arguments.
+ *
+ * @since 1.0.0
+ *
+ * @param array $args Arguments to get a column by.
+ * @return mixed Column object, or false
+ */
+ private function get_column_by( $args = array() ) {
+
+ // Filter columns
+ $filter = $this->get_columns( $args );
+
+ // Return column or false
+ return ! empty( $filter )
+ ? reset( $filter )
+ : false;
+ }
+
+ /**
+ * Get columns from an array of arguments.
+ *
+ * @since 1.0.0
+ *
+ * @param array $args Arguments to filter columns by.
+ * @param string $operator Optional. The logical operation to perform.
+ * @param string $field Optional. A field from the object to place
+ * instead of the entire object. Default false.
+ * @return array Array of column.
+ */
+ private function get_columns( $args = array(), $operator = 'and', $field = false ) {
+
+ // Filter columns
+ $filter = wp_filter_object_list( $this->columns, $args, $operator, $field );
+
+ // Return column or false
+ return ! empty( $filter )
+ ? array_values( $filter )
+ : array();
+ }
+
+ /**
+ * Get a single database row by any column and value, skipping cache.
+ *
+ * @since 1.0.0
+ *
+ * @param string $column_name Name of database column
+ * @param string $column_value Value to query for
+ * @return object|false False if empty/error, Object if successful
+ */
+ private function get_item_raw( $column_name = '', $column_value = '' ) {
+
+ // Bail if no name or value
+ if ( empty( $column_name ) || empty( $column_value ) ) {
+ return false;
+ }
+
+ // Bail if values aren't query'able
+ if ( ! is_string( $column_name ) || ! is_scalar( $column_value ) ) {
+ return false;
+ }
+
+ // Get query parts
+ $table = $this->get_table_name();
+ $pattern = $this->get_column_field( array( 'name' => $column_name ), 'pattern', '%s' );
+
+ // Query database
+ $query = "SELECT * FROM {$table} WHERE {$column_name} = {$pattern} LIMIT 1";
+ $select = $this->get_db()->prepare( $query, $column_value );
+ $result = $this->get_db()->get_row( $select );
+
+ // Bail on failure
+ if ( ! $this->is_success( $result ) ) {
+ return false;
+ }
+
+ // Return row
+ return $result;
+ }
+
+ /**
+ * Retrieves a list of items matching the query vars.
+ *
+ * @since 1.0.0
+ *
+ * @param bool $use_cache Use DB cache or not. (custom parameter added by us!)
+ *
+ * @return array|int List of items, or number of items when 'count' is passed as a query var.
+ */
+ private function get_items( bool $use_cache = true ) {
+
+ /**
+ * Fires before object items are retrieved.
+ *
+ * @since 1.0.0
+ *
+ * @param Query &$this Current instance of Query, passed by reference.
+ */
+ do_action_ref_array( $this->apply_prefix( "pre_get_{$this->item_name_plural}" ), array( &$this ) );
+
+ // Never limit, never update item/meta caches when counting
+ if ( ! empty( $this->query_vars['count'] ) ) {
+ $this->query_vars['number'] = false;
+ $this->query_vars['no_found_rows'] = true;
+ $this->query_vars['update_item_cache'] = false;
+ $this->query_vars['update_meta_cache'] = false;
+ }
+
+ // Check the cache
+ $cache_key = $this->get_cache_key();
+ $cache_value = $use_cache ? $this->cache_get( $cache_key, $this->cache_group ) : false;
+
+ // No cache value
+ if ( false === $cache_value ) {
+ $item_ids = $this->get_item_ids();
+
+ // Set the number of found items
+ $this->set_found_items( $item_ids );
+
+ if ( $use_cache ) {
+ // Format the cached value
+ $cache_value = array(
+ 'item_ids' => $item_ids,
+ 'found_items' => intval( $this->found_items ),
+ );
+
+ // Add value to the cache
+ $this->cache_add( $cache_key, $cache_value, $this->cache_group );
+ }
+
+ // Value exists in cache
+ } else {
+ $item_ids = $cache_value['item_ids'];
+ $this->found_items = intval( $cache_value['found_items'] );
+ }
+
+ // Pagination
+ if ( ! empty( $this->found_items ) && ! empty( $this->query_vars['number'] ) ) {
+ $this->max_num_pages = ceil( $this->found_items / $this->query_vars['number'] );
+ }
+
+ // Cast to int if not grouping counts
+ if ( ! empty( $this->query_vars['count'] ) && empty( $this->query_vars['groupby'] ) ) {
+ $item_ids = intval( $item_ids );
+ }
+
+ // Set items from IDs
+ $this->set_items( $item_ids );
+
+ // Return array of items
+ return $this->items;
+ }
+
+ /**
+ * Used internally to get a list of item IDs matching the query vars.
+ *
+ * @since 1.0.0
+ *
+ * @return int|array A single count of item IDs if a count query. An array
+ * of item IDs if a full query.
+ */
+ private function get_item_ids() {
+
+ // Setup primary column, and parse the where clause
+ $this->parse_where();
+
+ // Order & Order By
+ $order = $this->parse_order( $this->query_vars['order'] );
+ $orderby = $this->get_order_by( $order );
+
+ // Limit & Offset
+ $limit = absint( $this->query_vars['number'] );
+ $offset = absint( $this->query_vars['offset'] );
+
+ // Limits
+ if ( ! empty( $limit ) ) {
+ $limits = ! empty( $offset )
+ ? "LIMIT {$offset}, {$limit}"
+ : "LIMIT {$limit}";
+ } else {
+ $limits = '';
+ }
+
+ // Where & Join
+ $where = implode( ' AND ', $this->query_clauses['where'] );
+ $join = implode( ', ', $this->query_clauses['join'] );
+
+ // Group by
+ $groupby = $this->parse_groupby( $this->query_vars['groupby'] );
+
+ // Fields
+ $fields = $this->parse_fields( $this->query_vars['fields'] );
+
+ // Setup the query array (compact() is too opaque here)
+ $query = array(
+ 'fields' => $fields,
+ 'join' => $join,
+ 'where' => $where,
+ 'orderby' => $orderby,
+ 'limits' => $limits,
+ 'groupby' => $groupby
+ );
+
+ /**
+ * Filters the item query clauses.
+ *
+ * @since 1.0.0
+ *
+ * @param array $pieces A compacted array of item query clauses.
+ * @param Query &$this Current instance passed by reference.
+ */
+ $clauses = (array) apply_filters_ref_array( $this->apply_prefix( "{$this->item_name_plural}_query_clauses" ), array( $query, &$this ) );
+
+ // Setup request
+ $this->set_request_clauses( $clauses );
+ $this->set_request();
+
+ // Return count
+ if ( ! empty( $this->query_vars['count'] ) ) {
+
+ // Get vars or results
+ $retval = empty( $this->query_vars['groupby'] )
+ ? $this->get_db()->get_var( $this->request )
+ : $this->get_db()->get_results( $this->request, ARRAY_A );
+
+ // Return vars or results
+ return $retval;
+ }
+
+ // Get IDs
+ $item_ids = $this->get_db()->get_col( $this->request );
+
+ // Return parsed IDs
+ return wp_parse_id_list( $item_ids );
+ }
+
+ /**
+ * Get the ORDERBY clause.
+ *
+ * @since 1.0.0
+ *
+ * @param string $order
+ * @return string
+ */
+ private function get_order_by( $order = '' ) {
+
+ // Default orderby primary column
+ $parsed = $this->parse_orderby();
+ $orderby = "{$parsed} {$order}";
+
+ // Disable ORDER BY if counting, or: 'none', an empty array, or false.
+ if ( ! empty( $this->query_vars['count'] ) || in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
+ $orderby = '';
+
+ // Ordering by something, so figure it out
+ } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
+
+ // Array of keys, or comma separated
+ $ordersby = is_array( $this->query_vars['orderby'] )
+ ? $this->query_vars['orderby']
+ : preg_split( '/[,\s]/', $this->query_vars['orderby'] );
+
+ $orderby_array = array();
+ $possible_ins = $this->get_columns( array( 'in' => true ), 'and', 'name' );
+ $sortables = $this->get_columns( array( 'sortable' => true ), 'and', 'name' );
+
+ // Loop through possible order by's
+ foreach ( $ordersby as $_key => $_value ) {
+
+ // Skip if empty
+ if ( empty( $_value ) ) {
+ continue;
+ }
+
+ // Key is numeric
+ if ( is_int( $_key ) ) {
+ $_orderby = $_value;
+ $_item = $order;
+
+ // Key is string
+ } else {
+ $_orderby = $_key;
+ $_item = $_value;
+ }
+
+ // Skip if not sortable
+ if ( ! in_array( $_value, $sortables, true ) ) {
+ continue;
+ }
+
+ // Parse orderby
+ $parsed = $this->parse_orderby( $_orderby );
+
+ // Skip if empty
+ if ( empty( $parsed ) ) {
+ continue;
+ }
+
+ // Set if __in
+ if ( in_array( $_orderby, $possible_ins, true ) ) {
+ $orderby_array[] = "{$parsed} {$order}";
+ continue;
+ }
+
+ // Append parsed orderby to array
+ $orderby_array[] = $parsed . ' ' . $this->parse_order( $_item );
+ }
+
+ // Only set if valid orderby
+ if ( ! empty( $orderby_array ) ) {
+ $orderby = implode( ', ', $orderby_array );
+ }
+ }
+
+ // Return parsed orderby
+ return $orderby;
+ }
+
+ /**
+ * Used internally to generate an SQL string for searching across multiple
+ * columns.
+ *
+ * @since 1.0.0
+ *
+ * @param string $string Search string.
+ * @param array $columns Columns to search.
+ * @return string Search SQL.
+ */
+ private function get_search_sql( $string = '', $columns = array() ) {
+
+ // Array or String
+ $like = ( false !== strpos( $string, '*' ) )
+ ? '%' . implode( '%', array_map( array( $this->get_db(), 'esc_like' ), explode( '*', $string ) ) ) . '%'
+ : '%' . $this->get_db()->esc_like( $string ) . '%';
+
+ // Default array
+ $searches = array();
+
+ // Build search SQL
+ foreach ( $columns as $column ) {
+ $searches[] = $this->get_db()->prepare( "{$column} LIKE %s", $like );
+ }
+
+ // Return the clause
+ return '(' . implode( ' OR ', $searches ) . ')';
+ }
+
+ /** Private Parsers *******************************************************/
+
+ /**
+ * Parses arguments passed to the item query with default query parameters.
+ *
+ * @since 1.0.0
+ *
+ * @see Query::__construct()
+ *
+ * @param string|array $query Array or string of Query arguments.
+ */
+ private function parse_query( $query = array() ) {
+
+ // Setup the query_vars_original var
+ $this->query_var_originals = wp_parse_args( $query );
+
+ // Setup the query_vars parsed var
+ $this->query_vars = wp_parse_args(
+ $this->query_var_originals,
+ $this->query_var_defaults
+ );
+
+ /**
+ * Fires after the item query vars have been parsed.
+ *
+ * @since 1.0.0
+ *
+ * @param Query &$this The Query instance (passed by reference).
+ */
+ do_action_ref_array( $this->apply_prefix( "parse_{$this->item_name_plural}_query" ), array( &$this ) );
+ }
+
+ /**
+ * Parse the where clauses for all known columns.
+ *
+ * @todo split this method into smaller parts
+ *
+ * @since 1.0.0
+ */
+ private function parse_where() {
+
+ // Defaults
+ $where = $join = $searchable = $date_query = array();
+
+ // Loop through columns
+ foreach ( $this->columns as $column ) {
+
+ // Maybe add name to searchable array
+ if ( true === $column->searchable ) {
+ $searchable[] = $column->name;
+ }
+
+ // Literal column comparison
+ if ( ! $this->is_query_var_default( $column->name ) ) {
+
+ // Array (unprepared)
+ if ( is_array( $this->query_vars[ $column->name ] ) ) {
+ $where_id = "'" . implode( "', '", $this->get_db()->_escape( $this->query_vars[ $column->name ] ) ) . "'";
+ $statement = "{$this->table_alias}.{$column->name} IN ({$where_id})";
+
+ // Add to where array
+ $where[ $column->name ] = $statement;
+
+ // Numeric/String/Float (prepared)
+ } else {
+ $pattern = $this->get_column_field( array( 'name' => $column->name ), 'pattern', '%s' );
+ $where_id = $this->query_vars[ $column->name ];
+ $statement = "{$this->table_alias}.{$column->name} = {$pattern}";
+
+ // Add to where array
+ $where[ $column->name ] = $this->get_db()->prepare( $statement, $where_id );
+ }
+ }
+
+ // __in
+ if ( true === $column->in ) {
+ $where_id = "{$column->name}__in";
+
+ // Parse item for an IN clause.
+ if ( isset( $this->query_vars[ $where_id ] ) && is_array( $this->query_vars[ $where_id ] ) ) {
+
+ // Convert single item arrays to literal column comparisons
+ if ( 1 === count( $this->query_vars[ $where_id ] ) ) {
+ $column_value = reset( $this->query_vars[ $where_id ] );
+ $statement = "{$this->table_alias}.{$column->name} = %s";
+
+ $where[ $column->name ] = $this->get_db()->prepare( $statement, $column_value );
+
+ // Implode
+ } else {
+ $where[ $where_id ] = "{$this->table_alias}.{$column->name} IN ( '" . implode( "', '", $this->get_db()->_escape( $this->query_vars[ $where_id ] ) ) . "' )";
+ }
+ }
+ }
+
+ // __not_in
+ if ( true === $column->not_in ) {
+ $where_id = "{$column->name}__not_in";
+
+ // Parse item for a NOT IN clause.
+ if ( isset( $this->query_vars[ $where_id ] ) && is_array( $this->query_vars[ $where_id ] ) ) {
+
+ // Convert single item arrays to literal column comparisons
+ if ( 1 === count( $this->query_vars[ $where_id ] ) ) {
+ $column_value = reset( $this->query_vars[ $where_id ] );
+ $statement = "{$this->table_alias}.{$column->name} != %s";
+
+ $where[ $column->name ] = $this->get_db()->prepare( $statement, $column_value );
+
+ // Implode
+ } else {
+ $where[ $where_id ] = "{$this->table_alias}.{$column->name} NOT IN ( '" . implode( "', '", $this->get_db()->_escape( $this->query_vars[ $where_id ] ) ) . "' )";
+ }
+ }
+ }
+
+ // date_query
+ if ( true === $column->date_query ) {
+ $where_id = "{$column->name}_query";
+ $column_date = $this->query_vars[ $where_id ];
+
+ // Parse item
+ if ( ! empty( $column_date ) ) {
+
+ // Default arguments
+ $defaults = array(
+ 'column' => "{$this->table_alias}.{$column->name}",
+ 'before' => $column_date,
+ 'inclusive' => true
+ );
+
+ // Default date query
+ if ( is_string( $column_date ) ) {
+ $date_query[] = $defaults;
+
+ // Array query var
+ } elseif ( is_array( $column_date ) ) {
+
+ // Auto-fill column if empty
+ if ( empty( $column_date['column'] ) ) {
+ $column_date['column'] = $defaults['column'];
+ }
+
+ // Add clause to date query
+ $date_query[] = $column_date;
+ }
+ }
+ }
+ }
+
+ // Maybe search if columns are searchable.
+ if ( ! empty( $searchable ) && strlen( $this->query_vars['search'] ) ) {
+ $search_columns = array();
+
+ // Intersect against known searchable columns
+ if ( ! empty( $this->query_vars['search_columns'] ) ) {
+ $search_columns = array_intersect(
+ $this->query_vars['search_columns'],
+ $searchable
+ );
+ }
+
+ // Default to all searchable columns
+ if ( empty( $search_columns ) ) {
+ $search_columns = $searchable;
+ }
+
+ /**
+ * Filters the columns to search in a Query search.
+ *
+ * @since 1.0.0
+ *
+ * @param array $search_columns Array of column names to be searched.
+ * @param string $search Text being searched.
+ * @param object $this The current Query instance.
+ */
+ $search_columns = (array) apply_filters( $this->apply_prefix( "{$this->item_name_plural}_search_columns" ), $search_columns, $this->query_vars['search'], $this );
+
+ // Add search query clause
+ $where['search'] = $this->get_search_sql( $this->query_vars['search'], $search_columns );
+ }
+
+ /** Query Classes *****************************************************/
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get the meta table
+ $table = $this->get_meta_type();
+
+ // Set the " AND " regex pattern
+ $and = '/^\s*AND\s*/';
+
+ // Maybe perform a meta query.
+ $meta_query = $this->query_vars['meta_query'];
+ if ( ! empty( $meta_query ) && is_array( $meta_query ) ) {
+ $this->meta_query = $this->get_meta_query( $meta_query );
+ $clauses = $this->meta_query->get_sql( $table, $this->table_alias, $primary, $this );
+
+ // Not all objects have meta, so make sure this one exists
+ if ( false !== $clauses ) {
+
+ // Set join
+ if ( ! empty( $clauses['join'] ) ) {
+ $join['meta_query'] = $clauses['join'];
+ }
+
+ // Set where
+ if ( ! empty( $clauses['where'] ) ) {
+
+ // Remove " AND " from query query where clause
+ $where['meta_query'] = preg_replace( $and, '', $clauses['where'] );
+ }
+ }
+ }
+
+ // Maybe perform a compare query.
+ $compare_query = $this->query_vars['compare_query'];
+ if ( ! empty( $compare_query ) && is_array( $compare_query ) ) {
+ $this->compare_query = $this->get_compare_query( $compare_query );
+ $clauses = $this->compare_query->get_sql( $table, $this->table_alias, $primary, $this );
+
+ // Not all objects can compare, so make sure this one exists
+ if ( false !== $clauses ) {
+
+ // Set join
+ if ( ! empty( $clauses['join'] ) ) {
+ $join['compare_query'] = $clauses['join'];
+ }
+
+ // Set where
+ if ( ! empty( $clauses['where'] ) ) {
+
+ // Remove " AND " from query where clause.
+ $where['compare_query'] = preg_replace( $and, '', $clauses['where'] );
+ }
+ }
+ }
+
+ // Only do a date query with an array
+ $date_query = ! empty( $date_query )
+ ? $date_query
+ : $this->query_vars['date_query'];
+
+ // Maybe perform a date query
+ if ( ! empty( $date_query ) && is_array( $date_query ) ) {
+ $this->date_query = $this->get_date_query( $date_query );
+ $clauses = $this->date_query->get_sql( $this->table_name, $this->table_alias, $primary, $this );
+
+ // Not all objects are dates, so make sure this one exists
+ if ( false !== $clauses ) {
+
+ // Set join
+ if ( ! empty( $clauses['join'] ) ) {
+ $join['date_query'] = $clauses['join'];
+ }
+
+ // Set where
+ if ( ! empty( $clauses['where'] ) ) {
+
+ // Remove " AND " from query where clause.
+ $where['date_query'] = preg_replace( $and, '', $clauses['where'] );
+ }
+ }
+ }
+
+ // Set where and join clauses, removing possible empties
+ $this->query_clauses['where'] = array_filter( $where );
+ $this->query_clauses['join'] = array_filter( $join );
+ }
+
+ /**
+ * Parse which fields to query for.
+ *
+ * @since 1.0.0
+ *
+ * @param string $fields
+ * @param bool $alias
+ * @return string
+ */
+ private function parse_fields( $fields = '', $alias = true ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Default return value
+ $retval = ( true === $alias )
+ ? "{$this->table_alias}.{$primary}"
+ : $primary;
+
+ // No fields
+ if ( empty( $fields ) && ! empty( $this->query_vars['count'] ) ) {
+
+ // Possible fields to group by
+ $groupby_names = $this->parse_groupby( $this->query_vars['groupby'], $alias );
+ $groupby_names = ! empty( $groupby_names )
+ ? "{$groupby_names}"
+ : '';
+
+ // Group by or total count
+ $retval = ! empty( $groupby_names )
+ ? "{$groupby_names}, COUNT(*) as count"
+ : 'COUNT(*)';
+ }
+
+ // Return fields (or COUNT)
+ return $retval;
+ }
+
+ /**
+ * Parses and sanitizes the 'groupby' keys passed into the item query.
+ *
+ * @since 1.0.0
+ *
+ * @param string $groupby
+ * @param bool $alias
+ * @return string
+ */
+ private function parse_groupby( $groupby = '', $alias = true ) {
+
+ // Bail if empty
+ if ( empty( $groupby ) ) {
+ return '';
+ }
+
+ // Sanitize groupby columns
+ $groupby = (array) array_map( 'sanitize_key', (array) $groupby );
+
+ // Re'flip column names back around
+ $columns = array_flip( $this->get_column_names() );
+
+ // Get the intersection of allowed column names to groupby columns
+ $intersect = array_intersect( $groupby, $columns );
+
+ // Bail if invalid column
+ if ( empty( $intersect ) ) {
+ return '';
+ }
+
+ // Default return value
+ $retval = array();
+
+ // Maybe prepend table alias to key
+ foreach ( $intersect as $key ) {
+ $retval[] = ( true === $alias )
+ ? "{$this->table_alias}.{$key}"
+ : $key;
+ }
+
+ // Separate sanitized columns
+ return implode( ',', array_values( $retval ) );
+ }
+
+ /**
+ * Parses and sanitizes 'orderby' keys passed to the item query.
+ *
+ * @since 1.0.0
+ *
+ * @param string $orderby Field for the items to be ordered by.
+ * @return string|false Value to used in the ORDER clause. False otherwise.
+ */
+ private function parse_orderby( $orderby = '' ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Default return value
+ $parsed = "{$this->table_alias}.{$primary}";
+
+ // Default to primary column
+ if ( empty( $orderby ) ) {
+ $orderby = $primary;
+ }
+
+ // __in
+ if ( false !== strstr( $orderby, '__in' ) ) {
+ $column_name = str_replace( '__in', '', $orderby );
+ $column = $this->get_column_by( array( 'name' => $column_name ) );
+ $item_in = $column->is_numeric()
+ ? implode( ',', array_map( 'absint', $this->query_vars[ $orderby ] ) )
+ : implode( ',', $this->query_vars[ $orderby ] );
+
+ $parsed = "FIELD( {$this->table_alias}.{$column->name}, {$item_in} )";
+
+ // Specific column
+ } else {
+
+ // Orderby is a literal, sortable column name
+ $sortables = $this->get_columns( array( 'sortable' => true ), 'and', 'name' );
+ if ( in_array( $orderby, $sortables, true ) ) {
+ $parsed = "{$this->table_alias}.{$orderby}";
+ }
+ }
+
+ // Return parsed value
+ return $parsed;
+ }
+
+ /**
+ * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as
+ * necessary.
+ *
+ * @since 1.0.0
+ *
+ * @param string $order The 'order' query variable.
+ * @return string The sanitized 'order' query variable.
+ */
+ private function parse_order( $order = '' ) {
+
+ // Bail if malformed
+ if ( empty( $order ) || ! is_string( $order ) ) {
+ return 'DESC';
+ }
+
+ // Ascending or Descending
+ return ( 'ASC' === strtoupper( $order ) )
+ ? 'ASC'
+ : 'DESC';
+ }
+
+ /** Private Shapers *******************************************************/
+
+ /**
+ * Shape items into their most relevant objects.
+ *
+ * This will try to use item_shape, but will fallback to a private
+ * method for querying and caching items.
+ *
+ * If using the `fields` parameter, results will have unique shapes based on
+ * exactly what was requested.
+ *
+ * @since 1.0.0
+ *
+ * @param array $items
+ * @return array
+ */
+ private function shape_items( $items = array() ) {
+
+ // Force to stdClass if querying for fields
+ if ( ! empty( $this->query_vars['fields'] ) ) {
+ $this->item_shape = 'stdClass';
+ }
+
+ // Default return value
+ $retval = array();
+
+ // Use foreach because it's faster than array_map()
+ if ( ! empty( $items ) ) {
+ foreach ( $items as $item ) {
+ $retval[] = $this->get_item( $item );
+ }
+ }
+
+ /**
+ * Filters the object query results.
+ *
+ * Looks like `edd_get_customers`
+ *
+ * @since 1.0.0
+ *
+ * @param array $retval An array of items.
+ * @param object &$this Current instance of Query, passed by reference.
+ */
+ $retval = (array) apply_filters_ref_array( $this->apply_prefix( "the_{$this->item_name_plural}" ), array( $retval, &$this ) );
+
+ // Return filtered results
+ return ! empty( $this->query_vars['fields'] )
+ ? $this->get_item_fields( $retval )
+ : $retval;
+ }
+
+ /**
+ * Get specific item fields based on query_vars['fields'].
+ *
+ * @since 1.0.0
+ *
+ * @param array $items
+ * @return array
+ */
+ private function get_item_fields( $items = array() ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get the query var fields
+ $fields = $this->query_vars['fields'];
+
+ // Strings need to be single columns
+ if ( is_string( $fields ) ) {
+ $field = sanitize_key( $fields );
+ $items = ( 'ids' === $fields )
+ ? wp_list_pluck( $items, $primary )
+ : wp_list_pluck( $items, $field, $primary );
+
+ // Arrays could be anything
+ } elseif ( is_array( $fields ) ) {
+ $new_items = array();
+ $fields = array_flip( $fields );
+
+ // Loop through items and pluck out the fields
+ foreach ( $items as $item_id => $item ) {
+ $new_items[ $item_id ] = (object) array_intersect_key( (array) $item, $fields );
+ }
+
+ // Set the items and unset the new items
+ $items = $new_items;
+ unset( $new_items );
+ }
+
+ // Return the item, possibly reduced
+ return $items;
+ }
+
+ /**
+ * Shape an item ID from an object, array, or numeric value.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $item
+ * @return int
+ */
+ private function shape_item_id( $item = 0 ) {
+
+ // Default return value
+ $retval = 0;
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Numeric item ID
+ if ( is_numeric( $item ) ) {
+ $retval = $item;
+
+ // Object item
+ } elseif ( is_object( $item ) && isset( $item->{$primary} ) ) {
+ $retval = $item->{$primary};
+
+ // Array item
+ } elseif ( is_array( $item ) && isset( $item[ $primary ] ) ) {
+ $retval = $item[ $primary ];
+ }
+
+ // Return the item ID
+ return absint( $retval );
+ }
+
+ /** Queries ***************************************************************/
+
+ /**
+ * Get a single database row by the primary column ID, possibly from cache.
+ *
+ * Accepts an integer, object, or array, and attempts to get the ID from it,
+ * then attempts to retrieve that item fresh from the database or cache.
+ *
+ * @since 1.0.0
+ *
+ * @param int|array|object $item_id The ID of the item
+ * @return object|false False if empty/error, Object if successful
+ */
+ public function get_item( $item_id = 0 ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no item to get by
+ if ( empty( $item_id ) ) {
+ return false;
+ }
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get item by ID
+ return $this->get_item_by( $primary, $item_id );
+ }
+
+ /**
+ * Get a single database row by any column and value, possibly from cache.
+ *
+ * Take care to only use this method on columns with unique values,
+ * preferably with a cache group for that column. See: get_item().
+ *
+ * @since 1.0.0
+ *
+ * @param string $column_name Name of database column
+ * @param int|string $column_value Value to query for
+ * @return object|false False if empty/error, Object if successful
+ */
+ public function get_item_by( $column_name = '', $column_value = '' ) {
+
+ // Default return value
+ $retval = false;
+
+ // Bail if no key or value
+ if ( empty( $column_name ) || empty( $column_value ) ) {
+ return $retval;
+ }
+
+ // Bail if name is not a string
+ if ( ! is_string( $column_name ) ) {
+ return $retval;
+ }
+
+ // Bail if value is not scalar (null values also not allowed)
+ if ( ! is_scalar( $column_value ) ) {
+ return $retval;
+ }
+
+ // Get all of the column names
+ $columns = $this->get_column_names();
+
+ // Bail if column does not exist
+ if ( ! isset( $columns[ $column_name ] ) ) {
+ return $retval;
+ }
+
+ // Get all of the cache groups
+ $groups = $this->get_cache_groups();
+
+ // Check cache
+ if ( ! empty( $groups[ $column_name ] ) ) {
+ $retval = $this->cache_get( $column_value, $groups[ $column_name ] );
+ }
+
+ // Item not cached
+ if ( false === $retval ) {
+
+ // Get item by column name & value (from database, not cache)
+ $retval = $this->get_item_raw( $column_name, $column_value );
+
+ // Bail on failure
+ if ( ! $this->is_success( $retval ) ) {
+ return false;
+ }
+
+ // Update item cache(s)
+ $this->update_item_cache( $retval );
+ }
+
+ // Reduce the item
+ $retval = $this->reduce_item( 'select', $retval );
+
+ // Return result
+ return $this->shape_item( $retval );
+ }
+
+ /**
+ * Add an item to the database.
+ *
+ * @since 1.0.0
+ *
+ * @param array $data
+ * @return bool
+ */
+ public function add_item( $data = array() ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // If data includes primary column, check if item already exists
+ if ( ! empty( $data[ $primary ] ) ) {
+
+ // Shape the primary item ID
+ $item_id = $this->shape_item_id( $data[ $primary ] );
+
+ // Get item by ID (from database, not cache)
+ $item = $this->get_item_raw( $primary, $item_id );
+
+ // Bail if item already exists
+ if ( ! empty( $item ) ) {
+ return false;
+ }
+
+ // Set data primary ID to newly shaped ID
+ $data[ $primary ] = $item_id;
+ }
+
+ // Get default values for item (from columns)
+ $item = $this->default_item();
+
+ // Unset the primary key if not part of data array (auto-incremented)
+ if ( empty( $data[ $primary ] ) ) {
+ unset( $item[ $primary ] );
+ }
+
+ // Cut out non-keys for meta
+ $columns = $this->get_column_names();
+ $data = array_merge( $item, $data );
+ $meta = array_diff_key( $data, $columns );
+ $save = array_intersect_key( $data, $columns );
+
+ // Bail if nothing to save
+ if ( empty( $save ) && empty( $meta ) ) {
+ return false;
+ }
+
+ // Get the current time (maybe used by created/modified)
+ $time = $this->get_current_time();
+
+ // If date-created exists, but is empty or default, use the current time
+ $created = $this->get_column_by( array( 'created' => true ) );
+ if ( ! empty( $created ) && ( empty( $save[ $created->name ] ) || ( $save[ $created->name ] === $created->default ) ) ) {
+ $save[ $created->name ] = $time;
+ }
+
+ // If date-modified exists, but is empty or default, use the current time
+ $modified = $this->get_column_by( array( 'modified' => true ) );
+ if ( ! empty( $modified ) && ( empty( $save[ $modified->name ] ) || ( $save[ $modified->name ] === $modified->default ) ) ) {
+ $save[ $modified->name ] = $time;
+ }
+
+ // Try to add
+ $table = $this->get_table_name();
+ $reduce = $this->reduce_item( 'insert', $save );
+ $save = $this->validate_item( $reduce );
+ $result = ! empty( $save )
+ ? $this->get_db()->insert( $table, $save )
+ : false;
+
+ // Bail on failure
+ if ( ! $this->is_success( $result ) ) {
+ return false;
+ }
+
+ // Get the new item ID
+ $item_id = $this->get_db()->insert_id;
+
+ // Maybe save meta keys
+ if ( ! empty( $meta ) ) {
+ $this->save_extra_item_meta( $item_id, $meta );
+ }
+
+ // Update item cache(s)
+ $this->update_item_cache( $item_id );
+
+ // Transition item data
+ $this->transition_item( $save, array(), $item_id );
+
+ // Return result
+ return $item_id;
+ }
+
+ /**
+ * Copy an item in the database to a new item.
+ *
+ * @since 1.1.0
+ *
+ * @param int $item_id
+ * @param array $data
+ * @return bool
+ */
+ public function copy_item( $item_id = 0, $data = array() ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get item by ID (from database, not cache)
+ $item = $this->get_item_raw( $primary, $item_id );
+
+ // Bail if item does not exist
+ if ( empty( $item ) ) {
+ return false;
+ }
+
+ // Cast object to array
+ $save = (array) $item;
+
+ // Maybe merge data with original item
+ if ( ! empty( $data ) && is_array( $data ) ) {
+ $save = array_merge( $save, $data );
+ }
+
+ // Unset the primary key
+ unset( $save[ $primary ] );
+
+ // Return result
+ return $this->add_item( $save );
+ }
+
+ /**
+ * Update an item in the database.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ * @param array $data
+ * @return bool
+ */
+ public function update_item( $item_id = 0, $data = array() ) {
+
+ // Bail early if no data to update
+ if ( empty( $data ) ) {
+ return false;
+ }
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no item ID
+ if ( empty( $item_id ) ) {
+ return false;
+ }
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get item to update (from database, not cache)
+ $item = $this->get_item_raw( $primary, $item_id );
+
+ // Bail if item does not exist to update
+ if ( empty( $item ) ) {
+ return false;
+ }
+
+ // Cast as an array for easier manipulation
+ $item = (array) $item;
+
+ // Unset the primary key from item & data
+ unset(
+ $data[ $primary ],
+ $item[ $primary ]
+ );
+
+ // Slice data that has columns, and cut out non-keys for meta
+ $columns = $this->get_column_names();
+ $data = array_diff_assoc( $data, $item );
+ $meta = array_diff_key( $data, $columns );
+ $save = array_intersect_key( $data, $columns );
+
+ // Maybe save meta keys
+ if ( ! empty( $meta ) ) {
+ $this->save_extra_item_meta( $item_id, $meta );
+ }
+
+ // Bail if nothing to save
+ if ( empty( $save ) ) {
+ return false;
+ }
+
+ // If date-modified exists, use the current time
+ $modified = $this->get_column_by( array( 'modified' => true ) );
+ if ( ! empty( $modified ) ) {
+ $save[ $modified->name ] = $this->get_current_time();
+ }
+
+ // Try to update
+ $table = $this->get_table_name();
+ $reduce = $this->reduce_item( 'update', $save );
+ $save = $this->validate_item( $reduce );
+ $where = array( $primary => $item_id );
+ $result = ! empty( $save )
+ ? $this->get_db()->update( $table, $save, $where )
+ : false;
+
+ // Bail on failure
+ if ( ! $this->is_success( $result ) ) {
+ return false;
+ }
+
+ // Update item cache(s)
+ $this->update_item_cache( $item_id );
+
+ // Transition item data
+ $this->transition_item( $save, $item, $item_id );
+
+ // Return result
+ return $result;
+ }
+
+ /**
+ * Delete an item from the database.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ * @return bool
+ */
+ public function delete_item( $item_id = 0 ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no item ID
+ if ( empty( $item_id ) ) {
+ return false;
+ }
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get item by ID (from database, not cache)
+ $item = $this->get_item_raw( $primary, $item_id );
+
+ // Bail if item does not exist to delete
+ if ( empty( $item ) ) {
+ return false;
+ }
+
+ // Attempt to reduce this item
+ $item = $this->reduce_item( 'delete', $item );
+
+ // Bail if item was reduced to nothing
+ if ( empty( $item ) ) {
+ return false;
+ }
+
+ // Try to delete
+ $table = $this->get_table_name();
+ $where = array( $primary => $item_id );
+ $result = $this->get_db()->delete( $table, $where );
+
+ // Bail on failure
+ if ( ! $this->is_success( $result ) ) {
+ return false;
+ }
+
+ // Clean caches on successful delete
+ $this->delete_all_item_meta( $item_id );
+ $this->clean_item_cache( $item );
+
+ // Return result
+ return $result;
+ }
+
+ /**
+ * Filter an item before it is inserted of updated in the database.
+ *
+ * This method is public to allow subclasses to perform JIT manipulation
+ * of the parameters passed into it.
+ *
+ * @since 1.0.0
+ *
+ * @param array $item
+ * @return array
+ */
+ public function filter_item( $item = array() ) {
+ return (array) apply_filters_ref_array( $this->apply_prefix( "filter_{$this->item_name}_item" ), array( $item, &$this ) );
+ }
+
+ /**
+ * Shape an item from the database into the type of object it always wanted
+ * to be when it grew up.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed ID of item, or row from database
+ * @return mixed False on error, Object of single-object class type on success
+ */
+ private function shape_item( $item = 0 ) {
+
+ // Get the item from an ID
+ if ( is_numeric( $item ) ) {
+ $item = $this->get_item( $item );
+ }
+
+ // Return the item if it's already shaped
+ if ( $item instanceof $this->item_shape ) {
+ return $item;
+ }
+
+ // Shape the item as needed
+ $item = ! empty( $this->item_shape )
+ ? new $this->item_shape( $item )
+ : (object) $item;
+
+ // Return the item object
+ return $item;
+ }
+
+ /**
+ * Validate an item before it is updated in or added to the database.
+ *
+ * @since 1.0.0
+ *
+ * @param array $item
+ * @return array|false False on error, Array of validated values on success
+ */
+ private function validate_item( $item = array() ) {
+
+ // Bail if item is empty or not an array
+ if ( empty( $item ) || ! is_array( $item ) ) {
+ return $item;
+ }
+
+ // Loop through item attributes
+ foreach ( $item as $key => $value ) {
+
+ // Get the column
+ $column = $this->get_column_by( array( 'name' => $key ) );
+
+ // Null value is special for all item keys
+ if ( is_null( $value ) ) {
+
+ // Bail if null is not allowed
+ if ( false === $column->allow_null ) {
+ return false;
+ }
+
+ // Attempt to validate
+ } elseif ( ! empty( $column->validate ) && is_callable( $column->validate ) ) {
+ $validated = call_user_func( $column->validate, $value );
+
+ // Bail if error
+ if ( is_wp_error( $validated ) ) {
+ return false;
+ }
+
+ // Update the value
+ $item[ $key ] = $validated;
+
+ /**
+ * Fallback to using the raw value.
+ *
+ * Note: This may change at a later date, so do not rely on this.
+ * Please always validate all data.
+ */
+ } else {
+ $item[ $key ] = $value;
+ }
+ }
+
+ // Return the validated item
+ return $this->filter_item( $item );
+ }
+
+ /**
+ * Reduce an item down to the keys and values the current user has the
+ * appropriate capabilities to select|insert|update|delete.
+ *
+ * Note that internally, this method works with both arrays and objects of
+ * any type, and also resets the key values. It looks weird, but is
+ * currently by design to protect the integrity of the return value.
+ *
+ * @since 1.0.0
+ *
+ * @param string $method select|insert|update|delete
+ * @param mixed $item Object|Array of keys/values to reduce
+ *
+ * @return mixed Object|Array without keys the current user does not have caps for
+ */
+ private function reduce_item( $method = 'update', $item = array() ) {
+
+ // Bail if item is empty
+ if ( empty( $item ) ) {
+ return $item;
+ }
+
+ // Loop through item attributes
+ foreach ( $item as $key => $value ) {
+
+ // Get capabilities for this column
+ $caps = $this->get_column_field( array( 'name' => $key ), 'caps' );
+
+ // Unset if not explicitly allowed
+ if ( empty( $caps[ $method ] ) || ! current_user_can( $caps[ $method ] ) ) {
+ if ( is_array( $item ) ) {
+ unset( $item[ $key ] );
+ } elseif ( is_object( $item ) ) {
+ $item->{$key} = null;
+ }
+
+ // Set if explicitly allowed
+ } elseif ( is_array( $item ) ) {
+ $item[ $key ] = $value;
+ } elseif ( is_object( $item ) ) {
+ $item->{$key} = $value;
+ }
+ }
+
+ // Return the reduced item
+ return $item;
+ }
+
+ /**
+ * Return an item comprised of all default values.
+ *
+ * This is used by `add_item()` to populate known default values, to ensure
+ * new item data is always what we expect it to be.
+ *
+ * @since 1.0.0
+ *
+ * @return array
+ */
+ private function default_item() {
+
+ // Default return value
+ $retval = array();
+
+ // Get the column names and their defaults
+ $names = $this->get_columns( array(), 'and', 'name' );
+ $defaults = $this->get_columns( array(), 'and', 'default' );
+
+ // Put together an item using default values
+ foreach ( $names as $key => $name ) {
+ $retval[ $name ] = $defaults[ $key ];
+ }
+
+ // Return
+ return $retval;
+ }
+
+ /**
+ * Transition an item when adding or updating.
+ *
+ * This method takes the data being saved, looks for any columns that are
+ * known to transition between values, and fires actions on them.
+ *
+ * @since 1.0.0
+ *
+ * @param array $new_data
+ * @param array $old_data
+ * @param int $item_id
+ * @return array
+ */
+ private function transition_item( $new_data = array(), $old_data = array(), $item_id = 0 ) {
+
+ // Look for transition columns
+ $columns = $this->get_columns( array( 'transition' => true ), 'and', 'name' );
+
+ // Bail if no columns to transition
+ if ( empty( $columns ) ) {
+ return;
+ }
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no item ID
+ if ( empty( $item_id ) ) {
+ return;
+ }
+
+ // If no old value(s), it's new
+ if ( empty( $old_data ) || ! is_array( $old_data ) ) {
+ $old_data = $new_data;
+
+ // Set all old values to "new"
+ foreach ( $old_data as $key => $value ) {
+ $value = 'new';
+ $old_data[ $key ] = $value;
+ }
+ }
+
+ // Compare
+ $keys = array_flip( $columns );
+ $new = array_intersect_key( $new_data, $keys );
+ $old = array_intersect_key( $old_data, $keys );
+
+ // Get the difference
+ $diff = array_diff( $new, $old );
+
+ // Bail if nothing is changing
+ if ( empty( $diff ) ) {
+ return;
+ }
+
+ // Do the actions
+ foreach ( $diff as $key => $value ) {
+ $old_value = $old_data[ $key ];
+ $new_value = $new_data[ $key ];
+ $key_action = $this->apply_prefix( "transition_{$this->item_name}_{$key}" );
+
+ /**
+ * Fires after an object value has transitioned.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $old_value The value being transitioned FROM.
+ * @param mixed $new_value The value being transitioned TO.
+ * @param int $item_id The ID of the item that is transitioning.
+ */
+ do_action( $key_action, $old_value, $new_value, $item_id );
+ }
+ }
+
+ /** Meta ******************************************************************/
+
+ /**
+ * Add meta data to an item.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ * @param string $meta_key
+ * @param string $meta_value
+ * @param string $unique
+ * @return int|false The meta ID on success, false on failure.
+ */
+ protected function add_item_meta( $item_id = 0, $meta_key = '', $meta_value = '', $unique = false ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no meta to add
+ if ( empty( $item_id ) || empty( $meta_key ) ) {
+ return false;
+ }
+
+ // Bail if no meta table exists
+ if ( false === $this->get_meta_table_name() ) {
+ return false;
+ }
+
+ // Get the meta type
+ $meta_type = $this->get_meta_type();
+
+ // Return results of adding meta data
+ return add_metadata( $meta_type, $item_id, $meta_key, $meta_value, $unique );
+ }
+
+ /**
+ * Get meta data for an item.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ * @param string $meta_key
+ * @param bool $single
+ * @return mixed Single metadata value, or array of values
+ */
+ protected function get_item_meta( $item_id = 0, $meta_key = '', $single = false ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no meta was returned
+ if ( empty( $item_id ) || empty( $meta_key ) ) {
+ return false;
+ }
+
+ // Bail if no meta table exists
+ if ( false === $this->get_meta_table_name() ) {
+ return false;
+ }
+
+ // Get the meta type
+ $meta_type = $this->get_meta_type();
+
+ // Return results of getting meta data
+ return get_metadata( $meta_type, $item_id, $meta_key, $single );
+ }
+
+ /**
+ * Update meta data for an item.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ * @param string $meta_key
+ * @param string $meta_value
+ * @param string $prev_value
+ * @return bool True on successful update, false on failure.
+ */
+ protected function update_item_meta( $item_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no meta was returned
+ if ( empty( $item_id ) || empty( $meta_key ) ) {
+ return false;
+ }
+
+ // Bail if no meta table exists
+ if ( false === $this->get_meta_table_name() ) {
+ return false;
+ }
+
+ // Get the meta type
+ $meta_type = $this->get_meta_type();
+
+ // Return results of updating meta data
+ return update_metadata( $meta_type, $item_id, $meta_key, $meta_value, $prev_value );
+ }
+
+ /**
+ * Delete meta data for an item.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ * @param string $meta_key
+ * @param string $meta_value
+ * @param string $delete_all
+ * @return bool True on successful delete, false on failure.
+ */
+ protected function delete_item_meta( $item_id = 0, $meta_key = '', $meta_value = '', $delete_all = false ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no meta was returned
+ if ( empty( $item_id ) || empty( $meta_key ) ) {
+ return false;
+ }
+
+ // Bail if no meta table exists
+ if ( false === $this->get_meta_table_name() ) {
+ return false;
+ }
+
+ // Get the meta type
+ $meta_type = $this->get_meta_type();
+
+ // Return results of deleting meta data
+ return delete_metadata( $meta_type, $item_id, $meta_key, $meta_value, $delete_all );
+ }
+
+ /**
+ * Get registered meta data keys.
+ *
+ * @since 1.0.0
+ *
+ * @param string $object_subtype The sub-type of meta keys
+ *
+ * @return array
+ */
+ private function get_registered_meta_keys( $object_subtype = '' ) {
+
+ // Get the object type
+ $object_type = $this->get_meta_type();
+
+ // Return the keys
+ return get_registered_meta_keys( $object_type, $object_subtype );
+ }
+
+ /**
+ * Maybe update meta values on item update/save.
+ *
+ * @since 1.0.0
+ *
+ * @param array $meta
+ */
+ private function save_extra_item_meta( $item_id = 0, $meta = array() ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if there is no bulk meta to save
+ if ( empty( $item_id ) || empty( $meta ) ) {
+ return;
+ }
+
+ // Bail if no meta table exists
+ if ( false === $this->get_meta_table_name() ) {
+ return;
+ }
+
+ // Only save registered keys
+ $keys = $this->get_registered_meta_keys();
+ $meta = array_intersect_key( $meta, $keys );
+
+ // Bail if no registered meta keys
+ if ( empty( $meta ) ) {
+ return;
+ }
+
+ // Save or delete meta data
+ foreach ( $meta as $key => $value ) {
+ ! empty( $value )
+ ? $this->update_item_meta( $item_id, $key, $value )
+ : $this->delete_item_meta( $item_id, $key );
+ }
+ }
+
+ /**
+ * Delete all meta data for an item.
+ *
+ * @since 1.0.0
+ *
+ * @param int $item_id
+ */
+ private function delete_all_item_meta( $item_id = 0 ) {
+
+ // Shape the item ID
+ $item_id = $this->shape_item_id( $item_id );
+
+ // Bail if no item ID
+ if ( empty( $item_id ) ) {
+ return;
+ }
+
+ // Get the meta table name
+ $table = $this->get_meta_table_name();
+
+ // Bail if no meta table exists
+ if ( empty( $table ) ) {
+ return;
+ }
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Guess the item ID column for the meta table
+ $item_id_column = $this->apply_prefix( "{$this->item_name}_{$primary}" );
+
+ // Get meta IDs
+ $query = "SELECT meta_id FROM {$table} WHERE {$item_id_column} = %d";
+ $prepared = $this->get_db()->prepare( $query, $item_id );
+ $meta_ids = $this->get_db()->get_col( $prepared );
+
+ // Bail if no meta IDs to delete
+ if ( empty( $meta_ids ) ) {
+ return;
+ }
+
+ // Get the meta type
+ $meta_type = $this->get_meta_type();
+
+ // Delete all meta data for this item ID
+ foreach ( $meta_ids as $mid ) {
+ delete_metadata_by_mid( $meta_type, $mid );
+ }
+ }
+
+ /**
+ * Get the meta table for this query.
+ *
+ * Forked from WordPress\_get_meta_table() so it can be more accurately
+ * predicted in a future iteration and default to returning false.
+ *
+ * @since 1.0.0
+ *
+ * @return mixed Table name if exists, False if not
+ */
+ private function get_meta_table_name() {
+
+ // Get the meta-type
+ $type = $this->get_meta_type();
+
+ // Append "meta" to end of meta-type
+ $table_name = "{$type}meta";
+
+ // Variable'ize the database interface, to use inside empty()
+ $db = $this->get_db();
+
+ // If not empty, return table name
+ if ( ! empty( $db->{$table_name} ) ) {
+ return $db->{$table_name};
+ }
+
+ // Default return false
+ return false;
+ }
+
+ /**
+ * Get the meta type for this query.
+ *
+ * This method exists to reduce some duplication for now. Future iterations
+ * will likely use Column::relationships to
+ *
+ * @since 1.1.0
+ *
+ * @return string
+ */
+ private function get_meta_type() {
+ return $this->apply_prefix( $this->item_name );
+ }
+
+ /** Cache *****************************************************************/
+
+ /**
+ * Get cache key from query_vars and query_var_defaults.
+ *
+ * @since 1.0.0
+ *
+ * @return string
+ */
+ private function get_cache_key( $group = '' ) {
+
+ // Slice query vars
+ $slice = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
+
+ // Unset `fields` so it does not effect the cache key
+ unset( $slice['fields'] );
+
+ // Setup key & last_changed
+ $key = md5( serialize( $slice ) );
+ $last_changed = $this->get_last_changed_cache( $group );
+
+ // Concatenate and return cache key
+ return "get_{$this->item_name_plural}:{$key}:{$last_changed}";
+ }
+
+ /**
+ * Get the cache group, or fallback to the primary one.
+ *
+ * @since 1.0.0
+ *
+ * @param string $group
+ * @return string
+ */
+ private function get_cache_group( $group = '' ) {
+
+ // Get the primary column
+ $primary = $this->get_primary_column_name();
+
+ // Default return value
+ $retval = $this->cache_group;
+
+ // Only allow non-primary groups
+ if ( ! empty( $group ) && ( $group !== $primary ) ) {
+ $retval = $group;
+ }
+
+ // Return the group
+ return $retval;
+ }
+
+ /**
+ * Get array of which database columns have uniquely cached groups.
+ *
+ * @since 1.0.0
+ *
+ * @return array
+ */
+ private function get_cache_groups() {
+
+ // Return value
+ $cache_groups = array();
+
+ // Get the cache groups
+ $groups = $this->get_columns( array( 'cache_key' => true ), 'and', 'name' );
+
+ if ( ! empty( $groups ) ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Setup return values
+ foreach ( $groups as $name ) {
+ if ( $primary !== $name ) {
+ $cache_groups[ $name ] = "{$this->cache_group}-by-{$name}";
+ } else {
+ $cache_groups[ $name ] = $this->cache_group;
+ }
+ }
+ }
+
+ // Return cache groups array
+ return $cache_groups;
+ }
+
+ /**
+ * Maybe prime item & item-meta caches by querying 1 time for all un-cached
+ * items.
+ *
+ * Accepts a single ID, or an array of IDs.
+ *
+ * The reason this accepts only IDs is because it gets called immediately
+ * after an item is inserted in the database, but before items have been
+ * "shaped" into proper objects, so object properties may not be set yet.
+ *
+ * @since 1.0.0
+ *
+ * @param array $item_ids
+ * @param bool $force
+ *
+ * @return bool False if empty
+ */
+ private function prime_item_caches( $item_ids = array(), $force = false ) {
+
+ // Bail if no items to cache
+ if ( empty( $item_ids ) ) {
+ return false;
+ }
+
+ // Accepts single values, so cast to array
+ $item_ids = (array) $item_ids;
+
+ // Update item caches
+ if ( ! empty( $force ) || ! empty( $this->query_vars['update_item_cache'] ) ) {
+
+ // Look for non-cached IDs
+ $ids = $this->get_non_cached_ids( $item_ids, $this->cache_group );
+
+ // Bail if IDs are cached
+ if ( empty( $ids ) ) {
+ return false;
+ }
+
+ // Get query parts
+ $table = $this->get_table_name();
+ $primary = $this->get_primary_column_name();
+
+ // Query database
+ $query = "SELECT * FROM {$table} WHERE {$primary} IN (%s)";
+ $ids = implode( ',', array_map( 'absint', $ids ) );
+ $prepare = sprintf( $query, $ids );
+ $results = $this->get_db()->get_results( $prepare );
+
+ // Update item cache(s)
+ $this->update_item_cache( $results );
+ }
+
+ // Update meta data caches
+ if ( ! empty( $this->query_vars['update_meta_cache'] ) ) {
+ $singular = rtrim( $this->table_name, 's' ); // sic
+ update_meta_cache( $singular, $item_ids );
+ }
+ }
+
+ /**
+ * Update the cache for an item. Does not update item-meta cache.
+ *
+ * Accepts a single object, or an array of objects.
+ *
+ * The reason this does not accept ID's is because this gets called
+ * after an item is already updated in the database, so we want to avoid
+ * querying for it again. It's just safer this way.
+ *
+ * @since 1.0.0
+ *
+ * @param array $items
+ */
+ private function update_item_cache( $items = array() ) {
+
+ // Maybe query for single item
+ if ( is_numeric( $items ) ) {
+
+ // Get the primary column name
+ $primary = $this->get_primary_column_name();
+
+ // Get item by ID (from database, not cache)
+ $items = $this->get_item_raw( $primary, $items );
+ }
+
+ // Bail if no items to cache
+ if ( empty( $items ) ) {
+ return false;
+ }
+
+ // Make sure items are an array (without casting objects to arrays)
+ if ( ! is_array( $items ) ) {
+ $items = array( $items );
+ }
+
+ // Get the cache groups
+ $groups = $this->get_cache_groups();
+
+ // Loop through all items and cache them
+ foreach ( $items as $item ) {
+
+ // Skip if item is not an object
+ if ( ! is_object( $item ) ) {
+ continue;
+ }
+
+ // Loop through groups and set cache
+ if ( ! empty( $groups ) ) {
+ foreach ( $groups as $key => $group ) {
+ $this->cache_set( $item->{$key}, $item, $group );
+ }
+ }
+ }
+
+ // Update last changed
+ $this->update_last_changed_cache();
+ }
+
+ /**
+ * Clean the cache for an item. Does not clean item-meta.
+ *
+ * Accepts a single object, or an array of objects.
+ *
+ * The reason this does not accept ID's is because this gets called
+ * after an item is already deleted from the database, so it cannot be
+ * queried and may not exist in the cache. It's just safer this way.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $items Single object item, or Array of object items
+ *
+ * @return bool
+ */
+ private function clean_item_cache( $items = array() ) {
+
+ // Bail if no items to clean
+ if ( empty( $items ) ) {
+ return false;
+ }
+
+ // Make sure items are an array
+ if ( ! is_array( $items ) ) {
+ $items = array( $items );
+ }
+
+ // Get the cache groups
+ $groups = $this->get_cache_groups();
+
+ // Loop through all items and clean them
+ foreach ( $items as $item ) {
+
+ // Skip if item is not an object
+ if ( ! is_object( $item ) ) {
+ continue;
+ }
+
+ // Loop through groups and delete cache
+ if ( ! empty( $groups ) ) {
+ foreach ( $groups as $key => $group ) {
+ $this->cache_delete( $item->{$key}, $group );
+ }
+ }
+ }
+
+ // Update last changed
+ $this->update_last_changed_cache();
+ }
+
+ /**
+ * Update the last_changed key for the cache group.
+ *
+ * @since 1.0.0
+ *
+ * @return string The last time a cache group was changed.
+ */
+ private function update_last_changed_cache( $group = '' ) {
+
+ // Fallback to microtime
+ if ( empty( $this->last_changed ) ) {
+ $this->set_last_changed();
+ }
+
+ // Set the last changed time for this cache group
+ $this->cache_set( 'last_changed', $this->last_changed, $group );
+
+ // Return the last changed time
+ return $this->last_changed;
+ }
+
+ /**
+ * Get the last_changed key for a cache group.
+ *
+ * @since 1.0.0
+ *
+ * @param string $group Cache group. Defaults to $this->cache_group
+ *
+ * @return string The last time a cache group was changed.
+ */
+ private function get_last_changed_cache( $group = '' ) {
+
+ // Get the last changed cache value
+ $last_changed = $this->cache_get( 'last_changed', $group );
+
+ // Maybe update the last changed value
+ if ( false === $last_changed ) {
+ $last_changed = $this->update_last_changed_cache( $group );
+ }
+
+ // Return the last changed value for the cache group
+ return $last_changed;
+ }
+
+ /**
+ * Get array of non-cached item IDs.
+ *
+ * @since 1.0.0
+ *
+ * @param array $item_ids Array of item IDs
+ * @param string $group Cache group. Defaults to $this->cache_group
+ *
+ * @return array
+ */
+ private function get_non_cached_ids( $item_ids = array(), $group = '' ) {
+
+ // Default return value
+ $retval = array();
+
+ // Bail if no item IDs
+ if ( empty( $item_ids ) ) {
+ return $retval;
+ }
+
+ // Loop through item IDs
+ foreach ( $item_ids as $id ) {
+
+ // Shape the item ID
+ $id = $this->shape_item_id( $id );
+
+ // Add to return value if not cached
+ if ( false === $this->cache_get( $id, $group ) ) {
+ $retval[] = $id;
+ }
+ }
+
+ // Return array of IDs
+ return $retval;
+ }
+
+ /**
+ * Add a cache value for a key and group.
+ *
+ * @since 1.0.0
+ *
+ * @param string $key Cache key.
+ * @param mixed $value Cache value.
+ * @param string $group Cache group. Defaults to $this->cache_group
+ * @param int $expire Expiration.
+ */
+ private function cache_add( $key = '', $value = '', $group = '', $expire = 0 ) {
+
+ // Bail if cache invalidation is suspended
+ if ( wp_suspend_cache_addition() ) {
+ return;
+ }
+
+ // Bail if no cache key
+ if ( empty( $key ) ) {
+ return;
+ }
+
+ // Get the cache group
+ $group = $this->get_cache_group( $group );
+
+ // Add to the cache
+ wp_cache_add( $key, $value, $group, $expire );
+ }
+
+ /**
+ * Get a cache value for a key and group.
+ *
+ * @since 1.0.0
+ *
+ * @param string $key Cache key.
+ * @param string $group Cache group. Defaults to $this->cache_group
+ * @param bool $force
+ */
+ private function cache_get( $key = '', $group = '', $force = false ) {
+
+ // Bail if no cache key
+ if ( empty( $key ) ) {
+ return;
+ }
+
+ // Get the cache group
+ $group = $this->get_cache_group( $group );
+
+ // Return from the cache
+ return wp_cache_get( $key, $group, $force );
+ }
+
+ /**
+ * Set a cache value for a key and group.
+ *
+ * @since 1.0.0
+ *
+ * @param string $key Cache key.
+ * @param mixed $value Cache value.
+ * @param string $group Cache group. Defaults to $this->cache_group
+ * @param int $expire Expiration.
+ */
+ private function cache_set( $key = '', $value = '', $group = '', $expire = 0 ) {
+
+ // Bail if cache invalidation is suspended
+ if ( wp_suspend_cache_addition() ) {
+ return;
+ }
+
+ // Bail if no cache key
+ if ( empty( $key ) ) {
+ return;
+ }
+
+ // Get the cache group
+ $group = $this->get_cache_group( $group );
+
+ // Update the cache
+ wp_cache_set( $key, $value, $group, $expire );
+ }
+
+ /**
+ * Delete a cache key for a group.
+ *
+ * @since 1.0.0
+ *
+ * @global bool $_wp_suspend_cache_invalidation
+ *
+ * @param string $key Cache key.
+ * @param string $group Cache group. Defaults to $this->cache_group
+ */
+ private function cache_delete( $key = '', $group = '' ) {
+ global $_wp_suspend_cache_invalidation;
+
+ // Bail if cache invalidation is suspended
+ if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
+ return;
+ }
+
+ // Bail if no cache key
+ if ( empty( $key ) ) {
+ return;
+ }
+
+ // Get the cache group
+ $group = $this->get_cache_group( $group );
+
+ // Delete the cache
+ wp_cache_delete( $key, $group );
+ }
+
+ /**
+ * Fetch raw results directly from the database.
+ *
+ * @since 1.0.0
+ *
+ * @param array $cols Columns for `SELECT`.
+ * @param array $where_cols Where clauses. Each key-value pair in the array
+ * represents a column and a comparison.
+ * @param int $limit Optional. LIMIT value. Default 25.
+ * @param null $offset Optional. OFFSET value. Default null.
+ * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
+ * Default OBJECT.
+ * With one of the first three, return an array of
+ * rows indexed from 0 by SQL result row number.
+ * Each row is an associative array (column => value, ...),
+ * a numerically indexed array (0 => value, ...),
+ * or an object. ( ->column = value ), respectively.
+ * With OBJECT_K, return an associative array of
+ * row objects keyed by the value of each row's
+ * first column's value.
+ *
+ * @return array|object|null Database query results.
+ */
+ public function get_results( $cols = array(), $where_cols = array(), $limit = 25, $offset = null, $output = OBJECT ) {
+
+ // Bail if no columns have been passed
+ if ( empty( $cols ) ) {
+ return null;
+ }
+
+ // Fetch all the columns for the table being queried
+ $column_names = $this->get_column_names();
+
+ // Ensure valid column names have been passed for the `SELECT` clause
+ foreach ( $cols as $index => $column ) {
+ if ( ! array_key_exists( $column, $column_names ) ) {
+ unset( $cols[ $index ] );
+ }
+ }
+
+ // Columns to retrieve
+ $columns = implode( ',', $cols );
+
+ // Get the table name
+ $table = $this->get_table_name();
+
+ // Setup base query
+ $query = implode( ' ', array(
+ "SELECT",
+ $columns,
+ "FROM {$table} {$this->table_alias}",
+ "WHERE 1=1"
+ ) );
+
+ // Ensure valid columns have been passed for the `WHERE` clause
+ if ( ! empty( $where_cols ) ) {
+
+ // Get keys from where columns
+ $columns = array_keys( $where_cols );
+
+ // Loop through columns and unset any invalid names
+ foreach ( $columns as $index => $column ) {
+ if ( ! array_key_exists( $column, $column_names ) ) {
+ unset( $where_cols[ $index ] );
+ }
+ }
+
+ // Parse WHERE clauses
+ foreach ( $where_cols as $column => $compare ) {
+
+ // Basic WHERE clause
+ if ( ! is_array( $compare ) ) {
+ $pattern = $this->get_column_field( array( 'name' => $column ), 'pattern', '%s' );
+ $statement = " AND {$this->table_alias}.{$column} = {$pattern} ";
+ $query .= $this->get_db()->prepare( $statement, $compare );
+
+ // More complex WHERE clause
+ } else {
+ $value = isset( $compare['value'] )
+ ? $compare['value']
+ : false;
+
+ // Skip if a value was not provided
+ if ( false === $value ) {
+ continue;
+ }
+
+ // Default compare clause to equals
+ $compare_clause = isset( $compare['compare_query'] )
+ ? trim( strtoupper( $compare['compare_query'] ) )
+ : '=';
+
+ // Array (unprepared)
+ if ( is_array( $compare['value'] ) ) {
+
+ // Default to IN if clause not specified
+ if ( ! in_array( $compare_clause, array( 'IN', 'NOT IN', 'BETWEEN' ), true ) ) {
+ $compare_clause = 'IN';
+ }
+
+ // Parse & escape for IN and NOT IN
+ if ( 'IN' === $compare_clause || 'NOT IN' === $compare_clause ) {
+ $value = "('" . implode( "','", $this->get_db()->_escape( $compare['value'] ) ) . "')";
+
+ // Parse & escape for BETWEEN
+ } elseif ( is_array( $value ) && 2 === count( $value ) && 'BETWEEN' === $compare_clause ) {
+ $_this = $this->get_db()->_escape( $value[0] );
+ $_that = $this->get_db()->_escape( $value[1] );
+ $value = " {$_this} AND {$_that} ";
+ }
+ }
+
+ // Add WHERE clause
+ $query .= " AND {$this->table_alias}.{$column} {$compare_clause} {$value} ";
+ }
+ }
+ }
+
+ // Maybe set an offset
+ if ( ! empty( $offset ) ) {
+ $values = explode( ',', $offset );
+ $values = array_filter( $values, 'intval' );
+ $offset = implode( ',', $values );
+ $query .= " OFFSET {$offset} ";
+ }
+
+ // Maybe set a limit
+ if ( ! empty( $limit ) && ( $limit > 0 ) ) {
+ $limit = intval( $limit );
+ $query .= " LIMIT {$limit} ";
+ }
+
+ // Execute query
+ $results = $this->get_db()->get_results( $query, $output );
+
+ // Return results
+ return $results;
+ }
+}
diff --git a/inc/Dependencies/Database/Row.php b/inc/Dependencies/Database/Row.php
new file mode 100644
index 0000000..1614d6b
--- /dev/null
+++ b/inc/Dependencies/Database/Row.php
@@ -0,0 +1,65 @@
+init( $item );
+ }
+ }
+
+ /**
+ * Initialize class properties based on data array.
+ *
+ * @since 1.0.0
+ *
+ * @param array $data
+ */
+ private function init( $data = array() ) {
+ $this->set_vars( $data );
+ }
+
+ /**
+ * Determines whether the current row exists.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function exists() {
+ return ! empty( $this->id );
+ }
+}
diff --git a/inc/Dependencies/Database/Schema.php b/inc/Dependencies/Database/Schema.php
new file mode 100644
index 0000000..a7ed3e3
--- /dev/null
+++ b/inc/Dependencies/Database/Schema.php
@@ -0,0 +1,88 @@
+columns ) || ! is_array( $this->columns ) ) {
+ return;
+ }
+
+ // Juggle original columns array
+ $columns = $this->columns;
+ $this->columns = array();
+
+ // Loop through columns and create objects from them
+ foreach ( $columns as $column ) {
+ if ( is_array( $column ) ) {
+ $this->columns[] = new Column( $column );
+ } elseif ( $column instanceof Column ) {
+ $this->columns[] = $column;
+ }
+ }
+ }
+
+ /**
+ * Return the schema in string form.
+ *
+ * @since 1.0.0
+ *
+ * @return string Calls get_create_string() on every column.
+ */
+ protected function to_string() {
+
+ // Default return value
+ $retval = '';
+
+ // Bail if no columns to convert
+ if ( empty( $this->columns ) ) {
+ return $retval;
+ }
+
+ // Loop through columns...
+ foreach ( $this->columns as $column_info ) {
+ if ( method_exists( $column_info, 'get_create_string' ) ) {
+ $retval .= '\n' . $column_info->get_create_string() . ', ';
+ }
+ }
+
+ // Return the string
+ return $retval;
+ }
+}
diff --git a/inc/Dependencies/Database/Table.php b/inc/Dependencies/Database/Table.php
new file mode 100644
index 0000000..e85054e
--- /dev/null
+++ b/inc/Dependencies/Database/Table.php
@@ -0,0 +1,998 @@
+ value array of versions => methods.
+ *
+ * @since 1.0.0
+ * @var array
+ */
+ protected $upgrades = array();
+
+ /** Methods ***************************************************************/
+
+ /**
+ * Hook into queries, admin screens, and more!
+ *
+ * @since 1.0.0
+ */
+ public function __construct() {
+
+ // Setup the database table
+ $this->setup();
+
+ // Bail if setup failed
+ if ( empty( $this->name ) || empty( $this->db_version_key ) ) {
+ return;
+ }
+
+ // Add the table to the database interface
+ $this->set_db_interface();
+
+ // Set the database schema
+ $this->set_schema();
+
+ // Add hooks
+ $this->add_hooks();
+
+ // Maybe force upgrade if testing
+ if ( $this->is_testing() ) {
+ $this->maybe_upgrade();
+ }
+ }
+
+ /**
+ * Compatibility for clone() method for PHP versions less than 7.0.
+ *
+ * See: https://github.com/sugarcalendar/core/issues/105
+ *
+ * This shim will be removed at a later date.
+ *
+ * @since 2.0.20
+ *
+ * @param string $function
+ * @param array $args
+ */
+ public function __call( $function = '', $args = array() ) {
+ if ( 'clone' === $function ) {
+ call_user_func_array( array( $this, '_clone' ), $args );
+ }
+ }
+
+ /** Abstract **************************************************************/
+
+ /**
+ * Setup this database table.
+ *
+ * @since 1.0.0
+ */
+ protected abstract function set_schema();
+
+ /** Multisite *************************************************************/
+
+ /**
+ * Update table version & references.
+ *
+ * Hooked to the "switch_blog" action.
+ *
+ * @since 1.0.0
+ *
+ * @param int $site_id The site being switched to
+ */
+ public function switch_blog( $site_id = 0 ) {
+
+ // Update DB version based on the current site
+ if ( ! $this->is_global() ) {
+ $this->db_version = get_blog_option( $site_id, $this->db_version_key, false );
+ }
+
+ // Update interface for switched site
+ $this->set_db_interface();
+ }
+
+ /** Public Helpers ********************************************************/
+
+ /**
+ * Maybe upgrade the database table. Handles creation & schema changes.
+ *
+ * Hooked to the `admin_init` action.
+ *
+ * @since 1.0.0
+ */
+ public function maybe_upgrade() {
+
+ // Bail if not upgradeable
+ if ( ! $this->is_upgradeable() ) {
+ return;
+ }
+
+ // Bail if upgrade not needed
+ if ( ! $this->needs_upgrade() ) {
+ return;
+ }
+
+ // Upgrade
+ if ( $this->exists() ) {
+ $this->upgrade();
+
+ // Install
+ } else {
+ $this->install();
+ }
+ }
+
+ /**
+ * Return whether this table needs an upgrade.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $version Database version to check if upgrade is needed
+ *
+ * @return bool True if table needs upgrading. False if not.
+ */
+ public function needs_upgrade( $version = false ) {
+
+ // Use the current table version if none was passed
+ if ( empty( $version ) ) {
+ $version = $this->version;
+ }
+
+ // Get the current database version
+ $this->get_db_version();
+
+ // Is the database table up to date?
+ $is_current = version_compare( $this->db_version, $version, '>=' );
+
+ // Return false if current, true if out of date
+ return ( true === $is_current )
+ ? false
+ : true;
+ }
+
+ /**
+ * Return whether this table can be upgraded.
+ *
+ * @since 1.0.0
+ *
+ * @return bool True if table can be upgraded. False if not.
+ */
+ public function is_upgradeable() {
+
+ // Bail if global and upgrading global tables is not allowed
+ if ( $this->is_global() && ! wp_should_upgrade_global_tables() ) {
+ return false;
+ }
+
+ // Kinda weird, but assume it is
+ return true;
+ }
+
+ /**
+ * Return the current table version from the database.
+ *
+ * This is public method for accessing a private variable so that it cannot
+ * be externally modified.
+ *
+ * @since 1.0.0
+ *
+ * @return string
+ */
+ public function get_version() {
+ $this->get_db_version();
+
+ return $this->db_version;
+ }
+
+ /**
+ * Install a database table
+ *
+ * Creates the table and sets the version information if successful.
+ *
+ * @since 1.0.0
+ */
+ public function install() {
+
+ // Try to create the table
+ $created = $this->create();
+
+ // Set the DB version if create was successful
+ if ( true === $created ) {
+ $this->set_db_version();
+ }
+ }
+
+ /**
+ * Uninstall a database table
+ *
+ * Drops the table and deletes the version information if successful and/or
+ * the table does not exist anymore.
+ *
+ * @since 1.0.0
+ */
+ public function uninstall() {
+
+ // Try to drop the table
+ $dropped = $this->drop();
+
+ // Delete the DB version if drop was successful or table does not exist
+ if ( ( true === $dropped ) || ! $this->exists() ) {
+ $this->delete_db_version();
+ }
+ }
+
+ /** Public Management *****************************************************/
+
+ /**
+ * Check if table already exists.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function exists() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "SHOW TABLES LIKE %s";
+ $like = $db->esc_like( $this->table_name );
+ $prepared = $db->prepare( $query, $like );
+ $result = $db->get_var( $prepared );
+
+ // Does the table exist?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Get columns from table.
+ *
+ * @since 1.2.0
+ *
+ * @return array
+ */
+ public function columns() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "SHOW FULL COLUMNS FROM {$this->table_name}";
+ $result = $db->get_results( $query );
+
+ // Return the results
+ return $this->is_success( $result )
+ ? $result
+ : false;
+ }
+
+ /**
+ * Create the table.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function create() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "CREATE TABLE {$this->table_name} ( {$this->schema} ) {$this->charset_collation}";
+ $result = $db->query( $query );
+
+ // Was the table created?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Drop the database table.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function drop() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "DROP TABLE {$this->table_name}";
+ $result = $db->query( $query );
+
+ // Did the table get dropped?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Truncate the database table.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function truncate() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "TRUNCATE TABLE {$this->table_name}";
+ $result = $db->query( $query );
+
+ // Did the table get truncated?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Delete all items from the database table.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function delete_all() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "DELETE FROM {$this->table_name}";
+ $result = $db->query( $query );
+
+ // Return the results
+ return $result;
+ }
+
+ /**
+ * Clone this database table.
+ *
+ * Pair with copy().
+ *
+ * @since 1.1.0
+ *
+ * @param string $new_table_name The name of the new table, without prefix
+ *
+ * @return bool
+ */
+ public function _clone( $new_table_name = '' ) {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Sanitize the new table name
+ $table_name = $this->sanitize_table_name( $new_table_name );
+
+ // Bail if new table name is invalid
+ if ( empty( $table_name ) ) {
+ return false;
+ }
+
+ // Query statement
+ $table = $this->apply_prefix( $table_name );
+ $query = "CREATE TABLE {$table} LIKE {$this->table_name}";
+ $result = $db->query( $query );
+
+ // Did the table get cloned?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Copy the contents of this table to a new table.
+ *
+ * Pair with clone().
+ *
+ * @since 1.1.0
+ *
+ * @param string $new_table_name The name of the new table, without prefix
+ *
+ * @return bool
+ */
+ public function copy( $new_table_name = '' ) {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Sanitize the new table name
+ $table_name = $this->sanitize_table_name( $new_table_name );
+
+ // Bail if new table name is invalid
+ if ( empty( $table_name ) ) {
+ return false;
+ }
+
+ // Query statement
+ $table = $this->apply_prefix( $table_name );
+ $query = "INSERT INTO {$table} SELECT * FROM {$this->table_name}";
+ $result = $db->query( $query );
+
+ // Did the table get copied?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Count the number of items in the database table.
+ *
+ * @since 1.0.0
+ *
+ * @return int
+ */
+ public function count() {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return 0;
+ }
+
+ // Query statement
+ $query = "SELECT COUNT(*) FROM {$this->table_name}";
+ $result = $db->get_var( $query );
+
+ // Query success/fail
+ return intval( $result );
+ }
+
+ /**
+ * Check if column already exists.
+ *
+ * @since 1.0.0
+ *
+ * @param string $name Value
+ *
+ * @return bool
+ */
+ public function column_exists( $name = '' ) {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Query statement
+ $query = "SHOW COLUMNS FROM {$this->table_name} LIKE %s";
+ $like = $db->esc_like( $name );
+ $prepared = $db->prepare( $query, $like );
+ $result = $db->query( $prepared );
+
+ // Does the column exist?
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Check if index already exists.
+ *
+ * @since 1.0.0
+ *
+ * @param string $name Value
+ * @param string $column Column name
+ *
+ * @return bool
+ */
+ public function index_exists( $name = '', $column = 'Key_name' ) {
+
+ // Get the database interface
+ $db = $this->get_db();
+
+ // Bail if no database interface is available
+ if ( empty( $db ) ) {
+ return false;
+ }
+
+ // Limit $column to Key or Column name, until we can do better
+ if ( ! in_array( $column, array( 'Key_name', 'Column_name' ), true ) ) {
+ $column = 'Key_name';
+ }
+
+ // Query statement
+ $query = "SHOW INDEXES FROM {$this->table_name} WHERE {$column} LIKE %s";
+ $like = $db->esc_like( $name );
+ $prepared = $db->prepare( $query, $like );
+ $result = $db->query( $prepared );
+
+ // Does the index exist?
+ return $this->is_success( $result );
+ }
+
+ /** Upgrades **************************************************************/
+
+ /**
+ * Upgrade this database table.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ public function upgrade() {
+
+ // Get pending upgrades
+ $upgrades = $this->get_pending_upgrades();
+
+ // Bail if no upgrades
+ if ( empty( $upgrades ) ) {
+ $this->set_db_version();
+
+ // Return, without failure
+ return true;
+ }
+
+ // Default result
+ $result = false;
+
+ // Try to do the upgrades
+ foreach ( $upgrades as $version => $callback ) {
+
+ // Do the upgrade
+ $result = $this->upgrade_to( $version, $callback );
+
+ // Bail if an error occurs, to avoid skipping upgrades
+ if ( ! $this->is_success( $result ) ) {
+ return false;
+ }
+ }
+
+ // Success/fail
+ return $this->is_success( $result );
+ }
+
+ /**
+ * Return array of upgrades that still need to run.
+ *
+ * @since 1.1.0
+ *
+ * @return array Array of upgrade callbacks, keyed by their db version.
+ */
+ public function get_pending_upgrades() {
+
+ // Default return value
+ $upgrades = array();
+
+ // Bail if no upgrades, or no database version to compare to
+ if ( empty( $this->upgrades ) || empty( $this->db_version ) ) {
+ return $upgrades;
+ }
+
+ // Loop through all upgrades, and pick out the ones that need doing
+ foreach ( $this->upgrades as $version => $callback ) {
+ if ( true === version_compare( $version, $this->db_version, '>' ) ) {
+ $upgrades[ $version ] = $callback;
+ }
+ }
+
+ // Return
+ return $upgrades;
+ }
+
+ /**
+ * Upgrade to a specific database version.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $version Database version to check if upgrade is needed
+ * @param string $callback Callback function or class method to call
+ *
+ * @return bool
+ */
+ public function upgrade_to( $version = '', $callback = '' ) {
+
+ // Bail if no upgrade is needed
+ if ( ! $this->needs_upgrade( $version ) ) {
+ return false;
+ }
+
+ // Allow self-named upgrade callbacks
+ if ( empty( $callback ) ) {
+ $callback = $version;
+ }
+
+ // Is the callback... callable?
+ $callable = $this->get_callable( $callback );
+
+ // Bail if no callable upgrade was found
+ if ( empty( $callable ) ) {
+ return false;
+ }
+
+ // Do the upgrade
+ $result = call_user_func( $callable );
+ $success = $this->is_success( $result );
+
+ // Bail if upgrade failed
+ if ( true !== $success ) {
+ return false;
+ }
+
+ // Set the database version to this successful version
+ $this->set_db_version( $version );
+
+ // Return success
+ return true;
+ }
+
+ /** Private ***************************************************************/
+
+ /**
+ * Setup the necessary table variables.
+ *
+ * @since 1.0.0
+ */
+ private function setup() {
+
+ // Bail if no database interface is available
+ if ( ! $this->get_db() ) {
+ return;
+ }
+
+ // Sanitize the database table name
+ $this->name = $this->sanitize_table_name( $this->name );
+
+ // Bail if database table name was garbage
+ if ( false === $this->name ) {
+ return;
+ }
+
+ // Separator
+ $glue = '_';
+
+ // Setup the prefixed name
+ $this->prefixed_name = $this->apply_prefix( $this->name, $glue );
+
+ // Maybe create database key
+ if ( empty( $this->db_version_key ) ) {
+ $this->db_version_key = implode(
+ $glue,
+ array(
+ sanitize_key( $this->db_global ),
+ $this->prefixed_name,
+ 'version'
+ )
+ );
+ }
+ }
+
+ /**
+ * Set this table up in the database interface.
+ *
+ * This must be done directly because the database interface does not
+ * have a common mechanism for manipulating them safely.
+ *
+ * @since 1.0.0
+ */
+ private function set_db_interface() {
+
+ // Get the database once, to avoid duplicate function calls
+ $db = $this->get_db();
+
+ // Bail if no database
+ if ( empty( $db ) ) {
+ return;
+ }
+
+ // Set variables for global tables
+ if ( $this->is_global() ) {
+ $site_id = 0;
+ $tables = 'ms_global_tables';
+
+ // Set variables for per-site tables
+ } else {
+ $site_id = null;
+ $tables = 'tables';
+ }
+
+ // Set the table prefix and prefix the table name
+ $this->table_prefix = $db->get_blog_prefix( $site_id );
+
+ // Get the prefixed table name
+ $prefixed_table_name = "{$this->table_prefix}{$this->prefixed_name}";
+
+ // Set the database interface
+ $db->{$this->prefixed_name} = $this->table_name = $prefixed_table_name;
+
+ // Create the array if it does not exist
+ if ( ! isset( $db->{$tables} ) ) {
+ $db->{$tables} = array();
+ }
+
+ // Add the table to the global table array
+ $db->{$tables}[] = $this->prefixed_name;
+
+ // Charset
+ if ( ! empty( $db->charset ) ) {
+ $this->charset_collation = "DEFAULT CHARACTER SET {$db->charset}";
+ }
+
+ // Collation
+ if ( ! empty( $db->collate ) ) {
+ $this->charset_collation .= " COLLATE {$db->collate}";
+ }
+ }
+
+ /**
+ * Set the database version for the table.
+ *
+ * @since 1.0.0
+ *
+ * @param mixed $version Database version to set when upgrading/creating
+ */
+ private function set_db_version( $version = '' ) {
+
+ // If no version is passed during an upgrade, use the current version
+ if ( empty( $version ) ) {
+ $version = $this->version;
+ }
+
+ // Update the DB version
+ $this->is_global()
+ ? update_network_option( get_main_network_id(), $this->db_version_key, $version )
+ : update_option( $this->db_version_key, $version );
+
+ // Set the DB version
+ $this->db_version = $version;
+ }
+
+ /**
+ * Get the table version from the database.
+ *
+ * @since 1.0.0
+ */
+ private function get_db_version() {
+ $this->db_version = $this->is_global()
+ ? get_network_option( get_main_network_id(), $this->db_version_key, false )
+ : get_option( $this->db_version_key, false );
+ }
+
+ /**
+ * Delete the table version from the database.
+ *
+ * @since 1.0.0
+ */
+ private function delete_db_version() {
+ $this->db_version = $this->is_global()
+ ? delete_network_option( get_main_network_id(), $this->db_version_key )
+ : delete_option( $this->db_version_key );
+ }
+
+ /**
+ * Add class hooks to the parent application actions.
+ *
+ * @since 1.0.0
+ */
+ private function add_hooks() {
+
+ // Add table to the global database object
+ add_action( 'switch_blog', array( $this, 'switch_blog' ) );
+ add_action( 'admin_init', array( $this, 'maybe_upgrade' ) );
+ }
+
+ /**
+ * Check if the current request is from some kind of test.
+ *
+ * This is primarily used to skip 'admin_init' and force-install tables.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ private function is_testing() {
+ return (bool)
+
+ // Tests constant is being used
+ ( defined( 'WP_TESTS_DIR' ) && WP_TESTS_DIR )
+
+ ||
+
+ // Scaffolded (https://make.wordpress.org/cli/handbook/plugin-unit-tests/)
+ function_exists( '_manually_load_plugin' );
+ }
+
+ /**
+ * Check if table is global.
+ *
+ * @since 1.0.0
+ *
+ * @return bool
+ */
+ private function is_global() {
+ return ( true === $this->global );
+ }
+
+ /**
+ * Try to get a callable upgrade, with some magic to avoid needing to
+ * do this dance repeatedly inside subclasses.
+ *
+ * @since 1.0.0
+ *
+ * @param string $callback
+ *
+ * @return mixed Callable string, or false if not callable
+ */
+ private function get_callable( $callback = '' ) {
+
+ // Default return value
+ $callable = $callback;
+
+ // Look for global function
+ if ( ! is_callable( $callable ) ) {
+
+ // Fallback to local class method
+ $callable = array( $this, $callback );
+ if ( ! is_callable( $callable ) ) {
+
+ // Fallback to class method prefixed with "__"
+ $callable = array( $this, "__{$callback}" );
+ if ( ! is_callable( $callable ) ) {
+ $callable = false;
+ }
+ }
+ }
+
+ // Return callable string, or false if not callable
+ return $callable;
+ }
+}
diff --git a/inc/Dependencies/League/Container/Argument/ArgumentResolverInterface.php b/inc/Dependencies/League/Container/Argument/ArgumentResolverInterface.php
new file mode 100644
index 0000000..60acec5
--- /dev/null
+++ b/inc/Dependencies/League/Container/Argument/ArgumentResolverInterface.php
@@ -0,0 +1,28 @@
+getValue();
+ } elseif ($argument instanceof ClassNameInterface) {
+ $id = $argument->getClassName();
+ } elseif (!is_string($argument)) {
+ return $argument;
+ } else {
+ $justStringValue = true;
+ $id = $argument;
+ }
+
+ $container = null;
+
+ try {
+ $container = $this->getLeagueContainer();
+ } catch (ContainerException $e) {
+ if ($this instanceof ReflectionContainer) {
+ $container = $this;
+ }
+ }
+
+ if ($container !== null) {
+ try {
+ return $container->get($id);
+ } catch (NotFoundException $exception) {
+ if ($argument instanceof ClassNameWithOptionalValue) {
+ return $argument->getOptionalValue();
+ }
+
+ if ($justStringValue) {
+ return $id;
+ }
+
+ throw $exception;
+ }
+ }
+
+ if ($argument instanceof ClassNameWithOptionalValue) {
+ return $argument->getOptionalValue();
+ }
+
+ // Just a string value.
+ return $id;
+ }, $arguments);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function reflectArguments(ReflectionFunctionAbstract $method, array $args = []) : array
+ {
+ $arguments = array_map(function (ReflectionParameter $param) use ($method, $args) {
+ $name = $param->getName();
+ $type = $param->getType();
+
+ if (array_key_exists($name, $args)) {
+ return new RawArgument($args[$name]);
+ }
+
+ if ($type) {
+ if (PHP_VERSION_ID >= 70100) {
+ $typeName = $type->getName();
+ } else {
+ $typeName = (string) $type;
+ }
+
+ $typeName = ltrim($typeName, '?');
+
+ if ($param->isDefaultValueAvailable()) {
+ return new ClassNameWithOptionalValue($typeName, $param->getDefaultValue());
+ }
+
+ return new ClassName($typeName);
+ }
+
+ if ($param->isDefaultValueAvailable()) {
+ return new RawArgument($param->getDefaultValue());
+ }
+
+ throw new NotFoundException(sprintf(
+ 'Unable to resolve a value for parameter (%s) in the function/method (%s)',
+ $name,
+ $method->getName()
+ ));
+ }, $method->getParameters());
+
+ return $this->resolveArguments($arguments);
+ }
+
+ /**
+ * @return ContainerInterface
+ */
+ abstract public function getContainer() : ContainerInterface;
+
+ /**
+ * @return Container
+ */
+ abstract public function getLeagueContainer() : Container;
+}
diff --git a/inc/Dependencies/League/Container/Argument/ClassName.php b/inc/Dependencies/League/Container/Argument/ClassName.php
new file mode 100644
index 0000000..80a19a4
--- /dev/null
+++ b/inc/Dependencies/League/Container/Argument/ClassName.php
@@ -0,0 +1,29 @@
+value = $value;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getClassName() : string
+ {
+ return $this->value;
+ }
+}
diff --git a/inc/Dependencies/League/Container/Argument/ClassNameInterface.php b/inc/Dependencies/League/Container/Argument/ClassNameInterface.php
new file mode 100644
index 0000000..64973d8
--- /dev/null
+++ b/inc/Dependencies/League/Container/Argument/ClassNameInterface.php
@@ -0,0 +1,13 @@
+className = $className;
+ $this->optionalValue = $optionalValue;
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function getClassName(): string
+ {
+ return $this->className;
+ }
+
+ public function getOptionalValue()
+ {
+ return $this->optionalValue;
+ }
+}
diff --git a/inc/Dependencies/League/Container/Argument/RawArgument.php b/inc/Dependencies/League/Container/Argument/RawArgument.php
new file mode 100644
index 0000000..d0216c0
--- /dev/null
+++ b/inc/Dependencies/League/Container/Argument/RawArgument.php
@@ -0,0 +1,29 @@
+value = $value;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+}
diff --git a/inc/Dependencies/League/Container/Argument/RawArgumentInterface.php b/inc/Dependencies/League/Container/Argument/RawArgumentInterface.php
new file mode 100644
index 0000000..a1d8421
--- /dev/null
+++ b/inc/Dependencies/League/Container/Argument/RawArgumentInterface.php
@@ -0,0 +1,13 @@
+definitions = $definitions ?? new DefinitionAggregate;
+ $this->providers = $providers ?? new ServiceProviderAggregate;
+ $this->inflectors = $inflectors ?? new InflectorAggregate;
+
+ if ($this->definitions instanceof ContainerAwareInterface) {
+ $this->definitions->setLeagueContainer($this);
+ }
+
+ if ($this->providers instanceof ContainerAwareInterface) {
+ $this->providers->setLeagueContainer($this);
+ }
+
+ if ($this->inflectors instanceof ContainerAwareInterface) {
+ $this->inflectors->setLeagueContainer($this);
+ }
+ }
+
+ /**
+ * Add an item to the container.
+ *
+ * @param string $id
+ * @param mixed $concrete
+ * @param boolean $shared
+ *
+ * @return DefinitionInterface
+ */
+ public function add(string $id, $concrete = null, bool $shared = null) : DefinitionInterface
+ {
+ $concrete = $concrete ?? $id;
+ $shared = $shared ?? $this->defaultToShared;
+
+ return $this->definitions->add($id, $concrete, $shared);
+ }
+
+ /**
+ * Proxy to add with shared as true.
+ *
+ * @param string $id
+ * @param mixed $concrete
+ *
+ * @return DefinitionInterface
+ */
+ public function share(string $id, $concrete = null) : DefinitionInterface
+ {
+ return $this->add($id, $concrete, true);
+ }
+
+ /**
+ * Whether the container should default to defining shared definitions.
+ *
+ * @param boolean $shared
+ *
+ * @return self
+ */
+ public function defaultToShared(bool $shared = true) : ContainerInterface
+ {
+ $this->defaultToShared = $shared;
+
+ return $this;
+ }
+
+ /**
+ * Get a definition to extend.
+ *
+ * @param string $id [description]
+ *
+ * @return DefinitionInterface
+ */
+ public function extend(string $id) : DefinitionInterface
+ {
+ if ($this->providers->provides($id)) {
+ $this->providers->register($id);
+ }
+
+ if ($this->definitions->has($id)) {
+ return $this->definitions->getDefinition($id);
+ }
+
+ throw new NotFoundException(
+ sprintf('Unable to extend alias (%s) as it is not being managed as a definition', $id)
+ );
+ }
+
+ /**
+ * Add a service provider.
+ *
+ * @param ServiceProviderInterface|string $provider
+ *
+ * @return self
+ */
+ public function addServiceProvider($provider) : self
+ {
+ $this->providers->add($provider);
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function get($id, bool $new = false)
+ {
+ if ($this->definitions->has($id)) {
+ $resolved = $this->definitions->resolve($id, $new);
+ return $this->inflectors->inflect($resolved);
+ }
+
+ if ($this->definitions->hasTag($id)) {
+ $arrayOf = $this->definitions->resolveTagged($id, $new);
+
+ array_walk($arrayOf, function (&$resolved) {
+ $resolved = $this->inflectors->inflect($resolved);
+ });
+
+ return $arrayOf;
+ }
+
+ if ($this->providers->provides($id)) {
+ $this->providers->register($id);
+
+ if (!$this->definitions->has($id) && !$this->definitions->hasTag($id)) {
+ throw new ContainerException(sprintf('Service provider lied about providing (%s) service', $id));
+ }
+
+ return $this->get($id, $new);
+ }
+
+ foreach ($this->delegates as $delegate) {
+ if ($delegate->has($id)) {
+ $resolved = $delegate->get($id);
+ return $this->inflectors->inflect($resolved);
+ }
+ }
+
+ throw new NotFoundException(sprintf('Alias (%s) is not being managed by the container or delegates', $id));
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function has($id)
+ {
+ if ($this->definitions->has($id)) {
+ return true;
+ }
+
+ if ($this->definitions->hasTag($id)) {
+ return true;
+ }
+
+ if ($this->providers->provides($id)) {
+ return true;
+ }
+
+ foreach ($this->delegates as $delegate) {
+ if ($delegate->has($id)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Allows for manipulation of specific types on resolution.
+ *
+ * @param string $type
+ * @param callable|null $callback
+ *
+ * @return InflectorInterface
+ */
+ public function inflector(string $type, callable $callback = null) : InflectorInterface
+ {
+ return $this->inflectors->add($type, $callback);
+ }
+
+ /**
+ * Delegate a backup container to be checked for services if it
+ * cannot be resolved via this container.
+ *
+ * @param ContainerInterface $container
+ *
+ * @return self
+ */
+ public function delegate(ContainerInterface $container) : self
+ {
+ $this->delegates[] = $container;
+
+ if ($container instanceof ContainerAwareInterface) {
+ $container->setLeagueContainer($this);
+ }
+
+ return $this;
+ }
+}
diff --git a/inc/Dependencies/League/Container/ContainerAwareInterface.php b/inc/Dependencies/League/Container/ContainerAwareInterface.php
new file mode 100644
index 0000000..c2ffe83
--- /dev/null
+++ b/inc/Dependencies/League/Container/ContainerAwareInterface.php
@@ -0,0 +1,40 @@
+container = $container;
+
+ return $this;
+ }
+
+ /**
+ * Get the container.
+ *
+ * @return ContainerInterface
+ */
+ public function getContainer() : ContainerInterface
+ {
+ if ($this->container instanceof ContainerInterface) {
+ return $this->container;
+ }
+
+ throw new ContainerException('No container implementation has been set.');
+ }
+
+ /**
+ * Set a container.
+ *
+ * @param Container $container
+ *
+ * @return self
+ */
+ public function setLeagueContainer(Container $container) : ContainerAwareInterface
+ {
+ $this->container = $container;
+ $this->leagueContainer = $container;
+
+ return $this;
+ }
+
+ /**
+ * Get the container.
+ *
+ * @return Container
+ */
+ public function getLeagueContainer() : Container
+ {
+ if ($this->leagueContainer instanceof Container) {
+ return $this->leagueContainer;
+ }
+
+ throw new ContainerException('No container implementation has been set.');
+ }
+}
diff --git a/inc/Dependencies/League/Container/Definition/Definition.php b/inc/Dependencies/League/Container/Definition/Definition.php
new file mode 100644
index 0000000..09cdeef
--- /dev/null
+++ b/inc/Dependencies/League/Container/Definition/Definition.php
@@ -0,0 +1,278 @@
+alias = $id;
+ $this->concrete = $concrete;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function addTag(string $tag) : DefinitionInterface
+ {
+ $this->tags[$tag] = true;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function hasTag(string $tag) : bool
+ {
+ return isset($this->tags[$tag]);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setAlias(string $id) : DefinitionInterface
+ {
+ $this->alias = $id;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getAlias() : string
+ {
+ return $this->alias;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setShared(bool $shared = true) : DefinitionInterface
+ {
+ $this->shared = $shared;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function isShared() : bool
+ {
+ return $this->shared;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getConcrete()
+ {
+ return $this->concrete;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setConcrete($concrete) : DefinitionInterface
+ {
+ $this->concrete = $concrete;
+ $this->resolved = null;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function addArgument($arg) : DefinitionInterface
+ {
+ $this->arguments[] = $arg;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function addArguments(array $args) : DefinitionInterface
+ {
+ foreach ($args as $arg) {
+ $this->addArgument($arg);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function addMethodCall(string $method, array $args = []) : DefinitionInterface
+ {
+ $this->methods[] = [
+ 'method' => $method,
+ 'arguments' => $args
+ ];
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function addMethodCalls(array $methods = []) : DefinitionInterface
+ {
+ foreach ($methods as $method => $args) {
+ $this->addMethodCall($method, $args);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function resolve(bool $new = false)
+ {
+ $concrete = $this->concrete;
+
+ if ($this->isShared() && $this->resolved !== null && $new === false) {
+ return $this->resolved;
+ }
+
+ if (is_callable($concrete)) {
+ $concrete = $this->resolveCallable($concrete);
+ }
+
+ if ($concrete instanceof RawArgumentInterface) {
+ $this->resolved = $concrete->getValue();
+
+ return $concrete->getValue();
+ }
+
+ if ($concrete instanceof ClassNameInterface) {
+ $concrete = $concrete->getClassName();
+ }
+
+ if (is_string($concrete) && class_exists($concrete)) {
+ $concrete = $this->resolveClass($concrete);
+ }
+
+ if (is_object($concrete)) {
+ $concrete = $this->invokeMethods($concrete);
+ }
+
+ if (is_string($concrete) && $this->getContainer()->has($concrete)) {
+ $concrete = $this->getContainer()->get($concrete);
+ }
+
+ $this->resolved = $concrete;
+
+ return $concrete;
+ }
+
+ /**
+ * Resolve a callable.
+ *
+ * @param callable $concrete
+ *
+ * @return mixed
+ */
+ protected function resolveCallable(callable $concrete)
+ {
+ $resolved = $this->resolveArguments($this->arguments);
+
+ return call_user_func_array($concrete, $resolved);
+ }
+
+ /**
+ * Resolve a class.
+ *
+ * @param string $concrete
+ *
+ * @return object
+ *
+ * @throws ReflectionException
+ */
+ protected function resolveClass(string $concrete)
+ {
+ $resolved = $this->resolveArguments($this->arguments);
+ $reflection = new ReflectionClass($concrete);
+
+ return $reflection->newInstanceArgs($resolved);
+ }
+
+ /**
+ * Invoke methods on resolved instance.
+ *
+ * @param object $instance
+ *
+ * @return object
+ */
+ protected function invokeMethods($instance)
+ {
+ foreach ($this->methods as $method) {
+ $args = $this->resolveArguments($method['arguments']);
+
+ /** @var callable $callable */
+ $callable = [$instance, $method['method']];
+ call_user_func_array($callable, $args);
+ }
+
+ return $instance;
+ }
+}
diff --git a/inc/Dependencies/League/Container/Definition/DefinitionAggregate.php b/inc/Dependencies/League/Container/Definition/DefinitionAggregate.php
new file mode 100644
index 0000000..a3094a1
--- /dev/null
+++ b/inc/Dependencies/League/Container/Definition/DefinitionAggregate.php
@@ -0,0 +1,124 @@
+definitions = array_filter($definitions, function ($definition) {
+ return ($definition instanceof DefinitionInterface);
+ });
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function add(string $id, $definition, bool $shared = false) : DefinitionInterface
+ {
+ if (!$definition instanceof DefinitionInterface) {
+ $definition = new Definition($id, $definition);
+ }
+
+ $this->definitions[] = $definition
+ ->setAlias($id)
+ ->setShared($shared)
+ ;
+
+ return $definition;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function has(string $id) : bool
+ {
+ foreach ($this->getIterator() as $definition) {
+ if ($id === $definition->getAlias()) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function hasTag(string $tag) : bool
+ {
+ foreach ($this->getIterator() as $definition) {
+ if ($definition->hasTag($tag)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getDefinition(string $id) : DefinitionInterface
+ {
+ foreach ($this->getIterator() as $definition) {
+ if ($id === $definition->getAlias()) {
+ return $definition->setLeagueContainer($this->getLeagueContainer());
+ }
+ }
+
+ throw new NotFoundException(sprintf('Alias (%s) is not being handled as a definition.', $id));
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function resolve(string $id, bool $new = false)
+ {
+ return $this->getDefinition($id)->resolve($new);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function resolveTagged(string $tag, bool $new = false) : array
+ {
+ $arrayOf = [];
+
+ foreach ($this->getIterator() as $definition) {
+ if ($definition->hasTag($tag)) {
+ $arrayOf[] = $definition->setLeagueContainer($this->getLeagueContainer())->resolve($new);
+ }
+ }
+
+ return $arrayOf;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIterator() : Generator
+ {
+ $count = count($this->definitions);
+
+ for ($i = 0; $i < $count; $i++) {
+ yield $this->definitions[$i];
+ }
+ }
+}
diff --git a/inc/Dependencies/League/Container/Definition/DefinitionAggregateInterface.php b/inc/Dependencies/League/Container/Definition/DefinitionAggregateInterface.php
new file mode 100644
index 0000000..3fef003
--- /dev/null
+++ b/inc/Dependencies/League/Container/Definition/DefinitionAggregateInterface.php
@@ -0,0 +1,67 @@
+type = $type;
+ $this->callback = $callback;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getType() : string
+ {
+ return $this->type;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function invokeMethod(string $name, array $args) : InflectorInterface
+ {
+ $this->methods[$name] = $args;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function invokeMethods(array $methods) : InflectorInterface
+ {
+ foreach ($methods as $name => $args) {
+ $this->invokeMethod($name, $args);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setProperty(string $property, $value) : InflectorInterface
+ {
+ $this->properties[$property] = $this->resolveArguments([$value])[0];
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setProperties(array $properties) : InflectorInterface
+ {
+ foreach ($properties as $property => $value) {
+ $this->setProperty($property, $value);
+ }
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function inflect($object)
+ {
+ $properties = $this->resolveArguments(array_values($this->properties));
+ $properties = array_combine(array_keys($this->properties), $properties);
+
+ // array_combine() can technically return false
+ foreach ($properties ?: [] as $property => $value) {
+ $object->{$property} = $value;
+ }
+
+ foreach ($this->methods as $method => $args) {
+ $args = $this->resolveArguments($args);
+
+ /** @var callable $callable */
+ $callable = [$object, $method];
+ call_user_func_array($callable, $args);
+ }
+
+ if ($this->callback !== null) {
+ call_user_func($this->callback, $object);
+ }
+ }
+}
diff --git a/inc/Dependencies/League/Container/Inflector/InflectorAggregate.php b/inc/Dependencies/League/Container/Inflector/InflectorAggregate.php
new file mode 100644
index 0000000..4866cc0
--- /dev/null
+++ b/inc/Dependencies/League/Container/Inflector/InflectorAggregate.php
@@ -0,0 +1,58 @@
+inflectors[] = $inflector;
+
+ return $inflector;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIterator() : Generator
+ {
+ $count = count($this->inflectors);
+
+ for ($i = 0; $i < $count; $i++) {
+ yield $this->inflectors[$i];
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function inflect($object)
+ {
+ foreach ($this->getIterator() as $inflector) {
+ $type = $inflector->getType();
+
+ if (! $object instanceof $type) {
+ continue;
+ }
+
+ $inflector->setLeagueContainer($this->getLeagueContainer());
+ $inflector->inflect($object);
+ }
+
+ return $object;
+ }
+}
diff --git a/inc/Dependencies/League/Container/Inflector/InflectorAggregateInterface.php b/inc/Dependencies/League/Container/Inflector/InflectorAggregateInterface.php
new file mode 100644
index 0000000..24a5995
--- /dev/null
+++ b/inc/Dependencies/League/Container/Inflector/InflectorAggregateInterface.php
@@ -0,0 +1,27 @@
+cacheResolutions === true && array_key_exists($id, $this->cache)) {
+ return $this->cache[$id];
+ }
+
+ if (! $this->has($id)) {
+ throw new NotFoundException(
+ sprintf('Alias (%s) is not an existing class and therefore cannot be resolved', $id)
+ );
+ }
+
+ $reflector = new ReflectionClass($id);
+ $construct = $reflector->getConstructor();
+
+ if ($construct && !$construct->isPublic()) {
+ throw new NotFoundException(
+ sprintf('Alias (%s) has a non-public constructor and therefore cannot be instantiated', $id)
+ );
+ }
+
+ $resolution = $construct === null
+ ? new $id
+ : $resolution = $reflector->newInstanceArgs($this->reflectArguments($construct, $args))
+ ;
+
+ if ($this->cacheResolutions === true) {
+ $this->cache[$id] = $resolution;
+ }
+
+ return $resolution;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function has($id)
+ {
+ return class_exists($id);
+ }
+
+ /**
+ * Invoke a callable via the container.
+ *
+ * @param callable $callable
+ * @param array $args
+ *
+ * @return mixed
+ *
+ * @throws ReflectionException
+ */
+ public function call(callable $callable, array $args = [])
+ {
+ if (is_string($callable) && strpos($callable, '::') !== false) {
+ $callable = explode('::', $callable);
+ }
+
+ if (is_array($callable)) {
+ if (is_string($callable[0])) {
+ $callable[0] = $this->getContainer()->get($callable[0]);
+ }
+
+ $reflection = new ReflectionMethod($callable[0], $callable[1]);
+
+ if ($reflection->isStatic()) {
+ $callable[0] = null;
+ }
+
+ return $reflection->invokeArgs($callable[0], $this->reflectArguments($reflection, $args));
+ }
+
+ if (is_object($callable)) {
+ $reflection = new ReflectionMethod($callable, '__invoke');
+
+ return $reflection->invokeArgs($callable, $this->reflectArguments($reflection, $args));
+ }
+
+ $reflection = new ReflectionFunction(\Closure::fromCallable($callable));
+
+ return $reflection->invokeArgs($this->reflectArguments($reflection, $args));
+ }
+
+ /**
+ * Whether the container should default to caching resolutions and returning
+ * the cache on following calls.
+ *
+ * @param boolean $option
+ *
+ * @return self
+ */
+ public function cacheResolutions(bool $option = true) : ContainerInterface
+ {
+ $this->cacheResolutions = $option;
+
+ return $this;
+ }
+}
diff --git a/inc/Dependencies/League/Container/ServiceProvider/AbstractServiceProvider.php b/inc/Dependencies/League/Container/ServiceProvider/AbstractServiceProvider.php
new file mode 100644
index 0000000..77281ab
--- /dev/null
+++ b/inc/Dependencies/League/Container/ServiceProvider/AbstractServiceProvider.php
@@ -0,0 +1,46 @@
+provides, true);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setIdentifier(string $id) : ServiceProviderInterface
+ {
+ $this->identifier = $id;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIdentifier() : string
+ {
+ return $this->identifier ?? get_class($this);
+ }
+}
diff --git a/inc/Dependencies/League/Container/ServiceProvider/BootableServiceProviderInterface.php b/inc/Dependencies/League/Container/ServiceProvider/BootableServiceProviderInterface.php
new file mode 100644
index 0000000..2d00532
--- /dev/null
+++ b/inc/Dependencies/League/Container/ServiceProvider/BootableServiceProviderInterface.php
@@ -0,0 +1,14 @@
+getContainer()->has($provider)) {
+ $provider = $this->getContainer()->get($provider);
+ } elseif (is_string($provider) && class_exists($provider)) {
+ $provider = new $provider;
+ }
+
+ if (in_array($provider, $this->providers, true)) {
+ return $this;
+ }
+
+ if ($provider instanceof ContainerAwareInterface) {
+ $provider->setLeagueContainer($this->getLeagueContainer());
+ }
+
+ if ($provider instanceof BootableServiceProviderInterface) {
+ $provider->boot();
+ }
+
+ if ($provider instanceof ServiceProviderInterface) {
+ $this->providers[] = $provider;
+
+ return $this;
+ }
+
+ throw new ContainerException(
+ 'A service provider must be a fully qualified class name or instance ' .
+ 'of (\WP_Rocket\Dependencies\League\Container\ServiceProvider\ServiceProviderInterface)'
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function provides(string $service) : bool
+ {
+ foreach ($this->getIterator() as $provider) {
+ if ($provider->provides($service)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getIterator() : Generator
+ {
+ $count = count($this->providers);
+
+ for ($i = 0; $i < $count; $i++) {
+ yield $this->providers[$i];
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function register(string $service)
+ {
+ if (false === $this->provides($service)) {
+ throw new ContainerException(
+ sprintf('(%s) is not provided by a service provider', $service)
+ );
+ }
+
+ foreach ($this->getIterator() as $provider) {
+ if (in_array($provider->getIdentifier(), $this->registered, true)) {
+ continue;
+ }
+
+ if ($provider->provides($service)) {
+ $this->registered[] = $provider->getIdentifier();
+ $provider->register();
+ }
+ }
+ }
+}
diff --git a/inc/Dependencies/League/Container/ServiceProvider/ServiceProviderAggregateInterface.php b/inc/Dependencies/League/Container/ServiceProvider/ServiceProviderAggregateInterface.php
new file mode 100644
index 0000000..6b1fece
--- /dev/null
+++ b/inc/Dependencies/League/Container/ServiceProvider/ServiceProviderAggregateInterface.php
@@ -0,0 +1,36 @@
+leagueContainer property or the `getLeagueContainer` method
+ * from the ContainerAwareTrait.
+ *
+ * @return void
+ */
+ public function register();
+
+ /**
+ * Set a custom id for the service provider. This enables
+ * registering the same service provider multiple times.
+ *
+ * @param string $id
+ *
+ * @return self
+ */
+ public function setIdentifier(string $id) : ServiceProviderInterface;
+
+ /**
+ * The id of the service provider uniquely identifies it, so
+ * that we can quickly determine if it has already been registered.
+ * Defaults to get_class($provider).
+ *
+ * @return string
+ */
+ public function getIdentifier() : string;
+}
diff --git a/inc/Dependencies/Minify/CSS.php b/inc/Dependencies/Minify/CSS.php
new file mode 100644
index 0000000..8ac362c
--- /dev/null
+++ b/inc/Dependencies/Minify/CSS.php
@@ -0,0 +1,790 @@
+
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+
+namespace WP_Rocket\Dependencies\Minify;
+
+use WP_Rocket\Dependencies\Minify\Exceptions\FileImportException;
+use WP_Rocket\Dependencies\PathConverter\ConverterInterface;
+use WP_Rocket\Dependencies\PathConverter\Converter;
+
+/**
+ * CSS minifier
+ *
+ * Please report bugs on https://github.com/matthiasmullie/minify/issues
+ *
+ * @package Minify
+ * @author Matthias Mullie
+ * @author Tijs Verkoyen
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+class CSS extends Minify
+{
+ /**
+ * @var int maximum inport size in kB
+ */
+ protected $maxImportSize = 5;
+
+ /**
+ * @var string[] valid import extensions
+ */
+ protected $importExtensions = array(
+ 'gif' => 'data:image/gif',
+ 'png' => 'data:image/png',
+ 'jpe' => 'data:image/jpeg',
+ 'jpg' => 'data:image/jpeg',
+ 'jpeg' => 'data:image/jpeg',
+ 'svg' => 'data:image/svg+xml',
+ 'woff' => 'data:application/x-font-woff',
+ 'tif' => 'image/tiff',
+ 'tiff' => 'image/tiff',
+ 'xbm' => 'image/x-xbitmap',
+ );
+
+ /**
+ * Set the maximum size if files to be imported.
+ *
+ * Files larger than this size (in kB) will not be imported into the CSS.
+ * Importing files into the CSS as data-uri will save you some connections,
+ * but we should only import relatively small decorative images so that our
+ * CSS file doesn't get too bulky.
+ *
+ * @param int $size Size in kB
+ */
+ public function setMaxImportSize($size)
+ {
+ $this->maxImportSize = $size;
+ }
+
+ /**
+ * Set the type of extensions to be imported into the CSS (to save network
+ * connections).
+ * Keys of the array should be the file extensions & respective values
+ * should be the data type.
+ *
+ * @param string[] $extensions Array of file extensions
+ */
+ public function setImportExtensions(array $extensions)
+ {
+ $this->importExtensions = $extensions;
+ }
+
+ /**
+ * Move any import statements to the top.
+ *
+ * @param string $content Nearly finished CSS content
+ *
+ * @return string
+ */
+ protected function moveImportsToTop($content)
+ {
+ if (preg_match_all('/(;?)(@import (?url\()?(?P["\']?).+?(?P=quotes)(?(url)\)));?/', $content, $matches)) {
+ // remove from content
+ foreach ($matches[0] as $import) {
+ $content = str_replace($import, '', $content);
+ }
+
+ // add to top
+ $content = implode(';', $matches[2]).';'.trim($content, ';');
+ }
+
+ return $content;
+ }
+
+ /**
+ * Combine CSS from import statements.
+ *
+ * @import's will be loaded and their content merged into the original file,
+ * to save HTTP requests.
+ *
+ * @param string $source The file to combine imports for
+ * @param string $content The CSS content to combine imports for
+ * @param string[] $parents Parent paths, for circular reference checks
+ *
+ * @return string
+ *
+ * @throws FileImportException
+ */
+ protected function combineImports($source, $content, $parents)
+ {
+ $importRegexes = array(
+ // @import url(xxx)
+ '/
+ # import statement
+ @import
+
+ # whitespace
+ \s+
+
+ # open url()
+ url\(
+
+ # (optional) open path enclosure
+ (?P["\']?)
+
+ # fetch path
+ (?P.+?)
+
+ # (optional) close path enclosure
+ (?P=quotes)
+
+ # close url()
+ \)
+
+ # (optional) trailing whitespace
+ \s*
+
+ # (optional) media statement(s)
+ (?P[^;]*)
+
+ # (optional) trailing whitespace
+ \s*
+
+ # (optional) closing semi-colon
+ ;?
+
+ /ix',
+
+ // @import 'xxx'
+ '/
+
+ # import statement
+ @import
+
+ # whitespace
+ \s+
+
+ # open path enclosure
+ (?P["\'])
+
+ # fetch path
+ (?P.+?)
+
+ # close path enclosure
+ (?P=quotes)
+
+ # (optional) trailing whitespace
+ \s*
+
+ # (optional) media statement(s)
+ (?P[^;]*)
+
+ # (optional) trailing whitespace
+ \s*
+
+ # (optional) closing semi-colon
+ ;?
+
+ /ix',
+ );
+
+ // find all relative imports in css
+ $matches = array();
+ foreach ($importRegexes as $importRegex) {
+ if (preg_match_all($importRegex, $content, $regexMatches, PREG_SET_ORDER)) {
+ $matches = array_merge($matches, $regexMatches);
+ }
+ }
+
+ $search = array();
+ $replace = array();
+
+ // loop the matches
+ foreach ($matches as $match) {
+ // get the path for the file that will be imported
+ $importPath = dirname($source).'/'.$match['path'];
+
+ // only replace the import with the content if we can grab the
+ // content of the file
+ if (!$this->canImportByPath($match['path']) || !$this->canImportFile($importPath)) {
+ continue;
+ }
+
+ // check if current file was not imported previously in the same
+ // import chain.
+ if (in_array($importPath, $parents)) {
+ throw new FileImportException('Failed to import file "'.$importPath.'": circular reference detected.');
+ }
+
+ // grab referenced file & minify it (which may include importing
+ // yet other @import statements recursively)
+ $minifier = new self($importPath);
+ $minifier->setMaxImportSize($this->maxImportSize);
+ $minifier->setImportExtensions($this->importExtensions);
+ $importContent = $minifier->execute($source, $parents);
+
+ // check if this is only valid for certain media
+ if (!empty($match['media'])) {
+ $importContent = '@media '.$match['media'].'{'.$importContent.'}';
+ }
+
+ // add to replacement array
+ $search[] = $match[0];
+ $replace[] = $importContent;
+ }
+
+ // replace the import statements
+ return str_replace($search, $replace, $content);
+ }
+
+ /**
+ * Import files into the CSS, base64-ized.
+ *
+ * @url(image.jpg) images will be loaded and their content merged into the
+ * original file, to save HTTP requests.
+ *
+ * @param string $source The file to import files for
+ * @param string $content The CSS content to import files for
+ *
+ * @return string
+ */
+ protected function importFiles($source, $content)
+ {
+ $regex = '/url\((["\']?)(.+?)\\1\)/i';
+ if ($this->importExtensions && preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
+ $search = array();
+ $replace = array();
+
+ // loop the matches
+ foreach ($matches as $match) {
+ $extension = substr(strrchr($match[2], '.'), 1);
+ if ($extension && !array_key_exists($extension, $this->importExtensions)) {
+ continue;
+ }
+
+ // get the path for the file that will be imported
+ $path = $match[2];
+ $path = dirname($source).'/'.$path;
+
+ // only replace the import with the content if we're able to get
+ // the content of the file, and it's relatively small
+ if ($this->canImportFile($path) && $this->canImportBySize($path)) {
+ // grab content && base64-ize
+ $importContent = $this->load($path);
+ $importContent = base64_encode($importContent);
+
+ // build replacement
+ $search[] = $match[0];
+ $replace[] = 'url('.$this->importExtensions[$extension].';base64,'.$importContent.')';
+ }
+ }
+
+ // replace the import statements
+ $content = str_replace($search, $replace, $content);
+ }
+
+ return $content;
+ }
+
+ /**
+ * Minify the data.
+ * Perform CSS optimizations.
+ *
+ * @param string[optional] $path Path to write the data to
+ * @param string[] $parents Parent paths, for circular reference checks
+ *
+ * @return string The minified data
+ */
+ public function execute($path = null, $parents = array())
+ {
+ $content = '';
+
+ // loop CSS data (raw data and files)
+ foreach ($this->data as $source => $css) {
+ /*
+ * Let's first take out strings & comments, since we can't just
+ * remove whitespace anywhere. If whitespace occurs inside a string,
+ * we should leave it alone. E.g.:
+ * p { content: "a test" }
+ */
+ $this->extractStrings();
+ $this->stripComments();
+ $this->extractMath();
+ $this->extractCustomProperties();
+ $css = $this->replace($css);
+
+ $css = $this->stripWhitespace($css);
+ $css = $this->shortenColors($css);
+ $css = $this->shortenZeroes($css);
+ $css = $this->shortenFontWeights($css);
+ $css = $this->stripEmptyTags($css);
+
+ // restore the string we've extracted earlier
+ $css = $this->restoreExtractedData($css);
+
+ $source = is_int($source) ? '' : $source;
+ $parents = $source ? array_merge($parents, array($source)) : $parents;
+ $css = $this->combineImports($source, $css, $parents);
+ $css = $this->importFiles($source, $css);
+
+ /*
+ * If we'll save to a new path, we'll have to fix the relative paths
+ * to be relative no longer to the source file, but to the new path.
+ * If we don't write to a file, fall back to same path so no
+ * conversion happens (because we still want it to go through most
+ * of the move code, which also addresses url() & @import syntax...)
+ */
+ $converter = $this->getPathConverter($source, $path ?: $source);
+ $css = $this->move($converter, $css);
+
+ // combine css
+ $content .= $css;
+ }
+
+ $content = $this->moveImportsToTop($content);
+
+ return $content;
+ }
+
+ /**
+ * Moving a css file should update all relative urls.
+ * Relative references (e.g. ../images/image.gif) in a certain css file,
+ * will have to be updated when a file is being saved at another location
+ * (e.g. ../../images/image.gif, if the new CSS file is 1 folder deeper).
+ *
+ * @param ConverterInterface $converter Relative path converter
+ * @param string $content The CSS content to update relative urls for
+ *
+ * @return string
+ */
+ protected function move(ConverterInterface $converter, $content)
+ {
+ /*
+ * Relative path references will usually be enclosed by url(). @import
+ * is an exception, where url() is not necessary around the path (but is
+ * allowed).
+ * This *could* be 1 regular expression, where both regular expressions
+ * in this array are on different sides of a |. But we're using named
+ * patterns in both regexes, the same name on both regexes. This is only
+ * possible with a (?J) modifier, but that only works after a fairly
+ * recent PCRE version. That's why I'm doing 2 separate regular
+ * expressions & combining the matches after executing of both.
+ */
+ $relativeRegexes = array(
+ // url(xxx)
+ '/
+ # open url()
+ url\(
+
+ \s*
+
+ # open path enclosure
+ (?P["\'])?
+
+ # fetch path
+ (?P.+?)
+
+ # close path enclosure
+ (?(quotes)(?P=quotes))
+
+ \s*
+
+ # close url()
+ \)
+
+ /ix',
+
+ // @import "xxx"
+ '/
+ # import statement
+ @import
+
+ # whitespace
+ \s+
+
+ # we don\'t have to check for @import url(), because the
+ # condition above will already catch these
+
+ # open path enclosure
+ (?P["\'])
+
+ # fetch path
+ (?P.+?)
+
+ # close path enclosure
+ (?P=quotes)
+
+ /ix',
+ );
+
+ // find all relative urls in css
+ $matches = array();
+ foreach ($relativeRegexes as $relativeRegex) {
+ if (preg_match_all($relativeRegex, $content, $regexMatches, PREG_SET_ORDER)) {
+ $matches = array_merge($matches, $regexMatches);
+ }
+ }
+
+ $search = array();
+ $replace = array();
+
+ // loop all urls
+ foreach ($matches as $match) {
+ // determine if it's a url() or an @import match
+ $type = (strpos($match[0], '@import') === 0 ? 'import' : 'url');
+
+ $url = $match['path'];
+ if ($this->canImportByPath($url)) {
+ // attempting to interpret GET-params makes no sense, so let's discard them for awhile
+ $params = strrchr($url, '?');
+ $url = $params ? substr($url, 0, -strlen($params)) : $url;
+
+ // fix relative url
+ $url = $converter->convert($url);
+
+ // now that the path has been converted, re-apply GET-params
+ $url .= $params;
+ }
+
+ /*
+ * Urls with control characters above 0x7e should be quoted.
+ * According to Mozilla's parser, whitespace is only allowed at the
+ * end of unquoted urls.
+ * Urls with `)` (as could happen with data: uris) should also be
+ * quoted to avoid being confused for the url() closing parentheses.
+ * And urls with a # have also been reported to cause issues.
+ * Urls with quotes inside should also remain escaped.
+ *
+ * @see https://developer.mozilla.org/nl/docs/Web/CSS/url#The_url()_functional_notation
+ * @see https://hg.mozilla.org/mozilla-central/rev/14abca4e7378
+ * @see https://github.com/matthiasmullie/minify/issues/193
+ */
+ $url = trim($url);
+ if (preg_match('/[\s\)\'"#\x{7f}-\x{9f}]/u', $url)) {
+ $url = $match['quotes'] . $url . $match['quotes'];
+ }
+
+ // build replacement
+ $search[] = $match[0];
+ if ($type === 'url') {
+ $replace[] = 'url('.$url.')';
+ } elseif ($type === 'import') {
+ $replace[] = '@import "'.$url.'"';
+ }
+ }
+
+ // replace urls
+ return str_replace($search, $replace, $content);
+ }
+
+ /**
+ * Shorthand hex color codes.
+ * #FF0000 -> #F00.
+ *
+ * @param string $content The CSS content to shorten the hex color codes for
+ *
+ * @return string
+ */
+ protected function shortenColors($content)
+ {
+ $content = preg_replace('/(?<=[: ])#([0-9a-z])\\1([0-9a-z])\\2([0-9a-z])\\3(?:([0-9a-z])\\4)?(?=[; }])/i', '#$1$2$3$4', $content);
+
+ // remove alpha channel if it's pointless...
+ $content = preg_replace('/(?<=[: ])#([0-9a-z]{6})ff?(?=[; }])/i', '#$1', $content);
+ $content = preg_replace('/(?<=[: ])#([0-9a-z]{3})f?(?=[; }])/i', '#$1', $content);
+
+ $colors = array(
+ // we can shorten some even more by replacing them with their color name
+ '#F0FFFF' => 'azure',
+ '#F5F5DC' => 'beige',
+ '#A52A2A' => 'brown',
+ '#FF7F50' => 'coral',
+ '#FFD700' => 'gold',
+ '#808080' => 'gray',
+ '#008000' => 'green',
+ '#4B0082' => 'indigo',
+ '#FFFFF0' => 'ivory',
+ '#F0E68C' => 'khaki',
+ '#FAF0E6' => 'linen',
+ '#800000' => 'maroon',
+ '#000080' => 'navy',
+ '#808000' => 'olive',
+ '#CD853F' => 'peru',
+ '#FFC0CB' => 'pink',
+ '#DDA0DD' => 'plum',
+ '#800080' => 'purple',
+ '#F00' => 'red',
+ '#FA8072' => 'salmon',
+ '#A0522D' => 'sienna',
+ '#C0C0C0' => 'silver',
+ '#FFFAFA' => 'snow',
+ '#D2B48C' => 'tan',
+ '#FF6347' => 'tomato',
+ '#EE82EE' => 'violet',
+ '#F5DEB3' => 'wheat',
+ // or the other way around
+ 'WHITE' => '#fff',
+ 'BLACK' => '#000',
+ );
+
+ return preg_replace_callback(
+ '/(?<=[: ])('.implode('|', array_keys($colors)).')(?=[; }])/i',
+ function ($match) use ($colors) {
+ return $colors[strtoupper($match[0])];
+ },
+ $content
+ );
+ }
+
+ /**
+ * Shorten CSS font weights.
+ *
+ * @param string $content The CSS content to shorten the font weights for
+ *
+ * @return string
+ */
+ protected function shortenFontWeights($content)
+ {
+ $weights = array(
+ 'normal' => 400,
+ 'bold' => 700,
+ );
+
+ $callback = function ($match) use ($weights) {
+ return $match[1].$weights[$match[2]];
+ };
+
+ return preg_replace_callback('/(font-weight\s*:\s*)('.implode('|', array_keys($weights)).')(?=[;}])/', $callback, $content);
+ }
+
+ /**
+ * Shorthand 0 values to plain 0, instead of e.g. -0em.
+ *
+ * @param string $content The CSS content to shorten the zero values for
+ *
+ * @return string
+ */
+ protected function shortenZeroes($content)
+ {
+ // we don't want to strip units in `calc()` expressions:
+ // `5px - 0px` is valid, but `5px - 0` is not
+ // `10px * 0` is valid (equates to 0), and so is `10 * 0px`, but
+ // `10 * 0` is invalid
+ // we've extracted calcs earlier, so we don't need to worry about this
+
+ // reusable bits of code throughout these regexes:
+ // before & after are used to make sure we don't match lose unintended
+ // 0-like values (e.g. in #000, or in http://url/1.0)
+ // units can be stripped from 0 values, or used to recognize non 0
+ // values (where wa may be able to strip a .0 suffix)
+ $before = '(?<=[:(, ])';
+ $after = '(?=[ ,);}])';
+ $units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';
+
+ // strip units after zeroes (0px -> 0)
+ // NOTE: it should be safe to remove all units for a 0 value, but in
+ // practice, Webkit (especially Safari) seems to stumble over at least
+ // 0%, potentially other units as well. Only stripping 'px' for now.
+ // @see https://github.com/matthiasmullie/minify/issues/60
+ $content = preg_replace('/'.$before.'(-?0*(\.0+)?)(?<=0)px'.$after.'/', '\\1', $content);
+
+ // strip 0-digits (.0 -> 0)
+ $content = preg_replace('/'.$before.'\.0+'.$units.'?'.$after.'/', '0\\1', $content);
+ // strip trailing 0: 50.10 -> 50.1, 50.10px -> 50.1px
+ $content = preg_replace('/'.$before.'(-?[0-9]+\.[0-9]+)0+'.$units.'?'.$after.'/', '\\1\\2', $content);
+ // strip trailing 0: 50.00 -> 50, 50.00px -> 50px
+ $content = preg_replace('/'.$before.'(-?[0-9]+)\.0+'.$units.'?'.$after.'/', '\\1\\2', $content);
+ // strip leading 0: 0.1 -> .1, 01.1 -> 1.1
+ $content = preg_replace('/'.$before.'(-?)0+([0-9]*\.[0-9]+)'.$units.'?'.$after.'/', '\\1\\2\\3', $content);
+
+ // strip negative zeroes (-0 -> 0) & truncate zeroes (00 -> 0)
+ $content = preg_replace('/'.$before.'-?0+'.$units.'?'.$after.'/', '0\\1', $content);
+
+ // IE doesn't seem to understand a unitless flex-basis value (correct -
+ // it goes against the spec), so let's add it in again (make it `%`,
+ // which is only 1 char: 0%, 0px, 0 anything, it's all just the same)
+ // @see https://developer.mozilla.org/nl/docs/Web/CSS/flex
+ $content = preg_replace('/flex:([0-9]+\s[0-9]+\s)0([;\}])/', 'flex:${1}0%${2}', $content);
+ $content = preg_replace('/flex-basis:0([;\}])/', 'flex-basis:0%${1}', $content);
+
+ return $content;
+ }
+
+ /**
+ * Strip empty tags from source code.
+ *
+ * @param string $content
+ *
+ * @return string
+ */
+ protected function stripEmptyTags($content)
+ {
+ $content = preg_replace('/(?<=^)[^\{\};]+\{\s*\}/', '', $content);
+ $content = preg_replace('/(?<=(\}|;))[^\{\};]+\{\s*\}/', '', $content);
+
+ return $content;
+ }
+
+ /**
+ * Strip comments from source code.
+ */
+ protected function stripComments()
+ {
+ // PHP only supports $this inside anonymous functions since 5.4
+ $minifier = $this;
+ $callback = function ($match) use ($minifier) {
+ $count = count($minifier->extracted);
+ $placeholder = '/*'.$count.'*/';
+ $minifier->extracted[$placeholder] = $match[0];
+
+ return $placeholder;
+ };
+ $this->registerPattern('/\n?\/\*(!|.*?@license|.*?@preserve).*?\*\/\n?/s', $callback);
+
+ $this->registerPattern('/\/\*.*?\*\//s', '');
+ }
+
+ /**
+ * Strip whitespace.
+ *
+ * @param string $content The CSS content to strip the whitespace for
+ *
+ * @return string
+ */
+ protected function stripWhitespace($content)
+ {
+ // remove leading & trailing whitespace
+ $content = preg_replace('/^\s*/m', '', $content);
+ $content = preg_replace('/\s*$/m', '', $content);
+
+ // replace newlines with a single space
+ $content = preg_replace('/\s+/', ' ', $content);
+
+ // remove whitespace around meta characters
+ // inspired by stackoverflow.com/questions/15195750/minify-compress-css-with-regex
+ $content = preg_replace('/\s*([\*$~^|]?+=|[{};,>~]|!important\b)\s*/', '$1', $content);
+ $content = preg_replace('/([\[(:>\+])\s+/', '$1', $content);
+ $content = preg_replace('/\s+([\]\)>\+])/', '$1', $content);
+ $content = preg_replace('/\s+(:)(?![^\}]*\{)/', '$1', $content);
+
+ // whitespace around + and - can only be stripped inside some pseudo-
+ // classes, like `:nth-child(3+2n)`
+ // not in things like `calc(3px + 2px)`, shorthands like `3px -2px`, or
+ // selectors like `div.weird- p`
+ $pseudos = array('nth-child', 'nth-last-child', 'nth-last-of-type', 'nth-of-type');
+ $content = preg_replace('/:('.implode('|', $pseudos).')\(\s*([+-]?)\s*(.+?)\s*([+-]?)\s*(.*?)\s*\)/', ':$1($2$3$4$5)', $content);
+
+ // remove semicolon/whitespace followed by closing bracket
+ $content = str_replace(';}', '}', $content);
+
+ return trim($content);
+ }
+
+ /**
+ * Replace all occurrences of functions that may contain math, where
+ * whitespace around operators needs to be preserved (e.g. calc, clamp)
+ */
+ protected function extractMath()
+ {
+ $functions = array('calc', 'clamp', 'min', 'max');
+ $pattern = '/\b('. implode('|', $functions) .')(\(.+?)(?=$|;|})/m';
+
+ // PHP only supports $this inside anonymous functions since 5.4
+ $minifier = $this;
+ $callback = function ($match) use ($minifier, $pattern, &$callback) {
+ $function = $match[1];
+ $length = strlen($match[2]);
+ $expr = '';
+ $opened = 0;
+
+ // the regular expression for extracting math has 1 significant problem:
+ // it can't determine the correct closing parenthesis...
+ // instead, it'll match a larger portion of code to where it's certain that
+ // the calc() musts have ended, and we'll figure out which is the correct
+ // closing parenthesis here, by counting how many have opened
+ for ($i = 0; $i < $length; $i++) {
+ $char = $match[2][$i];
+ $expr .= $char;
+ if ($char === '(') {
+ $opened++;
+ } elseif ($char === ')' && --$opened === 0) {
+ break;
+ }
+ }
+
+ // now that we've figured out where the calc() starts and ends, extract it
+ $count = count($minifier->extracted);
+ $placeholder = 'math('.$count.')';
+ $minifier->extracted[$placeholder] = $function.'('.trim(substr($expr, 1, -1)).')';
+
+ // and since we've captured more code than required, we may have some leftover
+ // calc() in here too - go recursive on the remaining but of code to go figure
+ // that out and extract what is needed
+ $rest = "";
+ $pos = strpos($match[0], $function.$expr);
+ if ($pos !== false) {
+ $rest = substr_replace($match[0], '', $pos, strlen($function.$expr));
+ }
+ $rest = preg_replace_callback($pattern, $callback, $rest);
+
+ return $placeholder.$rest;
+ };
+
+ $this->registerPattern($pattern, $callback);
+ }
+
+ /**
+ * Replace custom properties, whose values may be used in scenarios where
+ * we wouldn't want them to be minified (e.g. inside calc)
+ */
+ protected function extractCustomProperties()
+ {
+ // PHP only supports $this inside anonymous functions since 5.4
+ $minifier = $this;
+ $this->registerPattern(
+ '/(?<=^|[;}{])\s*(--[^:;{}"\'\s]+)\s*:([^;{}]+)/m',
+ function ($match) use ($minifier) {
+ $placeholder = '--custom-'. count($minifier->extracted) . ':0';
+ $minifier->extracted[$placeholder] = $match[1] .':'. trim($match[2]);
+ return $placeholder;
+
+ }
+ );
+ }
+
+ /**
+ * Check if file is small enough to be imported.
+ *
+ * @param string $path The path to the file
+ *
+ * @return bool
+ */
+ protected function canImportBySize($path)
+ {
+ return ($size = @filesize($path)) && $size <= $this->maxImportSize * 1024;
+ }
+
+ /**
+ * Check if file a file can be imported, going by the path.
+ *
+ * @param string $path
+ *
+ * @return bool
+ */
+ protected function canImportByPath($path)
+ {
+ return preg_match('/^(data:|https?:|\\/)/', $path) === 0;
+ }
+
+ /**
+ * Return a converter to update relative paths to be relative to the new
+ * destination.
+ *
+ * @param string $source
+ * @param string $target
+ *
+ * @return ConverterInterface
+ */
+ protected function getPathConverter($source, $target)
+ {
+ return new Converter($source, $target);
+ }
+}
diff --git a/inc/Dependencies/Minify/Exception.php b/inc/Dependencies/Minify/Exception.php
new file mode 100644
index 0000000..46ede5d
--- /dev/null
+++ b/inc/Dependencies/Minify/Exception.php
@@ -0,0 +1,20 @@
+
+ */
+namespace WP_Rocket\Dependencies\Minify;
+
+/**
+ * Base Exception Class
+ * @deprecated Use Exceptions\BasicException instead
+ *
+ * @package Minify
+ * @author Matthias Mullie
+ */
+abstract class Exception extends \Exception
+{
+}
diff --git a/inc/Dependencies/Minify/Exceptions/BasicException.php b/inc/Dependencies/Minify/Exceptions/BasicException.php
new file mode 100644
index 0000000..4d6dfca
--- /dev/null
+++ b/inc/Dependencies/Minify/Exceptions/BasicException.php
@@ -0,0 +1,23 @@
+
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+namespace WP_Rocket\Dependencies\Minify\Exceptions;
+
+use WP_Rocket\Dependencies\Minify\Exception;
+
+/**
+ * Basic Exception Class
+ *
+ * @package Minify\Exception
+ * @author Matthias Mullie
+ */
+abstract class BasicException extends Exception
+{
+}
diff --git a/inc/Dependencies/Minify/Exceptions/FileImportException.php b/inc/Dependencies/Minify/Exceptions/FileImportException.php
new file mode 100644
index 0000000..b5f9e30
--- /dev/null
+++ b/inc/Dependencies/Minify/Exceptions/FileImportException.php
@@ -0,0 +1,21 @@
+
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+namespace WP_Rocket\Dependencies\Minify\Exceptions;
+
+/**
+ * File Import Exception Class
+ *
+ * @package Minify\Exception
+ * @author Matthias Mullie
+ */
+class FileImportException extends BasicException
+{
+}
diff --git a/inc/Dependencies/Minify/Exceptions/IOException.php b/inc/Dependencies/Minify/Exceptions/IOException.php
new file mode 100644
index 0000000..5bc6bfb
--- /dev/null
+++ b/inc/Dependencies/Minify/Exceptions/IOException.php
@@ -0,0 +1,21 @@
+
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+namespace WP_Rocket\Dependencies\Minify\Exceptions;
+
+/**
+ * IO Exception Class
+ *
+ * @package Minify\Exception
+ * @author Matthias Mullie
+ */
+class IOException extends BasicException
+{
+}
diff --git a/inc/Dependencies/Minify/JS.php b/inc/Dependencies/Minify/JS.php
new file mode 100644
index 0000000..3fc9b4c
--- /dev/null
+++ b/inc/Dependencies/Minify/JS.php
@@ -0,0 +1,622 @@
+
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+namespace WP_Rocket\Dependencies\Minify;
+
+/**
+ * JavaScript Minifier Class
+ *
+ * Please report bugs on https://github.com/matthiasmullie/minify/issues
+ *
+ * @package Minify
+ * @author Matthias Mullie
+ * @author Tijs Verkoyen
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+class JS extends Minify
+{
+ /**
+ * Var-matching regex based on http://stackoverflow.com/a/9337047/802993.
+ *
+ * Note that regular expressions using that bit must have the PCRE_UTF8
+ * pattern modifier (/u) set.
+ *
+ * @var string
+ */
+ const REGEX_VARIABLE = '\b[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\x{02c1}\x{02c6}-\x{02d1}\x{02e0}-\x{02e4}\x{02ec}\x{02ee}\x{0370}-\x{0374}\x{0376}\x{0377}\x{037a}-\x{037d}\x{0386}\x{0388}-\x{038a}\x{038c}\x{038e}-\x{03a1}\x{03a3}-\x{03f5}\x{03f7}-\x{0481}\x{048a}-\x{0527}\x{0531}-\x{0556}\x{0559}\x{0561}-\x{0587}\x{05d0}-\x{05ea}\x{05f0}-\x{05f2}\x{0620}-\x{064a}\x{066e}\x{066f}\x{0671}-\x{06d3}\x{06d5}\x{06e5}\x{06e6}\x{06ee}\x{06ef}\x{06fa}-\x{06fc}\x{06ff}\x{0710}\x{0712}-\x{072f}\x{074d}-\x{07a5}\x{07b1}\x{07ca}-\x{07ea}\x{07f4}\x{07f5}\x{07fa}\x{0800}-\x{0815}\x{081a}\x{0824}\x{0828}\x{0840}-\x{0858}\x{08a0}\x{08a2}-\x{08ac}\x{0904}-\x{0939}\x{093d}\x{0950}\x{0958}-\x{0961}\x{0971}-\x{0977}\x{0979}-\x{097f}\x{0985}-\x{098c}\x{098f}\x{0990}\x{0993}-\x{09a8}\x{09aa}-\x{09b0}\x{09b2}\x{09b6}-\x{09b9}\x{09bd}\x{09ce}\x{09dc}\x{09dd}\x{09df}-\x{09e1}\x{09f0}\x{09f1}\x{0a05}-\x{0a0a}\x{0a0f}\x{0a10}\x{0a13}-\x{0a28}\x{0a2a}-\x{0a30}\x{0a32}\x{0a33}\x{0a35}\x{0a36}\x{0a38}\x{0a39}\x{0a59}-\x{0a5c}\x{0a5e}\x{0a72}-\x{0a74}\x{0a85}-\x{0a8d}\x{0a8f}-\x{0a91}\x{0a93}-\x{0aa8}\x{0aaa}-\x{0ab0}\x{0ab2}\x{0ab3}\x{0ab5}-\x{0ab9}\x{0abd}\x{0ad0}\x{0ae0}\x{0ae1}\x{0b05}-\x{0b0c}\x{0b0f}\x{0b10}\x{0b13}-\x{0b28}\x{0b2a}-\x{0b30}\x{0b32}\x{0b33}\x{0b35}-\x{0b39}\x{0b3d}\x{0b5c}\x{0b5d}\x{0b5f}-\x{0b61}\x{0b71}\x{0b83}\x{0b85}-\x{0b8a}\x{0b8e}-\x{0b90}\x{0b92}-\x{0b95}\x{0b99}\x{0b9a}\x{0b9c}\x{0b9e}\x{0b9f}\x{0ba3}\x{0ba4}\x{0ba8}-\x{0baa}\x{0bae}-\x{0bb9}\x{0bd0}\x{0c05}-\x{0c0c}\x{0c0e}-\x{0c10}\x{0c12}-\x{0c28}\x{0c2a}-\x{0c33}\x{0c35}-\x{0c39}\x{0c3d}\x{0c58}\x{0c59}\x{0c60}\x{0c61}\x{0c85}-\x{0c8c}\x{0c8e}-\x{0c90}\x{0c92}-\x{0ca8}\x{0caa}-\x{0cb3}\x{0cb5}-\x{0cb9}\x{0cbd}\x{0cde}\x{0ce0}\x{0ce1}\x{0cf1}\x{0cf2}\x{0d05}-\x{0d0c}\x{0d0e}-\x{0d10}\x{0d12}-\x{0d3a}\x{0d3d}\x{0d4e}\x{0d60}\x{0d61}\x{0d7a}-\x{0d7f}\x{0d85}-\x{0d96}\x{0d9a}-\x{0db1}\x{0db3}-\x{0dbb}\x{0dbd}\x{0dc0}-\x{0dc6}\x{0e01}-\x{0e30}\x{0e32}\x{0e33}\x{0e40}-\x{0e46}\x{0e81}\x{0e82}\x{0e84}\x{0e87}\x{0e88}\x{0e8a}\x{0e8d}\x{0e94}-\x{0e97}\x{0e99}-\x{0e9f}\x{0ea1}-\x{0ea3}\x{0ea5}\x{0ea7}\x{0eaa}\x{0eab}\x{0ead}-\x{0eb0}\x{0eb2}\x{0eb3}\x{0ebd}\x{0ec0}-\x{0ec4}\x{0ec6}\x{0edc}-\x{0edf}\x{0f00}\x{0f40}-\x{0f47}\x{0f49}-\x{0f6c}\x{0f88}-\x{0f8c}\x{1000}-\x{102a}\x{103f}\x{1050}-\x{1055}\x{105a}-\x{105d}\x{1061}\x{1065}\x{1066}\x{106e}-\x{1070}\x{1075}-\x{1081}\x{108e}\x{10a0}-\x{10c5}\x{10c7}\x{10cd}\x{10d0}-\x{10fa}\x{10fc}-\x{1248}\x{124a}-\x{124d}\x{1250}-\x{1256}\x{1258}\x{125a}-\x{125d}\x{1260}-\x{1288}\x{128a}-\x{128d}\x{1290}-\x{12b0}\x{12b2}-\x{12b5}\x{12b8}-\x{12be}\x{12c0}\x{12c2}-\x{12c5}\x{12c8}-\x{12d6}\x{12d8}-\x{1310}\x{1312}-\x{1315}\x{1318}-\x{135a}\x{1380}-\x{138f}\x{13a0}-\x{13f4}\x{1401}-\x{166c}\x{166f}-\x{167f}\x{1681}-\x{169a}\x{16a0}-\x{16ea}\x{16ee}-\x{16f0}\x{1700}-\x{170c}\x{170e}-\x{1711}\x{1720}-\x{1731}\x{1740}-\x{1751}\x{1760}-\x{176c}\x{176e}-\x{1770}\x{1780}-\x{17b3}\x{17d7}\x{17dc}\x{1820}-\x{1877}\x{1880}-\x{18a8}\x{18aa}\x{18b0}-\x{18f5}\x{1900}-\x{191c}\x{1950}-\x{196d}\x{1970}-\x{1974}\x{1980}-\x{19ab}\x{19c1}-\x{19c7}\x{1a00}-\x{1a16}\x{1a20}-\x{1a54}\x{1aa7}\x{1b05}-\x{1b33}\x{1b45}-\x{1b4b}\x{1b83}-\x{1ba0}\x{1bae}\x{1baf}\x{1bba}-\x{1be5}\x{1c00}-\x{1c23}\x{1c4d}-\x{1c4f}\x{1c5a}-\x{1c7d}\x{1ce9}-\x{1cec}\x{1cee}-\x{1cf1}\x{1cf5}\x{1cf6}\x{1d00}-\x{1dbf}\x{1e00}-\x{1f15}\x{1f18}-\x{1f1d}\x{1f20}-\x{1f45}\x{1f48}-\x{1f4d}\x{1f50}-\x{1f57}\x{1f59}\x{1f5b}\x{1f5d}\x{1f5f}-\x{1f7d}\x{1f80}-\x{1fb4}\x{1fb6}-\x{1fbc}\x{1fbe}\x{1fc2}-\x{1fc4}\x{1fc6}-\x{1fcc}\x{1fd0}-\x{1fd3}\x{1fd6}-\x{1fdb}\x{1fe0}-\x{1fec}\x{1ff2}-\x{1ff4}\x{1ff6}-\x{1ffc}\x{2071}\x{207f}\x{2090}-\x{209c}\x{2102}\x{2107}\x{210a}-\x{2113}\x{2115}\x{2119}-\x{211d}\x{2124}\x{2126}\x{2128}\x{212a}-\x{212d}\x{212f}-\x{2139}\x{213c}-\x{213f}\x{2145}-\x{2149}\x{214e}\x{2160}-\x{2188}\x{2c00}-\x{2c2e}\x{2c30}-\x{2c5e}\x{2c60}-\x{2ce4}\x{2ceb}-\x{2cee}\x{2cf2}\x{2cf3}\x{2d00}-\x{2d25}\x{2d27}\x{2d2d}\x{2d30}-\x{2d67}\x{2d6f}\x{2d80}-\x{2d96}\x{2da0}-\x{2da6}\x{2da8}-\x{2dae}\x{2db0}-\x{2db6}\x{2db8}-\x{2dbe}\x{2dc0}-\x{2dc6}\x{2dc8}-\x{2dce}\x{2dd0}-\x{2dd6}\x{2dd8}-\x{2dde}\x{2e2f}\x{3005}-\x{3007}\x{3021}-\x{3029}\x{3031}-\x{3035}\x{3038}-\x{303c}\x{3041}-\x{3096}\x{309d}-\x{309f}\x{30a1}-\x{30fa}\x{30fc}-\x{30ff}\x{3105}-\x{312d}\x{3131}-\x{318e}\x{31a0}-\x{31ba}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}\x{4e00}-\x{9fcc}\x{a000}-\x{a48c}\x{a4d0}-\x{a4fd}\x{a500}-\x{a60c}\x{a610}-\x{a61f}\x{a62a}\x{a62b}\x{a640}-\x{a66e}\x{a67f}-\x{a697}\x{a6a0}-\x{a6ef}\x{a717}-\x{a71f}\x{a722}-\x{a788}\x{a78b}-\x{a78e}\x{a790}-\x{a793}\x{a7a0}-\x{a7aa}\x{a7f8}-\x{a801}\x{a803}-\x{a805}\x{a807}-\x{a80a}\x{a80c}-\x{a822}\x{a840}-\x{a873}\x{a882}-\x{a8b3}\x{a8f2}-\x{a8f7}\x{a8fb}\x{a90a}-\x{a925}\x{a930}-\x{a946}\x{a960}-\x{a97c}\x{a984}-\x{a9b2}\x{a9cf}\x{aa00}-\x{aa28}\x{aa40}-\x{aa42}\x{aa44}-\x{aa4b}\x{aa60}-\x{aa76}\x{aa7a}\x{aa80}-\x{aaaf}\x{aab1}\x{aab5}\x{aab6}\x{aab9}-\x{aabd}\x{aac0}\x{aac2}\x{aadb}-\x{aadd}\x{aae0}-\x{aaea}\x{aaf2}-\x{aaf4}\x{ab01}-\x{ab06}\x{ab09}-\x{ab0e}\x{ab11}-\x{ab16}\x{ab20}-\x{ab26}\x{ab28}-\x{ab2e}\x{abc0}-\x{abe2}\x{ac00}-\x{d7a3}\x{d7b0}-\x{d7c6}\x{d7cb}-\x{d7fb}\x{f900}-\x{fa6d}\x{fa70}-\x{fad9}\x{fb00}-\x{fb06}\x{fb13}-\x{fb17}\x{fb1d}\x{fb1f}-\x{fb28}\x{fb2a}-\x{fb36}\x{fb38}-\x{fb3c}\x{fb3e}\x{fb40}\x{fb41}\x{fb43}\x{fb44}\x{fb46}-\x{fbb1}\x{fbd3}-\x{fd3d}\x{fd50}-\x{fd8f}\x{fd92}-\x{fdc7}\x{fdf0}-\x{fdfb}\x{fe70}-\x{fe74}\x{fe76}-\x{fefc}\x{ff21}-\x{ff3a}\x{ff41}-\x{ff5a}\x{ff66}-\x{ffbe}\x{ffc2}-\x{ffc7}\x{ffca}-\x{ffcf}\x{ffd2}-\x{ffd7}\x{ffda}-\x{ffdc}][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\x{02c1}\x{02c6}-\x{02d1}\x{02e0}-\x{02e4}\x{02ec}\x{02ee}\x{0370}-\x{0374}\x{0376}\x{0377}\x{037a}-\x{037d}\x{0386}\x{0388}-\x{038a}\x{038c}\x{038e}-\x{03a1}\x{03a3}-\x{03f5}\x{03f7}-\x{0481}\x{048a}-\x{0527}\x{0531}-\x{0556}\x{0559}\x{0561}-\x{0587}\x{05d0}-\x{05ea}\x{05f0}-\x{05f2}\x{0620}-\x{064a}\x{066e}\x{066f}\x{0671}-\x{06d3}\x{06d5}\x{06e5}\x{06e6}\x{06ee}\x{06ef}\x{06fa}-\x{06fc}\x{06ff}\x{0710}\x{0712}-\x{072f}\x{074d}-\x{07a5}\x{07b1}\x{07ca}-\x{07ea}\x{07f4}\x{07f5}\x{07fa}\x{0800}-\x{0815}\x{081a}\x{0824}\x{0828}\x{0840}-\x{0858}\x{08a0}\x{08a2}-\x{08ac}\x{0904}-\x{0939}\x{093d}\x{0950}\x{0958}-\x{0961}\x{0971}-\x{0977}\x{0979}-\x{097f}\x{0985}-\x{098c}\x{098f}\x{0990}\x{0993}-\x{09a8}\x{09aa}-\x{09b0}\x{09b2}\x{09b6}-\x{09b9}\x{09bd}\x{09ce}\x{09dc}\x{09dd}\x{09df}-\x{09e1}\x{09f0}\x{09f1}\x{0a05}-\x{0a0a}\x{0a0f}\x{0a10}\x{0a13}-\x{0a28}\x{0a2a}-\x{0a30}\x{0a32}\x{0a33}\x{0a35}\x{0a36}\x{0a38}\x{0a39}\x{0a59}-\x{0a5c}\x{0a5e}\x{0a72}-\x{0a74}\x{0a85}-\x{0a8d}\x{0a8f}-\x{0a91}\x{0a93}-\x{0aa8}\x{0aaa}-\x{0ab0}\x{0ab2}\x{0ab3}\x{0ab5}-\x{0ab9}\x{0abd}\x{0ad0}\x{0ae0}\x{0ae1}\x{0b05}-\x{0b0c}\x{0b0f}\x{0b10}\x{0b13}-\x{0b28}\x{0b2a}-\x{0b30}\x{0b32}\x{0b33}\x{0b35}-\x{0b39}\x{0b3d}\x{0b5c}\x{0b5d}\x{0b5f}-\x{0b61}\x{0b71}\x{0b83}\x{0b85}-\x{0b8a}\x{0b8e}-\x{0b90}\x{0b92}-\x{0b95}\x{0b99}\x{0b9a}\x{0b9c}\x{0b9e}\x{0b9f}\x{0ba3}\x{0ba4}\x{0ba8}-\x{0baa}\x{0bae}-\x{0bb9}\x{0bd0}\x{0c05}-\x{0c0c}\x{0c0e}-\x{0c10}\x{0c12}-\x{0c28}\x{0c2a}-\x{0c33}\x{0c35}-\x{0c39}\x{0c3d}\x{0c58}\x{0c59}\x{0c60}\x{0c61}\x{0c85}-\x{0c8c}\x{0c8e}-\x{0c90}\x{0c92}-\x{0ca8}\x{0caa}-\x{0cb3}\x{0cb5}-\x{0cb9}\x{0cbd}\x{0cde}\x{0ce0}\x{0ce1}\x{0cf1}\x{0cf2}\x{0d05}-\x{0d0c}\x{0d0e}-\x{0d10}\x{0d12}-\x{0d3a}\x{0d3d}\x{0d4e}\x{0d60}\x{0d61}\x{0d7a}-\x{0d7f}\x{0d85}-\x{0d96}\x{0d9a}-\x{0db1}\x{0db3}-\x{0dbb}\x{0dbd}\x{0dc0}-\x{0dc6}\x{0e01}-\x{0e30}\x{0e32}\x{0e33}\x{0e40}-\x{0e46}\x{0e81}\x{0e82}\x{0e84}\x{0e87}\x{0e88}\x{0e8a}\x{0e8d}\x{0e94}-\x{0e97}\x{0e99}-\x{0e9f}\x{0ea1}-\x{0ea3}\x{0ea5}\x{0ea7}\x{0eaa}\x{0eab}\x{0ead}-\x{0eb0}\x{0eb2}\x{0eb3}\x{0ebd}\x{0ec0}-\x{0ec4}\x{0ec6}\x{0edc}-\x{0edf}\x{0f00}\x{0f40}-\x{0f47}\x{0f49}-\x{0f6c}\x{0f88}-\x{0f8c}\x{1000}-\x{102a}\x{103f}\x{1050}-\x{1055}\x{105a}-\x{105d}\x{1061}\x{1065}\x{1066}\x{106e}-\x{1070}\x{1075}-\x{1081}\x{108e}\x{10a0}-\x{10c5}\x{10c7}\x{10cd}\x{10d0}-\x{10fa}\x{10fc}-\x{1248}\x{124a}-\x{124d}\x{1250}-\x{1256}\x{1258}\x{125a}-\x{125d}\x{1260}-\x{1288}\x{128a}-\x{128d}\x{1290}-\x{12b0}\x{12b2}-\x{12b5}\x{12b8}-\x{12be}\x{12c0}\x{12c2}-\x{12c5}\x{12c8}-\x{12d6}\x{12d8}-\x{1310}\x{1312}-\x{1315}\x{1318}-\x{135a}\x{1380}-\x{138f}\x{13a0}-\x{13f4}\x{1401}-\x{166c}\x{166f}-\x{167f}\x{1681}-\x{169a}\x{16a0}-\x{16ea}\x{16ee}-\x{16f0}\x{1700}-\x{170c}\x{170e}-\x{1711}\x{1720}-\x{1731}\x{1740}-\x{1751}\x{1760}-\x{176c}\x{176e}-\x{1770}\x{1780}-\x{17b3}\x{17d7}\x{17dc}\x{1820}-\x{1877}\x{1880}-\x{18a8}\x{18aa}\x{18b0}-\x{18f5}\x{1900}-\x{191c}\x{1950}-\x{196d}\x{1970}-\x{1974}\x{1980}-\x{19ab}\x{19c1}-\x{19c7}\x{1a00}-\x{1a16}\x{1a20}-\x{1a54}\x{1aa7}\x{1b05}-\x{1b33}\x{1b45}-\x{1b4b}\x{1b83}-\x{1ba0}\x{1bae}\x{1baf}\x{1bba}-\x{1be5}\x{1c00}-\x{1c23}\x{1c4d}-\x{1c4f}\x{1c5a}-\x{1c7d}\x{1ce9}-\x{1cec}\x{1cee}-\x{1cf1}\x{1cf5}\x{1cf6}\x{1d00}-\x{1dbf}\x{1e00}-\x{1f15}\x{1f18}-\x{1f1d}\x{1f20}-\x{1f45}\x{1f48}-\x{1f4d}\x{1f50}-\x{1f57}\x{1f59}\x{1f5b}\x{1f5d}\x{1f5f}-\x{1f7d}\x{1f80}-\x{1fb4}\x{1fb6}-\x{1fbc}\x{1fbe}\x{1fc2}-\x{1fc4}\x{1fc6}-\x{1fcc}\x{1fd0}-\x{1fd3}\x{1fd6}-\x{1fdb}\x{1fe0}-\x{1fec}\x{1ff2}-\x{1ff4}\x{1ff6}-\x{1ffc}\x{2071}\x{207f}\x{2090}-\x{209c}\x{2102}\x{2107}\x{210a}-\x{2113}\x{2115}\x{2119}-\x{211d}\x{2124}\x{2126}\x{2128}\x{212a}-\x{212d}\x{212f}-\x{2139}\x{213c}-\x{213f}\x{2145}-\x{2149}\x{214e}\x{2160}-\x{2188}\x{2c00}-\x{2c2e}\x{2c30}-\x{2c5e}\x{2c60}-\x{2ce4}\x{2ceb}-\x{2cee}\x{2cf2}\x{2cf3}\x{2d00}-\x{2d25}\x{2d27}\x{2d2d}\x{2d30}-\x{2d67}\x{2d6f}\x{2d80}-\x{2d96}\x{2da0}-\x{2da6}\x{2da8}-\x{2dae}\x{2db0}-\x{2db6}\x{2db8}-\x{2dbe}\x{2dc0}-\x{2dc6}\x{2dc8}-\x{2dce}\x{2dd0}-\x{2dd6}\x{2dd8}-\x{2dde}\x{2e2f}\x{3005}-\x{3007}\x{3021}-\x{3029}\x{3031}-\x{3035}\x{3038}-\x{303c}\x{3041}-\x{3096}\x{309d}-\x{309f}\x{30a1}-\x{30fa}\x{30fc}-\x{30ff}\x{3105}-\x{312d}\x{3131}-\x{318e}\x{31a0}-\x{31ba}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}\x{4e00}-\x{9fcc}\x{a000}-\x{a48c}\x{a4d0}-\x{a4fd}\x{a500}-\x{a60c}\x{a610}-\x{a61f}\x{a62a}\x{a62b}\x{a640}-\x{a66e}\x{a67f}-\x{a697}\x{a6a0}-\x{a6ef}\x{a717}-\x{a71f}\x{a722}-\x{a788}\x{a78b}-\x{a78e}\x{a790}-\x{a793}\x{a7a0}-\x{a7aa}\x{a7f8}-\x{a801}\x{a803}-\x{a805}\x{a807}-\x{a80a}\x{a80c}-\x{a822}\x{a840}-\x{a873}\x{a882}-\x{a8b3}\x{a8f2}-\x{a8f7}\x{a8fb}\x{a90a}-\x{a925}\x{a930}-\x{a946}\x{a960}-\x{a97c}\x{a984}-\x{a9b2}\x{a9cf}\x{aa00}-\x{aa28}\x{aa40}-\x{aa42}\x{aa44}-\x{aa4b}\x{aa60}-\x{aa76}\x{aa7a}\x{aa80}-\x{aaaf}\x{aab1}\x{aab5}\x{aab6}\x{aab9}-\x{aabd}\x{aac0}\x{aac2}\x{aadb}-\x{aadd}\x{aae0}-\x{aaea}\x{aaf2}-\x{aaf4}\x{ab01}-\x{ab06}\x{ab09}-\x{ab0e}\x{ab11}-\x{ab16}\x{ab20}-\x{ab26}\x{ab28}-\x{ab2e}\x{abc0}-\x{abe2}\x{ac00}-\x{d7a3}\x{d7b0}-\x{d7c6}\x{d7cb}-\x{d7fb}\x{f900}-\x{fa6d}\x{fa70}-\x{fad9}\x{fb00}-\x{fb06}\x{fb13}-\x{fb17}\x{fb1d}\x{fb1f}-\x{fb28}\x{fb2a}-\x{fb36}\x{fb38}-\x{fb3c}\x{fb3e}\x{fb40}\x{fb41}\x{fb43}\x{fb44}\x{fb46}-\x{fbb1}\x{fbd3}-\x{fd3d}\x{fd50}-\x{fd8f}\x{fd92}-\x{fdc7}\x{fdf0}-\x{fdfb}\x{fe70}-\x{fe74}\x{fe76}-\x{fefc}\x{ff21}-\x{ff3a}\x{ff41}-\x{ff5a}\x{ff66}-\x{ffbe}\x{ffc2}-\x{ffc7}\x{ffca}-\x{ffcf}\x{ffd2}-\x{ffd7}\x{ffda}-\x{ffdc}0-9\x{0300}-\x{036f}\x{0483}-\x{0487}\x{0591}-\x{05bd}\x{05bf}\x{05c1}\x{05c2}\x{05c4}\x{05c5}\x{05c7}\x{0610}-\x{061a}\x{064b}-\x{0669}\x{0670}\x{06d6}-\x{06dc}\x{06df}-\x{06e4}\x{06e7}\x{06e8}\x{06ea}-\x{06ed}\x{06f0}-\x{06f9}\x{0711}\x{0730}-\x{074a}\x{07a6}-\x{07b0}\x{07c0}-\x{07c9}\x{07eb}-\x{07f3}\x{0816}-\x{0819}\x{081b}-\x{0823}\x{0825}-\x{0827}\x{0829}-\x{082d}\x{0859}-\x{085b}\x{08e4}-\x{08fe}\x{0900}-\x{0903}\x{093a}-\x{093c}\x{093e}-\x{094f}\x{0951}-\x{0957}\x{0962}\x{0963}\x{0966}-\x{096f}\x{0981}-\x{0983}\x{09bc}\x{09be}-\x{09c4}\x{09c7}\x{09c8}\x{09cb}-\x{09cd}\x{09d7}\x{09e2}\x{09e3}\x{09e6}-\x{09ef}\x{0a01}-\x{0a03}\x{0a3c}\x{0a3e}-\x{0a42}\x{0a47}\x{0a48}\x{0a4b}-\x{0a4d}\x{0a51}\x{0a66}-\x{0a71}\x{0a75}\x{0a81}-\x{0a83}\x{0abc}\x{0abe}-\x{0ac5}\x{0ac7}-\x{0ac9}\x{0acb}-\x{0acd}\x{0ae2}\x{0ae3}\x{0ae6}-\x{0aef}\x{0b01}-\x{0b03}\x{0b3c}\x{0b3e}-\x{0b44}\x{0b47}\x{0b48}\x{0b4b}-\x{0b4d}\x{0b56}\x{0b57}\x{0b62}\x{0b63}\x{0b66}-\x{0b6f}\x{0b82}\x{0bbe}-\x{0bc2}\x{0bc6}-\x{0bc8}\x{0bca}-\x{0bcd}\x{0bd7}\x{0be6}-\x{0bef}\x{0c01}-\x{0c03}\x{0c3e}-\x{0c44}\x{0c46}-\x{0c48}\x{0c4a}-\x{0c4d}\x{0c55}\x{0c56}\x{0c62}\x{0c63}\x{0c66}-\x{0c6f}\x{0c82}\x{0c83}\x{0cbc}\x{0cbe}-\x{0cc4}\x{0cc6}-\x{0cc8}\x{0cca}-\x{0ccd}\x{0cd5}\x{0cd6}\x{0ce2}\x{0ce3}\x{0ce6}-\x{0cef}\x{0d02}\x{0d03}\x{0d3e}-\x{0d44}\x{0d46}-\x{0d48}\x{0d4a}-\x{0d4d}\x{0d57}\x{0d62}\x{0d63}\x{0d66}-\x{0d6f}\x{0d82}\x{0d83}\x{0dca}\x{0dcf}-\x{0dd4}\x{0dd6}\x{0dd8}-\x{0ddf}\x{0df2}\x{0df3}\x{0e31}\x{0e34}-\x{0e3a}\x{0e47}-\x{0e4e}\x{0e50}-\x{0e59}\x{0eb1}\x{0eb4}-\x{0eb9}\x{0ebb}\x{0ebc}\x{0ec8}-\x{0ecd}\x{0ed0}-\x{0ed9}\x{0f18}\x{0f19}\x{0f20}-\x{0f29}\x{0f35}\x{0f37}\x{0f39}\x{0f3e}\x{0f3f}\x{0f71}-\x{0f84}\x{0f86}\x{0f87}\x{0f8d}-\x{0f97}\x{0f99}-\x{0fbc}\x{0fc6}\x{102b}-\x{103e}\x{1040}-\x{1049}\x{1056}-\x{1059}\x{105e}-\x{1060}\x{1062}-\x{1064}\x{1067}-\x{106d}\x{1071}-\x{1074}\x{1082}-\x{108d}\x{108f}-\x{109d}\x{135d}-\x{135f}\x{1712}-\x{1714}\x{1732}-\x{1734}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17d3}\x{17dd}\x{17e0}-\x{17e9}\x{180b}-\x{180d}\x{1810}-\x{1819}\x{18a9}\x{1920}-\x{192b}\x{1930}-\x{193b}\x{1946}-\x{194f}\x{19b0}-\x{19c0}\x{19c8}\x{19c9}\x{19d0}-\x{19d9}\x{1a17}-\x{1a1b}\x{1a55}-\x{1a5e}\x{1a60}-\x{1a7c}\x{1a7f}-\x{1a89}\x{1a90}-\x{1a99}\x{1b00}-\x{1b04}\x{1b34}-\x{1b44}\x{1b50}-\x{1b59}\x{1b6b}-\x{1b73}\x{1b80}-\x{1b82}\x{1ba1}-\x{1bad}\x{1bb0}-\x{1bb9}\x{1be6}-\x{1bf3}\x{1c24}-\x{1c37}\x{1c40}-\x{1c49}\x{1c50}-\x{1c59}\x{1cd0}-\x{1cd2}\x{1cd4}-\x{1ce8}\x{1ced}\x{1cf2}-\x{1cf4}\x{1dc0}-\x{1de6}\x{1dfc}-\x{1dff}\x{200c}\x{200d}\x{203f}\x{2040}\x{2054}\x{20d0}-\x{20dc}\x{20e1}\x{20e5}-\x{20f0}\x{2cef}-\x{2cf1}\x{2d7f}\x{2de0}-\x{2dff}\x{302a}-\x{302f}\x{3099}\x{309a}\x{a620}-\x{a629}\x{a66f}\x{a674}-\x{a67d}\x{a69f}\x{a6f0}\x{a6f1}\x{a802}\x{a806}\x{a80b}\x{a823}-\x{a827}\x{a880}\x{a881}\x{a8b4}-\x{a8c4}\x{a8d0}-\x{a8d9}\x{a8e0}-\x{a8f1}\x{a900}-\x{a909}\x{a926}-\x{a92d}\x{a947}-\x{a953}\x{a980}-\x{a983}\x{a9b3}-\x{a9c0}\x{a9d0}-\x{a9d9}\x{aa29}-\x{aa36}\x{aa43}\x{aa4c}\x{aa4d}\x{aa50}-\x{aa59}\x{aa7b}\x{aab0}\x{aab2}-\x{aab4}\x{aab7}\x{aab8}\x{aabe}\x{aabf}\x{aac1}\x{aaeb}-\x{aaef}\x{aaf5}\x{aaf6}\x{abe3}-\x{abea}\x{abec}\x{abed}\x{abf0}-\x{abf9}\x{fb1e}\x{fe00}-\x{fe0f}\x{fe20}-\x{fe26}\x{fe33}\x{fe34}\x{fe4d}-\x{fe4f}\x{ff10}-\x{ff19}\x{ff3f}]*\b';
+
+ /**
+ * Full list of JavaScript reserved words.
+ * Will be loaded from /data/js/keywords_reserved.txt.
+ *
+ * @see https://mathiasbynens.be/notes/reserved-keywords
+ *
+ * @var string[]
+ */
+ protected $keywordsReserved = array();
+
+ /**
+ * List of JavaScript reserved words that accept a
+ * after them. Some end of lines are not the end of a statement, like with
+ * these keywords.
+ *
+ * E.g.: we shouldn't insert a ; after this else
+ * else
+ * console.log('this is quite fine')
+ *
+ * Will be loaded from /data/js/keywords_before.txt
+ *
+ * @var string[]
+ */
+ protected $keywordsBefore = array();
+
+ /**
+ * List of JavaScript reserved words that accept a
+ * before them. Some end of lines are not the end of a statement, like when
+ * continued by one of these keywords on the newline.
+ *
+ * E.g.: we shouldn't insert a ; before this instanceof
+ * variable
+ * instanceof String
+ *
+ * Will be loaded from /data/js/keywords_after.txt
+ *
+ * @var string[]
+ */
+ protected $keywordsAfter = array();
+
+ /**
+ * List of all JavaScript operators.
+ *
+ * Will be loaded from /data/js/operators.txt
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
+ *
+ * @var string[]
+ */
+ protected $operators = array();
+
+ /**
+ * List of JavaScript operators that accept a after
+ * them. Some end of lines are not the end of a statement, like with these
+ * operators.
+ *
+ * Note: Most operators are fine, we've only removed ++ and --.
+ * ++ & -- have to be joined with the value they're in-/decrementing.
+ *
+ * Will be loaded from /data/js/operators_before.txt
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
+ *
+ * @var string[]
+ */
+ protected $operatorsBefore = array();
+
+ /**
+ * List of JavaScript operators that accept a before
+ * them. Some end of lines are not the end of a statement, like when
+ * continued by one of these operators on the newline.
+ *
+ * Note: Most operators are fine, we've only removed ), ], ++, --, ! and ~.
+ * There can't be a newline separating ! or ~ and whatever it is negating.
+ * ++ & -- have to be joined with the value they're in-/decrementing.
+ * ) & ] are "special" in that they have lots or usecases. () for example
+ * is used for function calls, for grouping, in if () and for (), ...
+ *
+ * Will be loaded from /data/js/operators_after.txt
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
+ *
+ * @var string[]
+ */
+ protected $operatorsAfter = array();
+
+ /**
+ * {@inheritdoc}
+ */
+ public function __construct()
+ {
+ call_user_func_array(array('\\WP_Rocket\Dependencies\Minify\\Minify', '__construct'), func_get_args());
+
+ $dataDir = __DIR__.'/data/js/';
+ $options = FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES;
+ $this->keywordsReserved = file($dataDir.'keywords_reserved.txt', $options);
+ $this->keywordsBefore = file($dataDir.'keywords_before.txt', $options);
+ $this->keywordsAfter = file($dataDir.'keywords_after.txt', $options);
+ $this->operators = file($dataDir.'operators.txt', $options);
+ $this->operatorsBefore = file($dataDir.'operators_before.txt', $options);
+ $this->operatorsAfter = file($dataDir.'operators_after.txt', $options);
+ }
+
+ /**
+ * Minify the data.
+ * Perform JS optimizations.
+ *
+ * @param string[optional] $path Path to write the data to
+ *
+ * @return string The minified data
+ */
+ public function execute($path = null)
+ {
+ $content = '';
+
+ /*
+ * Let's first take out strings, comments and regular expressions.
+ * All of these can contain JS code-like characters, and we should make
+ * sure any further magic ignores anything inside of these.
+ *
+ * Consider this example, where we should not strip any whitespace:
+ * var str = "a test";
+ *
+ * Comments will be removed altogether, strings and regular expressions
+ * will be replaced by placeholder text, which we'll restore later.
+ */
+ $this->extractStrings('\'"`');
+ $this->stripComments();
+ $this->extractRegex();
+
+ // loop files
+ foreach ($this->data as $source => $js) {
+ // take out strings, comments & regex (for which we've registered
+ // the regexes just a few lines earlier)
+ $js = $this->replace($js);
+
+ $js = $this->propertyNotation($js);
+ $js = $this->shortenBools($js);
+ $js = $this->stripWhitespace($js);
+
+ // combine js: separating the scripts by a ;
+ $content .= $js.";";
+ }
+
+ // clean up leftover `;`s from the combination of multiple scripts
+ $content = ltrim($content, ';');
+ $content = (string) substr($content, 0, -1);
+
+ /*
+ * Earlier, we extracted strings & regular expressions and replaced them
+ * with placeholder text. This will restore them.
+ */
+ $content = $this->restoreExtractedData($content);
+
+ return $content;
+ }
+
+ /**
+ * Strip comments from source code.
+ */
+ protected function stripComments()
+ {
+ // PHP only supports $this inside anonymous functions since 5.4
+ $minifier = $this;
+ $callback = function ($match) use ($minifier) {
+ if (
+ substr($match[1], 0, 1) === '!' ||
+ strpos($match[1], '@license') !== false ||
+ strpos($match[1], '@preserve') !== false
+ ) {
+ // preserve multi-line comments that start with /*!
+ // or contain @license or @preserve annotations
+ $count = count($minifier->extracted);
+ $placeholder = '/*'.$count.'*/';
+ $minifier->extracted[$placeholder] = $match[0];
+
+ return $placeholder;
+ }
+
+ return '';
+ };
+
+ // multi-line comments
+ $this->registerPattern('/\n?\/\*(.*?)\*\/\n?/s', $callback);
+
+ // single-line comments
+ $this->registerPattern('/\/\/.*$/m', '');
+ }
+
+ /**
+ * JS can have /-delimited regular expressions, like: /ab+c/.match(string).
+ *
+ * The content inside the regex can contain characters that may be confused
+ * for JS code: e.g. it could contain whitespace it needs to match & we
+ * don't want to strip whitespace in there.
+ *
+ * The regex can be pretty simple: we don't have to care about comments,
+ * (which also use slashes) because stripComments() will have stripped those
+ * already.
+ *
+ * This method will replace all string content with simple REGEX#
+ * placeholder text, so we've rid all regular expressions from characters
+ * that may be misinterpreted. Original regex content will be saved in
+ * $this->extracted and after doing all other minifying, we can restore the
+ * original content via restoreRegex()
+ */
+ protected function extractRegex()
+ {
+ // PHP only supports $this inside anonymous functions since 5.4
+ $minifier = $this;
+ $callback = function ($match) use ($minifier) {
+ $count = count($minifier->extracted);
+ $placeholder = '"'.$count.'"';
+ $minifier->extracted[$placeholder] = $match[0];
+
+ return $placeholder;
+ };
+
+ // match all chars except `/` and `\`
+ // `\` is allowed though, along with whatever char follows (which is the
+ // one being escaped)
+ // this should allow all chars, except for an unescaped `/` (= the one
+ // closing the regex)
+ // then also ignore bare `/` inside `[]`, where they don't need to be
+ // escaped: anything inside `[]` can be ignored safely
+ $pattern = '\\/(?!\*)(?:[^\\[\\/\\\\\n\r]++|(?:\\\\.)++|(?:\\[(?:[^\\]\\\\\n\r]++|(?:\\\\.)++)++\\])++)++\\/[gimuy]*';
+
+ // a regular expression can only be followed by a few operators or some
+ // of the RegExp methods (a `\` followed by a variable or value is
+ // likely part of a division, not a regex)
+ $keywords = array('do', 'in', 'new', 'else', 'throw', 'yield', 'delete', 'return', 'typeof');
+ $before = '(^|[=:,;\+\-\*\/\}\(\{\[&\|!]|'.implode('|', $keywords).')\s*';
+ $propertiesAndMethods = array(
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Properties_2
+ 'constructor',
+ 'flags',
+ 'global',
+ 'ignoreCase',
+ 'multiline',
+ 'source',
+ 'sticky',
+ 'unicode',
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Methods_2
+ 'compile(',
+ 'exec(',
+ 'test(',
+ 'toSource(',
+ 'toString(',
+ );
+ $delimiters = array_fill(0, count($propertiesAndMethods), '/');
+ $propertiesAndMethods = array_map('preg_quote', $propertiesAndMethods, $delimiters);
+ $after = '(?=\s*([\.,;\)\}&\|+]|\/\/|$|\.('.implode('|', $propertiesAndMethods).')))';
+ $this->registerPattern('/'.$before.'\K'.$pattern.$after.'/', $callback);
+
+ // regular expressions following a `)` are rather annoying to detect...
+ // quite often, `/` after `)` is a division operator & if it happens to
+ // be followed by another one (or a comment), it is likely to be
+ // confused for a regular expression
+ // however, it's perfectly possible for a regex to follow a `)`: after
+ // a single-line `if()`, `while()`, ... statement, for example
+ // since, when they occur like that, they're always the start of a
+ // statement, there's only a limited amount of ways they can be useful:
+ // by calling the regex methods directly
+ // if a regex following `)` is not followed by `.`,
+ // it's quite likely not a regex
+ $before = '\)\s*';
+ $after = '(?=\s*\.('.implode('|', $propertiesAndMethods).'))';
+ $this->registerPattern('/'.$before.'\K'.$pattern.$after.'/', $callback);
+
+ // 1 more edge case: a regex can be followed by a lot more operators or
+ // keywords if there's a newline (ASI) in between, where the operator
+ // actually starts a new statement
+ // (https://github.com/matthiasmullie/minify/issues/56)
+ $operators = $this->getOperatorsForRegex($this->operatorsBefore, '/');
+ $operators += $this->getOperatorsForRegex($this->keywordsReserved, '/');
+ $after = '(?=\s*\n\s*('.implode('|', $operators).'))';
+ $this->registerPattern('/'.$pattern.$after.'/', $callback);
+ }
+
+ /**
+ * Strip whitespace.
+ *
+ * We won't strip *all* whitespace, but as much as possible. The thing that
+ * we'll preserve are newlines we're unsure about.
+ * JavaScript doesn't require statements to be terminated with a semicolon.
+ * It will automatically fix missing semicolons with ASI (automatic semi-
+ * colon insertion) at the end of line causing errors (without semicolon.)
+ *
+ * Because it's sometimes hard to tell if a newline is part of a statement
+ * that should be terminated or not, we'll just leave some of them alone.
+ *
+ * @param string $content The content to strip the whitespace for
+ *
+ * @return string
+ */
+ protected function stripWhitespace($content)
+ {
+ // uniform line endings, make them all line feed
+ $content = str_replace(array("\r\n", "\r"), "\n", $content);
+
+ // collapse all non-line feed whitespace into a single space
+ $content = preg_replace('/[^\S\n]+/', ' ', $content);
+
+ // strip leading & trailing whitespace
+ $content = str_replace(array(" \n", "\n "), "\n", $content);
+
+ // collapse consecutive line feeds into just 1
+ $content = preg_replace('/\n+/', "\n", $content);
+
+ $operatorsBefore = $this->getOperatorsForRegex($this->operatorsBefore, '/');
+ $operatorsAfter = $this->getOperatorsForRegex($this->operatorsAfter, '/');
+ $operators = $this->getOperatorsForRegex($this->operators, '/');
+ $keywordsBefore = $this->getKeywordsForRegex($this->keywordsBefore, '/');
+ $keywordsAfter = $this->getKeywordsForRegex($this->keywordsAfter, '/');
+
+ // strip whitespace that ends in (or next line begin with) an operator
+ // that allows statements to be broken up over multiple lines
+ unset($operatorsBefore['+'], $operatorsBefore['-'], $operatorsAfter['+'], $operatorsAfter['-']);
+ $content = preg_replace(
+ array(
+ '/('.implode('|', $operatorsBefore).')\s+/',
+ '/\s+('.implode('|', $operatorsAfter).')/',
+ ),
+ '\\1',
+ $content
+ );
+
+ // make sure + and - can't be mistaken for, or joined into ++ and --
+ $content = preg_replace(
+ array(
+ '/(?%&|', $delimiter);
+ $operators['='] = '(?keywordsReserved;
+ $callback = function ($match) use ($minifier, $keywords) {
+ $property = trim($minifier->extracted[$match[1]], '\'"');
+
+ /*
+ * Check if the property is a reserved keyword. In this context (as
+ * property of an object literal/array) it shouldn't matter, but IE8
+ * freaks out with "Expected identifier".
+ */
+ if (in_array($property, $keywords)) {
+ return $match[0];
+ }
+
+ /*
+ * See if the property is in a variable-like format (e.g.
+ * array['key-here'] can't be replaced by array.key-here since '-'
+ * is not a valid character there.
+ */
+ if (!preg_match('/^'.$minifier::REGEX_VARIABLE.'$/u', $property)) {
+ return $match[0];
+ }
+
+ return '.'.$property;
+ };
+
+ /*
+ * Figure out if previous character is a variable name (of the array
+ * we want to use property notation on) - this is to make sure
+ * standalone ['value'] arrays aren't confused for keys-of-an-array.
+ * We can (and only have to) check the last character, because PHP's
+ * regex implementation doesn't allow unfixed-length look-behind
+ * assertions.
+ */
+ preg_match('/(\[[^\]]+\])[^\]]*$/', static::REGEX_VARIABLE, $previousChar);
+ $previousChar = $previousChar[1];
+
+ /*
+ * Make sure word preceding the ['value'] is not a keyword, e.g.
+ * return['x']. Because -again- PHP's regex implementation doesn't allow
+ * unfixed-length look-behind assertions, I'm just going to do a lot of
+ * separate look-behind assertions, one for each keyword.
+ */
+ $keywords = $this->getKeywordsForRegex($keywords);
+ $keywords = '(?
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+namespace WP_Rocket\Dependencies\Minify;
+
+use WP_Rocket\Dependencies\Minify\Exceptions\IOException;
+use Psr\Cache\CacheItemInterface;
+
+/**
+ * Abstract minifier class.
+ *
+ * Please report bugs on https://github.com/matthiasmullie/minify/issues
+ *
+ * @package Minify
+ * @author Matthias Mullie
+ * @copyright Copyright (c) 2012, Matthias Mullie. All rights reserved
+ * @license MIT License
+ */
+abstract class Minify
+{
+ /**
+ * The data to be minified.
+ *
+ * @var string[]
+ */
+ protected $data = array();
+
+ /**
+ * Array of patterns to match.
+ *
+ * @var string[]
+ */
+ protected $patterns = array();
+
+ /**
+ * This array will hold content of strings and regular expressions that have
+ * been extracted from the JS source code, so we can reliably match "code",
+ * without having to worry about potential "code-like" characters inside.
+ *
+ * @var string[]
+ */
+ public $extracted = array();
+
+ /**
+ * Init the minify class - optionally, code may be passed along already.
+ */
+ public function __construct(/* $data = null, ... */)
+ {
+ // it's possible to add the source through the constructor as well ;)
+ if (func_num_args()) {
+ call_user_func_array(array($this, 'add'), func_get_args());
+ }
+ }
+
+ /**
+ * Add a file or straight-up code to be minified.
+ *
+ * @param string|string[] $data
+ *
+ * @return static
+ */
+ public function add($data /* $data = null, ... */)
+ {
+ // bogus "usage" of parameter $data: scrutinizer warns this variable is
+ // not used (we're using func_get_args instead to support overloading),
+ // but it still needs to be defined because it makes no sense to have
+ // this function without argument :)
+ $args = array($data) + func_get_args();
+
+ // this method can be overloaded
+ foreach ($args as $data) {
+ if (is_array($data)) {
+ call_user_func_array(array($this, 'add'), $data);
+ continue;
+ }
+
+ // redefine var
+ $data = (string) $data;
+
+ // load data
+ $value = $this->load($data);
+ $key = ($data != $value) ? $data : count($this->data);
+
+ // replace CR linefeeds etc.
+ // @see https://github.com/matthiasmullie/minify/pull/139
+ $value = str_replace(array("\r\n", "\r"), "\n", $value);
+
+ // store data
+ $this->data[$key] = $value;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Add a file to be minified.
+ *
+ * @param string|string[] $data
+ *
+ * @return static
+ *
+ * @throws IOException
+ */
+ public function addFile($data /* $data = null, ... */)
+ {
+ // bogus "usage" of parameter $data: scrutinizer warns this variable is
+ // not used (we're using func_get_args instead to support overloading),
+ // but it still needs to be defined because it makes no sense to have
+ // this function without argument :)
+ $args = array($data) + func_get_args();
+
+ // this method can be overloaded
+ foreach ($args as $path) {
+ if (is_array($path)) {
+ call_user_func_array(array($this, 'addFile'), $path);
+ continue;
+ }
+
+ // redefine var
+ $path = (string) $path;
+
+ // check if we can read the file
+ if (!$this->canImportFile($path)) {
+ throw new IOException('The file "'.$path.'" could not be opened for reading. Check if PHP has enough permissions.');
+ }
+
+ $this->add($path);
+ }
+
+ return $this;
+ }
+
+ /**
+ * Minify the data & (optionally) saves it to a file.
+ *
+ * @param string[optional] $path Path to write the data to
+ *
+ * @return string The minified data
+ */
+ public function minify($path = null)
+ {
+ $content = $this->execute($path);
+
+ // save to path
+ if ($path !== null) {
+ $this->save($content, $path);
+ }
+
+ return $content;
+ }
+
+ /**
+ * Minify & gzip the data & (optionally) saves it to a file.
+ *
+ * @param string[optional] $path Path to write the data to
+ * @param int[optional] $level Compression level, from 0 to 9
+ *
+ * @return string The minified & gzipped data
+ */
+ public function gzip($path = null, $level = 9)
+ {
+ $content = $this->execute($path);
+ $content = gzencode($content, $level, FORCE_GZIP);
+
+ // save to path
+ if ($path !== null) {
+ $this->save($content, $path);
+ }
+
+ return $content;
+ }
+
+ /**
+ * Minify the data & write it to a CacheItemInterface object.
+ *
+ * @param CacheItemInterface $item Cache item to write the data to
+ *
+ * @return CacheItemInterface Cache item with the minifier data
+ */
+ public function cache(CacheItemInterface $item)
+ {
+ $content = $this->execute();
+ $item->set($content);
+
+ return $item;
+ }
+
+ /**
+ * Minify the data.
+ *
+ * @param string[optional] $path Path to write the data to
+ *
+ * @return string The minified data
+ */
+ abstract public function execute($path = null);
+
+ /**
+ * Load data.
+ *
+ * @param string $data Either a path to a file or the content itself
+ *
+ * @return string
+ */
+ protected function load($data)
+ {
+ // check if the data is a file
+ if ($this->canImportFile($data)) {
+ $data = file_get_contents($data);
+
+ // strip BOM, if any
+ if (substr($data, 0, 3) == "\xef\xbb\xbf") {
+ $data = substr($data, 3);
+ }
+ }
+
+ return $data;
+ }
+
+ /**
+ * Save to file.
+ *
+ * @param string $content The minified data
+ * @param string $path The path to save the minified data to
+ *
+ * @throws IOException
+ */
+ protected function save($content, $path)
+ {
+ $handler = $this->openFileForWriting($path);
+
+ $this->writeToFile($handler, $content);
+
+ @fclose($handler);
+ }
+
+ /**
+ * Register a pattern to execute against the source content.
+ *
+ * If $replacement is a string, it must be plain text. Placeholders like $1 or \2 don't work.
+ * If you need that functionality, use a callback instead.
+ *
+ * @param string $pattern PCRE pattern
+ * @param string|callable $replacement Replacement value for matched pattern
+ */
+ protected function registerPattern($pattern, $replacement = '')
+ {
+ // study the pattern, we'll execute it more than once
+ $pattern .= 'S';
+
+ $this->patterns[] = array($pattern, $replacement);
+ }
+
+ /**
+ * We can't "just" run some regular expressions against JavaScript: it's a
+ * complex language. E.g. having an occurrence of // xyz would be a comment,
+ * unless it's used within a string. Of you could have something that looks
+ * like a 'string', but inside a comment.
+ * The only way to accurately replace these pieces is to traverse the JS one
+ * character at a time and try to find whatever starts first.
+ *
+ * @param string $content The content to replace patterns in
+ *
+ * @return string The (manipulated) content
+ */
+ protected function replace($content)
+ {
+ $contentLength = strlen($content);
+ $output = '';
+ $processedOffset = 0;
+ $positions = array_fill(0, count($this->patterns), -1);
+ $matches = array();
+
+ while ($processedOffset < $contentLength) {
+ // find first match for all patterns
+ foreach ($this->patterns as $i => $pattern) {
+ list($pattern, $replacement) = $pattern;
+
+ // we can safely ignore patterns for positions we've unset earlier,
+ // because we know these won't show up anymore
+ if (array_key_exists($i, $positions) == false) {
+ continue;
+ }
+
+ // no need to re-run matches that are still in the part of the
+ // content that hasn't been processed
+ if ($positions[$i] >= $processedOffset) {
+ continue;
+ }
+
+ $match = null;
+ if (preg_match($pattern, $content, $match, PREG_OFFSET_CAPTURE, $processedOffset)) {
+ $matches[$i] = $match;
+
+ // we'll store the match position as well; that way, we
+ // don't have to redo all preg_matches after changing only
+ // the first (we'll still know where those others are)
+ $positions[$i] = $match[0][1];
+ } else {
+ // if the pattern couldn't be matched, there's no point in
+ // executing it again in later runs on this same content;
+ // ignore this one until we reach end of content
+ unset($matches[$i], $positions[$i]);
+ }
+ }
+
+ // no more matches to find: everything's been processed, break out
+ if (!$matches) {
+ // output the remaining content
+ $output .= substr($content, $processedOffset);
+ break;
+ }
+
+ // see which of the patterns actually found the first thing (we'll
+ // only want to execute that one, since we're unsure if what the
+ // other found was not inside what the first found)
+ $matchOffset = min($positions);
+ $firstPattern = array_search($matchOffset, $positions);
+ $match = $matches[$firstPattern];
+
+ // execute the pattern that matches earliest in the content string
+ list(, $replacement) = $this->patterns[$firstPattern];
+
+ // add the part of the input between $processedOffset and the first match;
+ // that content wasn't matched by anything
+ $output .= substr($content, $processedOffset, $matchOffset - $processedOffset);
+ // add the replacement for the match
+ $output .= $this->executeReplacement($replacement, $match);
+ // advance $processedOffset past the match
+ $processedOffset = $matchOffset + strlen($match[0][0]);
+ }
+
+ return $output;
+ }
+
+ /**
+ * If $replacement is a callback, execute it, passing in the match data.
+ * If it's a string, just pass it through.
+ *
+ * @param string|callable $replacement Replacement value
+ * @param array $match Match data, in PREG_OFFSET_CAPTURE form
+ *
+ * @return string
+ */
+ protected function executeReplacement($replacement, $match)
+ {
+ if (!is_callable($replacement)) {
+ return $replacement;
+ }
+ // convert $match from the PREG_OFFSET_CAPTURE form to the form the callback expects
+ foreach ($match as &$matchItem) {
+ $matchItem = $matchItem[0];
+ }
+ return $replacement($match);
+ }
+
+ /**
+ * Strings are a pattern we need to match, in order to ignore potential
+ * code-like content inside them, but we just want all of the string
+ * content to remain untouched.
+ *
+ * This method will replace all string content with simple STRING#
+ * placeholder text, so we've rid all strings from characters that may be
+ * misinterpreted. Original string content will be saved in $this->extracted
+ * and after doing all other minifying, we can restore the original content
+ * via restoreStrings().
+ *
+ * @param string[optional] $chars
+ * @param string[optional] $placeholderPrefix
+ */
+ protected function extractStrings($chars = '\'"', $placeholderPrefix = '')
+ {
+ // PHP only supports $this inside anonymous functions since 5.4
+ $minifier = $this;
+ $callback = function ($match) use ($minifier, $placeholderPrefix) {
+ // check the second index here, because the first always contains a quote
+ if ($match[2] === '') {
+ /*
+ * Empty strings need no placeholder; they can't be confused for
+ * anything else anyway.
+ * But we still needed to match them, for the extraction routine
+ * to skip over this particular string.
+ */
+ return $match[0];
+ }
+
+ $count = count($minifier->extracted);
+ $placeholder = $match[1].$placeholderPrefix.$count.$match[1];
+ $minifier->extracted[$placeholder] = $match[1].$match[2].$match[1];
+
+ return $placeholder;
+ };
+
+ /*
+ * The \\ messiness explained:
+ * * Don't count ' or " as end-of-string if it's escaped (has backslash
+ * in front of it)
+ * * Unless... that backslash itself is escaped (another leading slash),
+ * in which case it's no longer escaping the ' or "
+ * * So there can be either no backslash, or an even number
+ * * multiply all of that times 4, to account for the escaping that has
+ * to be done to pass the backslash into the PHP string without it being
+ * considered as escape-char (times 2) and to get it in the regex,
+ * escaped (times 2)
+ */
+ $this->registerPattern('/(['.$chars.'])(.*?(?extracted.
+ *
+ * @param string $content
+ *
+ * @return string
+ */
+ protected function restoreExtractedData($content)
+ {
+ if (!$this->extracted) {
+ // nothing was extracted, nothing to restore
+ return $content;
+ }
+
+ $content = strtr($content, $this->extracted);
+
+ $this->extracted = array();
+
+ return $content;
+ }
+
+ /**
+ * Check if the path is a regular file and can be read.
+ *
+ * @param string $path
+ *
+ * @return bool
+ */
+ protected function canImportFile($path)
+ {
+ $parsed = parse_url($path);
+ if (
+ // file is elsewhere
+ isset($parsed['host']) ||
+ // file responds to queries (may change, or need to bypass cache)
+ isset($parsed['query'])
+ ) {
+ return false;
+ }
+
+ return strlen($path) < PHP_MAXPATHLEN && @is_file($path) && is_readable($path);
+ }
+
+ /**
+ * Attempts to open file specified by $path for writing.
+ *
+ * @param string $path The path to the file
+ *
+ * @return resource Specifier for the target file
+ *
+ * @throws IOException
+ */
+ protected function openFileForWriting($path)
+ {
+ if ($path === '' || ($handler = @fopen($path, 'w')) === false) {
+ throw new IOException('The file "'.$path.'" could not be opened for writing. Check if PHP has enough permissions.');
+ }
+
+ return $handler;
+ }
+
+ /**
+ * Attempts to write $content to the file specified by $handler. $path is used for printing exceptions.
+ *
+ * @param resource $handler The resource to write to
+ * @param string $content The content to write
+ * @param string $path The path to the file (for exception printing only)
+ *
+ * @throws IOException
+ */
+ protected function writeToFile($handler, $content, $path = '')
+ {
+ if (
+ !is_resource($handler) ||
+ ($result = @fwrite($handler, $content)) === false ||
+ ($result < strlen($content))
+ ) {
+ throw new IOException('The file "'.$path.'" could not be written to. Check your disk space and file permissions.');
+ }
+ }
+}
diff --git a/inc/Dependencies/Minify/data/js/keywords_after.txt b/inc/Dependencies/Minify/data/js/keywords_after.txt
new file mode 100644
index 0000000..5c8cba7
--- /dev/null
+++ b/inc/Dependencies/Minify/data/js/keywords_after.txt
@@ -0,0 +1,7 @@
+in
+public
+extends
+private
+protected
+implements
+instanceof
\ No newline at end of file
diff --git a/inc/Dependencies/Minify/data/js/keywords_before.txt b/inc/Dependencies/Minify/data/js/keywords_before.txt
new file mode 100644
index 0000000..5abf357
--- /dev/null
+++ b/inc/Dependencies/Minify/data/js/keywords_before.txt
@@ -0,0 +1,26 @@
+do
+in
+let
+new
+var
+case
+else
+enum
+void
+with
+class
+const
+yield
+delete
+export
+import
+public
+static
+typeof
+extends
+package
+private
+function
+protected
+implements
+instanceof
\ No newline at end of file
diff --git a/inc/Dependencies/Minify/data/js/keywords_reserved.txt b/inc/Dependencies/Minify/data/js/keywords_reserved.txt
new file mode 100644
index 0000000..2a3ad3c
--- /dev/null
+++ b/inc/Dependencies/Minify/data/js/keywords_reserved.txt
@@ -0,0 +1,63 @@
+do
+if
+in
+for
+let
+new
+try
+var
+case
+else
+enum
+eval
+null
+this
+true
+void
+with
+break
+catch
+class
+const
+false
+super
+throw
+while
+yield
+delete
+export
+import
+public
+return
+static
+switch
+typeof
+default
+extends
+finally
+package
+private
+continue
+debugger
+function
+arguments
+interface
+protected
+implements
+instanceof
+abstract
+boolean
+byte
+char
+double
+final
+float
+goto
+int
+long
+native
+short
+synchronized
+throws
+transient
+volatile
\ No newline at end of file
diff --git a/inc/Dependencies/Minify/data/js/operators.txt b/inc/Dependencies/Minify/data/js/operators.txt
new file mode 100644
index 0000000..e66229a
--- /dev/null
+++ b/inc/Dependencies/Minify/data/js/operators.txt
@@ -0,0 +1,46 @@
++
+-
+*
+/
+%
+=
++=
+-=
+*=
+/=
+%=
+<<=
+>>=
+>>>=
+&=
+^=
+|=
+&
+|
+^
+~
+<<
+>>
+>>>
+==
+===
+!=
+!==
+>
+<
+>=
+<=
+&&
+||
+!
+.
+[
+]
+?
+:
+,
+;
+(
+)
+{
+}
\ No newline at end of file
diff --git a/inc/Dependencies/Minify/data/js/operators_after.txt b/inc/Dependencies/Minify/data/js/operators_after.txt
new file mode 100644
index 0000000..71a9b70
--- /dev/null
+++ b/inc/Dependencies/Minify/data/js/operators_after.txt
@@ -0,0 +1,43 @@
++
+-
+*
+/
+%
+=
++=
+-=
+*=
+/=
+%=
+<<=
+>>=
+>>>=
+&=
+^=
+|=
+&
+|
+^
+<<
+>>
+>>>
+==
+===
+!=
+!==
+>
+<
+>=
+<=
+&&
+||
+.
+[
+]
+?
+:
+,
+;
+(
+)
+}
\ No newline at end of file
diff --git a/inc/Dependencies/Minify/data/js/operators_before.txt b/inc/Dependencies/Minify/data/js/operators_before.txt
new file mode 100644
index 0000000..ff50d87
--- /dev/null
+++ b/inc/Dependencies/Minify/data/js/operators_before.txt
@@ -0,0 +1,43 @@
++
+-
+*
+/
+%
+=
++=
+-=
+*=
+/=
+%=
+<<=
+>>=
+>>>=
+&=
+^=
+|=
+&
+|
+^
+~
+<<
+>>
+>>>
+==
+===
+!=
+!==
+>
+<
+>=
+<=
+&&
+||
+!
+.
+[
+?
+:
+,
+;
+(
+{
diff --git a/inc/Dependencies/Monolog/ErrorHandler.php b/inc/Dependencies/Monolog/ErrorHandler.php
new file mode 100644
index 0000000..faa26b5
--- /dev/null
+++ b/inc/Dependencies/Monolog/ErrorHandler.php
@@ -0,0 +1,239 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace WP_Rocket\Dependencies\Monolog;
+
+use WP_Rocket\Dependencies\Psr\Log\LoggerInterface;
+use WP_Rocket\Dependencies\Psr\Log\LogLevel;
+use WP_Rocket\Dependencies\Monolog\Handler\AbstractHandler;
+
+/**
+ * WP_Rocket\Dependencies\Monolog error handler
+ *
+ * A facility to enable logging of runtime errors, exceptions and fatal errors.
+ *
+ * Quick setup: ErrorHandler::register($logger);
+ *
+ * @author Jordi Boggiano
+ */
+class ErrorHandler
+{
+ private $logger;
+
+ private $previousExceptionHandler;
+ private $uncaughtExceptionLevel;
+
+ private $previousErrorHandler;
+ private $errorLevelMap;
+ private $handleOnlyReportedErrors;
+
+ private $hasFatalErrorHandler;
+ private $fatalLevel;
+ private $reservedMemory;
+ private $lastFatalTrace;
+ private static $fatalErrors = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);
+
+ public function __construct(LoggerInterface $logger)
+ {
+ $this->logger = $logger;
+ }
+
+ /**
+ * Registers a new ErrorHandler for a given Logger
+ *
+ * By default it will handle errors, exceptions and fatal errors
+ *
+ * @param LoggerInterface $logger
+ * @param array|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
+ * @param int|false $exceptionLevel a LogLevel::* constant, or false to disable exception handling
+ * @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling
+ * @return ErrorHandler
+ */
+ public static function register(LoggerInterface $logger, $errorLevelMap = array(), $exceptionLevel = null, $fatalLevel = null)
+ {
+ //Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929
+ class_exists('\\Psr\\Log\\LogLevel', true);
+
+ /** @phpstan-ignore-next-line */
+ $handler = new static($logger);
+ if ($errorLevelMap !== false) {
+ $handler->registerErrorHandler($errorLevelMap);
+ }
+ if ($exceptionLevel !== false) {
+ $handler->registerExceptionHandler($exceptionLevel);
+ }
+ if ($fatalLevel !== false) {
+ $handler->registerFatalHandler($fatalLevel);
+ }
+
+ return $handler;
+ }
+
+ public function registerExceptionHandler($level = null, $callPrevious = true)
+ {
+ $prev = set_exception_handler(array($this, 'handleException'));
+ $this->uncaughtExceptionLevel = $level;
+ if ($callPrevious && $prev) {
+ $this->previousExceptionHandler = $prev;
+ }
+ }
+
+ public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true)
+ {
+ $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
+ $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
+ if ($callPrevious) {
+ $this->previousErrorHandler = $prev ?: true;
+ }
+
+ $this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
+ }
+
+ public function registerFatalHandler($level = null, $reservedMemorySize = 20)
+ {
+ register_shutdown_function(array($this, 'handleFatalError'));
+
+ $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
+ $this->fatalLevel = $level;
+ $this->hasFatalErrorHandler = true;
+ }
+
+ protected function defaultErrorLevelMap()
+ {
+ return array(
+ E_ERROR => LogLevel::CRITICAL,
+ E_WARNING => LogLevel::WARNING,
+ E_PARSE => LogLevel::ALERT,
+ E_NOTICE => LogLevel::NOTICE,
+ E_CORE_ERROR => LogLevel::CRITICAL,
+ E_CORE_WARNING => LogLevel::WARNING,
+ E_COMPILE_ERROR => LogLevel::ALERT,
+ E_COMPILE_WARNING => LogLevel::WARNING,
+ E_USER_ERROR => LogLevel::ERROR,
+ E_USER_WARNING => LogLevel::WARNING,
+ E_USER_NOTICE => LogLevel::NOTICE,
+ E_STRICT => LogLevel::NOTICE,
+ E_RECOVERABLE_ERROR => LogLevel::ERROR,
+ E_DEPRECATED => LogLevel::NOTICE,
+ E_USER_DEPRECATED => LogLevel::NOTICE,
+ );
+ }
+
+ /**
+ * @private
+ */
+ public function handleException($e)
+ {
+ $this->logger->log(
+ $this->uncaughtExceptionLevel === null ? LogLevel::ERROR : $this->uncaughtExceptionLevel,
+ sprintf('Uncaught Exception %s: "%s" at %s line %s', Utils::getClass($e), $e->getMessage(), $e->getFile(), $e->getLine()),
+ array('exception' => $e)
+ );
+
+ if ($this->previousExceptionHandler) {
+ call_user_func($this->previousExceptionHandler, $e);
+ }
+
+ exit(255);
+ }
+
+ /**
+ * @private
+ */
+ public function handleError($code, $message, $file = '', $line = 0, $context = array())
+ {
+ if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) {
+ return;
+ }
+
+ // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries
+ if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) {
+ $level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : LogLevel::CRITICAL;
+ $this->logger->log($level, self::codeToString($code).': '.$message, array('code' => $code, 'message' => $message, 'file' => $file, 'line' => $line));
+ } else {
+ // http://php.net/manual/en/function.debug-backtrace.php
+ // As of 5.3.6, DEBUG_BACKTRACE_IGNORE_ARGS option was added.
+ // Any version less than 5.3.6 must use the DEBUG_BACKTRACE_IGNORE_ARGS constant value '2'.
+ $trace = debug_backtrace((PHP_VERSION_ID < 50306) ? 2 : DEBUG_BACKTRACE_IGNORE_ARGS);
+ array_shift($trace); // Exclude handleError from trace
+ $this->lastFatalTrace = $trace;
+ }
+
+ if ($this->previousErrorHandler === true) {
+ return false;
+ } elseif ($this->previousErrorHandler) {
+ return call_user_func($this->previousErrorHandler, $code, $message, $file, $line, $context);
+ }
+ }
+
+ /**
+ * @private
+ */
+ public function handleFatalError()
+ {
+ $this->reservedMemory = null;
+
+ $lastError = error_get_last();
+ if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) {
+ $this->logger->log(
+ $this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel,
+ 'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
+ array('code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'trace' => $this->lastFatalTrace)
+ );
+
+ if ($this->logger instanceof Logger) {
+ foreach ($this->logger->getHandlers() as $handler) {
+ if ($handler instanceof AbstractHandler) {
+ $handler->close();
+ }
+ }
+ }
+ }
+ }
+
+ private static function codeToString($code)
+ {
+ switch ($code) {
+ case E_ERROR:
+ return 'E_ERROR';
+ case E_WARNING:
+ return 'E_WARNING';
+ case E_PARSE:
+ return 'E_PARSE';
+ case E_NOTICE:
+ return 'E_NOTICE';
+ case E_CORE_ERROR:
+ return 'E_CORE_ERROR';
+ case E_CORE_WARNING:
+ return 'E_CORE_WARNING';
+ case E_COMPILE_ERROR:
+ return 'E_COMPILE_ERROR';
+ case E_COMPILE_WARNING:
+ return 'E_COMPILE_WARNING';
+ case E_USER_ERROR:
+ return 'E_USER_ERROR';
+ case E_USER_WARNING:
+ return 'E_USER_WARNING';
+ case E_USER_NOTICE:
+ return 'E_USER_NOTICE';
+ case E_STRICT:
+ return 'E_STRICT';
+ case E_RECOVERABLE_ERROR:
+ return 'E_RECOVERABLE_ERROR';
+ case E_DEPRECATED:
+ return 'E_DEPRECATED';
+ case E_USER_DEPRECATED:
+ return 'E_USER_DEPRECATED';
+ }
+
+ return 'Unknown PHP error';
+ }
+}
diff --git a/inc/Dependencies/Monolog/Formatter/FormatterInterface.php b/inc/Dependencies/Monolog/Formatter/FormatterInterface.php
new file mode 100644
index 0000000..e4a3176
--- /dev/null
+++ b/inc/Dependencies/Monolog/Formatter/FormatterInterface.php
@@ -0,0 +1,36 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace WP_Rocket\Dependencies\Monolog\Formatter;
+
+/**
+ * Interface for formatters
+ *
+ * @author Jordi Boggiano
+ */
+interface FormatterInterface
+{
+ /**
+ * Formats a log record.
+ *
+ * @param array $record A record to format
+ * @return mixed The formatted record
+ */
+ public function format(array $record);
+
+ /**
+ * Formats a set of log records.
+ *
+ * @param array $records A set of records to format
+ * @return mixed The formatted set of records
+ */
+ public function formatBatch(array $records);
+}
diff --git a/inc/Dependencies/Monolog/Formatter/HtmlFormatter.php b/inc/Dependencies/Monolog/Formatter/HtmlFormatter.php
new file mode 100644
index 0000000..b8c2158
--- /dev/null
+++ b/inc/Dependencies/Monolog/Formatter/HtmlFormatter.php
@@ -0,0 +1,142 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace WP_Rocket\Dependencies\Monolog\Formatter;
+
+use WP_Rocket\Dependencies\Monolog\Logger;
+use WP_Rocket\Dependencies\Monolog\Utils;
+
+/**
+ * Formats incoming records into an HTML table
+ *
+ * This is especially useful for html email logging
+ *
+ * @author Tiago Brito
+ */
+class HtmlFormatter extends NormalizerFormatter
+{
+ /**
+ * Translates WP_Rocket\Dependencies\Monolog log levels to html color priorities.
+ */
+ protected $logLevels = array(
+ Logger::DEBUG => '#cccccc',
+ Logger::INFO => '#468847',
+ Logger::NOTICE => '#3a87ad',
+ Logger::WARNING => '#c09853',
+ Logger::ERROR => '#f0ad4e',
+ Logger::CRITICAL => '#FF7708',
+ Logger::ALERT => '#C12A19',
+ Logger::EMERGENCY => '#000000',
+ );
+
+ /**
+ * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
+ */
+ public function __construct($dateFormat = null)
+ {
+ parent::__construct($dateFormat);
+ }
+
+ /**
+ * Creates an HTML table row
+ *
+ * @param string $th Row header content
+ * @param string $td Row standard cell content
+ * @param bool $escapeTd false if td content must not be html escaped
+ * @return string
+ */
+ protected function addRow($th, $td = ' ', $escapeTd = true)
+ {
+ $th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
+ if ($escapeTd) {
+ $td = '
'.htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8').'
';
+ }
+
+ return "
\n
$th:
\n
".$td."
\n
";
+ }
+
+ /**
+ * Create a HTML h1 tag
+ *
+ * @param string $title Text to be in the h1
+ * @param int $level Error level
+ * @return string
+ */
+ protected function addTitle($title, $level)
+ {
+ $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');
+
+ return '
'.$title.'
';
+ }
+
+ /**
+ * Formats a log record.
+ *
+ * @param array $record A record to format
+ * @return mixed The formatted record
+ */
+ public function format(array $record)
+ {
+ $output = $this->addTitle($record['level_name'], $record['level']);
+ $output .= '