D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
proc
/
self
/
root
/
proc
/
self
/
root
/
home
/
vblioqus
/
karachi777.vip
/
in
/
106014
/
900508
/
Filename :
vendor.tar
back
Copy
a5hleyrich/wp-background-processing/classes/wp-background-process.php 0000644 00000055371 15151523431 0022116 0 ustar 00 <?php /** * WP Background Process * * @package WP-Background-Processing */ /** * Abstract WP_Background_Process class. * * @abstract * @extends WP_Async_Request */ abstract class WP_Background_Process extends WP_Async_Request { /** * The default query arg name used for passing the chain ID to new processes. */ const CHAIN_ID_ARG_NAME = 'chain_id'; /** * Unique background process chain ID. * * @var string */ private $chain_id; /** * Action * * (default value: 'background_process') * * @var string * @access protected */ protected $action = 'background_process'; /** * Start time of current process. * * (default value: 0) * * @var int * @access protected */ protected $start_time = 0; /** * Cron_hook_identifier * * @var string * @access protected */ protected $cron_hook_identifier; /** * Cron_interval_identifier * * @var string * @access protected */ protected $cron_interval_identifier; /** * Restrict object instantiation when using unserialize. * * @var bool|array */ protected $allowed_batch_data_classes = true; /** * The status set when process is cancelling. * * @var int */ const STATUS_CANCELLED = 1; /** * The status set when process is paused or pausing. * * @var int; */ const STATUS_PAUSED = 2; /** * Initiate new background process. * * @param bool|array $allowed_batch_data_classes Optional. Array of class names that can be unserialized. Default true (any class). */ public function __construct( $allowed_batch_data_classes = true ) { parent::__construct(); if ( empty( $allowed_batch_data_classes ) && false !== $allowed_batch_data_classes ) { $allowed_batch_data_classes = true; } if ( ! is_bool( $allowed_batch_data_classes ) && ! is_array( $allowed_batch_data_classes ) ) { $allowed_batch_data_classes = true; } // If allowed_batch_data_classes property set in subclass, // only apply override if not allowing any class. if ( true === $this->allowed_batch_data_classes || true !== $allowed_batch_data_classes ) { $this->allowed_batch_data_classes = $allowed_batch_data_classes; } $this->cron_hook_identifier = $this->identifier . '_cron'; $this->cron_interval_identifier = $this->identifier . '_cron_interval'; add_action( $this->cron_hook_identifier, array( $this, 'handle_cron_healthcheck' ) ); add_filter( 'cron_schedules', array( $this, 'schedule_cron_healthcheck' ) ); // Ensure dispatch query args included extra data. add_filter( $this->identifier . '_query_args', array( $this, 'filter_dispatch_query_args' ) ); } /** * Schedule the cron healthcheck and dispatch an async request to start processing the queue. * * @access public * @return array|WP_Error|false HTTP Response array, WP_Error on failure, or false if not attempted. */ public function dispatch() { if ( $this->is_processing() ) { // Process already running. return false; } /** * Filter fired before background process dispatches its next process. * * @param bool $cancel Should the dispatch be cancelled? Default false. * @param string $chain_id The background process chain ID. */ $cancel = apply_filters( $this->identifier . '_pre_dispatch', false, $this->get_chain_id() ); if ( $cancel ) { return false; } // Schedule the cron healthcheck. $this->schedule_event(); // Perform remote post. return parent::dispatch(); } /** * Push to the queue. * * Note, save must be called in order to persist queued items to a batch for processing. * * @param mixed $data Data. * * @return $this */ public function push_to_queue( $data ) { $this->data[] = $data; return $this; } /** * Save the queued items for future processing. * * @return $this */ public function save() { $key = $this->generate_key(); if ( ! empty( $this->data ) ) { update_site_option( $key, $this->data ); } // Clean out data so that new data isn't prepended with closed session's data. $this->data = array(); return $this; } /** * Update a batch's queued items. * * @param string $key Key. * @param array $data Data. * * @return $this */ public function update( $key, $data ) { if ( ! empty( $data ) ) { update_site_option( $key, $data ); } return $this; } /** * Delete a batch of queued items. * * @param string $key Key. * * @return $this */ public function delete( $key ) { delete_site_option( $key ); return $this; } /** * Delete entire job queue. */ public function delete_all() { $batches = $this->get_batches(); foreach ( $batches as $batch ) { $this->delete( $batch->key ); } delete_site_option( $this->get_status_key() ); $this->cancelled(); } /** * Cancel job on next batch. */ public function cancel() { update_site_option( $this->get_status_key(), self::STATUS_CANCELLED ); // Just in case the job was paused at the time. $this->dispatch(); } /** * Has the process been cancelled? * * @return bool */ public function is_cancelled() { return $this->get_status() === self::STATUS_CANCELLED; } /** * Called when background process has been cancelled. */ protected function cancelled() { do_action( $this->identifier . '_cancelled', $this->get_chain_id() ); } /** * Pause job on next batch. */ public function pause() { update_site_option( $this->get_status_key(), self::STATUS_PAUSED ); } /** * Has the process been paused? * * @return bool */ public function is_paused() { return $this->get_status() === self::STATUS_PAUSED; } /** * Called when background process has been paused. */ protected function paused() { do_action( $this->identifier . '_paused', $this->get_chain_id() ); } /** * Resume job. */ public function resume() { delete_site_option( $this->get_status_key() ); $this->schedule_event(); $this->dispatch(); $this->resumed(); } /** * Called when background process has been resumed. */ protected function resumed() { do_action( $this->identifier . '_resumed', $this->get_chain_id() ); } /** * Is queued? * * @return bool */ public function is_queued() { return ! $this->is_queue_empty(); } /** * Is the tool currently active, e.g. starting, working, paused or cleaning up? * * @return bool */ public function is_active() { return $this->is_queued() || $this->is_processing() || $this->is_paused() || $this->is_cancelled(); } /** * Generate key for a batch. * * Generates a unique key based on microtime. Queue items are * given a unique key so that they can be merged upon save. * * @param int $length Optional max length to trim key to, defaults to 64 characters. * @param string $key Optional string to append to identifier before hash, defaults to "batch". * * @return string */ protected function generate_key( $length = 64, $key = 'batch' ) { $unique = md5( microtime() . wp_rand() ); $prepend = $this->identifier . '_' . $key . '_'; return substr( $prepend . $unique, 0, $length ); } /** * Get the status key. * * @return string */ protected function get_status_key() { return $this->identifier . '_status'; } /** * Get the status value for the process. * * @return int */ protected function get_status() { global $wpdb; if ( is_multisite() ) { $status = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d LIMIT 1", $this->get_status_key(), get_current_network_id() ) ); } else { $status = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $this->get_status_key() ) ); } return absint( $status ); } /** * Maybe process a batch of queued items. * * Checks whether data exists within the queue and that * the process is not already running. */ public function maybe_handle() { // Don't lock up other requests while processing. session_write_close(); check_ajax_referer( $this->identifier, 'nonce' ); // Background process already running. if ( $this->is_processing() ) { return $this->maybe_wp_die(); } // Cancel requested. if ( $this->is_cancelled() ) { $this->clear_scheduled_event(); $this->delete_all(); return $this->maybe_wp_die(); } // Pause requested. if ( $this->is_paused() ) { $this->clear_scheduled_event(); $this->paused(); return $this->maybe_wp_die(); } // No data to process. if ( $this->is_queue_empty() ) { return $this->maybe_wp_die(); } $this->handle(); return $this->maybe_wp_die(); } /** * Is queue empty? * * @return bool */ protected function is_queue_empty() { return empty( $this->get_batch() ); } /** * Is process running? * * Check whether the current process is already running * in a background process. * * @return bool * * @deprecated 1.1.0 Superseded. * @see is_processing() */ protected function is_process_running() { return $this->is_processing(); } /** * Is the background process currently running? * * @return bool */ public function is_processing() { if ( get_site_transient( $this->identifier . '_process_lock' ) ) { // Process already running. return true; } return false; } /** * Lock process. * * Lock the process so that multiple instances can't run simultaneously. * Override if applicable, but the duration should be greater than that * defined in the time_exceeded() method. * * @param bool $reset_start_time Optional, default true. */ public function lock_process( $reset_start_time = true ) { if ( $reset_start_time ) { $this->start_time = time(); // Set start time of current process. } $lock_duration = ( property_exists( $this, 'queue_lock_time' ) ) ? $this->queue_lock_time : 60; // 1 minute $lock_duration = apply_filters( $this->identifier . '_queue_lock_time', $lock_duration ); $microtime = microtime(); $locked = set_site_transient( $this->identifier . '_process_lock', $microtime, $lock_duration ); /** * Action to note whether the background process managed to create its lock. * * The lock is used to signify that a process is running a task and no other * process should be allowed to run the same task until the lock is released. * * @param bool $locked Whether the lock was successfully created. * @param string $microtime Microtime string value used for the lock. * @param int $lock_duration Max number of seconds that the lock will live for. * @param string $chain_id Current background process chain ID. */ do_action( $this->identifier . '_process_locked', $locked, $microtime, $lock_duration, $this->get_chain_id() ); } /** * Unlock process. * * Unlock the process so that other instances can spawn. * * @return $this */ protected function unlock_process() { $unlocked = delete_site_transient( $this->identifier . '_process_lock' ); /** * Action to note whether the background process managed to release its lock. * * The lock is used to signify that a process is running a task and no other * process should be allowed to run the same task until the lock is released. * * @param bool $unlocked Whether the lock was released. * @param string $chain_id Current background process chain ID. */ do_action( $this->identifier . '_process_unlocked', $unlocked, $this->get_chain_id() ); return $this; } /** * Get batch. * * @return stdClass Return the first batch of queued items. */ protected function get_batch() { return array_reduce( $this->get_batches( 1 ), static function ( $carry, $batch ) { return $batch; }, array() ); } /** * Get batches. * * @param int $limit Number of batches to return, defaults to all. * * @return array of stdClass */ public function get_batches( $limit = 0 ) { global $wpdb; if ( empty( $limit ) || ! is_int( $limit ) ) { $limit = 0; } $table = $wpdb->options; $column = 'option_name'; $key_column = 'option_id'; $value_column = 'option_value'; if ( is_multisite() ) { $table = $wpdb->sitemeta; $column = 'meta_key'; $key_column = 'meta_id'; $value_column = 'meta_value'; } $key = $wpdb->esc_like( $this->identifier . '_batch_' ) . '%'; $sql = ' SELECT * FROM ' . $table . ' WHERE ' . $column . ' LIKE %s ORDER BY ' . $key_column . ' ASC '; $args = array( $key ); if ( ! empty( $limit ) ) { $sql .= ' LIMIT %d'; $args[] = $limit; } $items = $wpdb->get_results( $wpdb->prepare( $sql, // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $args ) ); $batches = array(); if ( ! empty( $items ) ) { $allowed_classes = $this->allowed_batch_data_classes; $batches = array_map( static function ( $item ) use ( $column, $value_column, $allowed_classes ) { $batch = new stdClass(); $batch->key = $item->{$column}; $batch->data = static::maybe_unserialize( $item->{$value_column}, $allowed_classes ); return $batch; }, $items ); } return $batches; } /** * Handle a dispatched request. * * Pass each queue item to the task handler, while remaining * within server memory and time limit constraints. */ protected function handle() { $this->lock_process(); /** * Number of seconds to sleep between batches. Defaults to 0 seconds, minimum 0. * * @param int $seconds */ $throttle_seconds = max( 0, apply_filters( $this->identifier . '_seconds_between_batches', apply_filters( $this->prefix . '_seconds_between_batches', 0 ) ) ); do { $batch = $this->get_batch(); foreach ( $batch->data as $key => $value ) { $task = $this->task( $value ); if ( false !== $task ) { $batch->data[ $key ] = $task; } else { unset( $batch->data[ $key ] ); } // Keep the batch up to date while processing it. if ( ! empty( $batch->data ) ) { $this->update( $batch->key, $batch->data ); } // Let the server breathe a little. sleep( $throttle_seconds ); // Batch limits reached, or pause or cancel requested. if ( ! $this->should_continue() ) { break; } } // Delete current batch if fully processed. if ( empty( $batch->data ) ) { $this->delete( $batch->key ); } } while ( ! $this->is_queue_empty() && $this->should_continue() ); $this->unlock_process(); // Start next batch or complete process. if ( ! $this->is_queue_empty() ) { $this->dispatch(); } else { $this->complete(); } return $this->maybe_wp_die(); } /** * Memory exceeded? * * Ensures the batch process never exceeds 90% * of the maximum WordPress memory. * * @return bool */ protected function memory_exceeded() { $memory_limit = $this->get_memory_limit() * 0.9; // 90% of max memory $current_memory = memory_get_usage( true ); $return = false; if ( $current_memory >= $memory_limit ) { $return = true; } return apply_filters( $this->identifier . '_memory_exceeded', $return ); } /** * Get memory limit in bytes. * * @return int */ protected function get_memory_limit() { if ( function_exists( 'ini_get' ) ) { $memory_limit = ini_get( 'memory_limit' ); } else { // Sensible default. $memory_limit = '128M'; } if ( ! $memory_limit || -1 === intval( $memory_limit ) ) { // Unlimited, set to 32GB. $memory_limit = '32000M'; } return wp_convert_hr_to_bytes( $memory_limit ); } /** * Time limit exceeded? * * Ensures the batch never exceeds a sensible time limit. * A timeout limit of 30s is common on shared hosting. * * @return bool */ protected function time_exceeded() { $finish = $this->start_time + apply_filters( $this->identifier . '_default_time_limit', 20 ); // 20 seconds $return = false; if ( time() >= $finish ) { $return = true; } return apply_filters( $this->identifier . '_time_exceeded', $return ); } /** * Complete processing. * * Override if applicable, but ensure that the below actions are * performed, or, call parent::complete(). */ protected function complete() { delete_site_option( $this->get_status_key() ); // Remove the cron healthcheck job from the cron schedule. $this->clear_scheduled_event(); $this->completed(); } /** * Called when background process has completed. */ protected function completed() { do_action( $this->identifier . '_completed', $this->get_chain_id() ); } /** * Get the cron healthcheck interval in minutes. * * Default is 5 minutes, minimum is 1 minute. * * @return int */ public function get_cron_interval() { $interval = 5; if ( property_exists( $this, 'cron_interval' ) ) { $interval = $this->cron_interval; } $interval = apply_filters( $this->cron_interval_identifier, $interval ); return is_int( $interval ) && 0 < $interval ? $interval : 5; } /** * Schedule the cron healthcheck job. * * @access public * * @param mixed $schedules Schedules. * * @return mixed */ public function schedule_cron_healthcheck( $schedules ) { $interval = $this->get_cron_interval(); if ( 1 === $interval ) { $display = __( 'Every Minute' ); } else { $display = sprintf( __( 'Every %d Minutes' ), $interval ); } // Adds an "Every NNN Minute(s)" schedule to the existing cron schedules. $schedules[ $this->cron_interval_identifier ] = array( 'interval' => MINUTE_IN_SECONDS * $interval, 'display' => $display, ); return $schedules; } /** * Handle cron healthcheck event. * * Restart the background process if not already running * and data exists in the queue. */ public function handle_cron_healthcheck() { if ( $this->is_processing() ) { // Background process already running. exit; } if ( $this->is_queue_empty() ) { // No data to process. $this->clear_scheduled_event(); exit; } $this->dispatch(); } /** * Schedule the cron healthcheck event. */ protected function schedule_event() { if ( ! wp_next_scheduled( $this->cron_hook_identifier ) ) { wp_schedule_event( time() + ( $this->get_cron_interval() * MINUTE_IN_SECONDS ), $this->cron_interval_identifier, $this->cron_hook_identifier ); } } /** * Clear scheduled cron healthcheck event. */ protected function clear_scheduled_event() { $timestamp = wp_next_scheduled( $this->cron_hook_identifier ); if ( $timestamp ) { wp_unschedule_event( $timestamp, $this->cron_hook_identifier ); } } /** * Cancel the background process. * * Stop processing queue items, clear cron job and delete batch. * * @deprecated 1.1.0 Superseded. * @see cancel() */ public function cancel_process() { $this->cancel(); } /** * Perform task with queued item. * * Override this method to perform any actions required on each * queue item. Return the modified item for further processing * in the next pass through. Or, return false to remove the * item from the queue. * * @param mixed $item Queue item to iterate over. * * @return mixed */ abstract protected function task( $item ); /** * Maybe unserialize data, but not if an object. * * @param mixed $data Data to be unserialized. * @param bool|array $allowed_classes Array of class names that can be unserialized. * * @return mixed */ protected static function maybe_unserialize( $data, $allowed_classes ) { if ( is_serialized( $data ) ) { $options = array(); if ( is_bool( $allowed_classes ) || is_array( $allowed_classes ) ) { $options['allowed_classes'] = $allowed_classes; } return @unserialize( $data, $options ); // @phpcs:ignore } return $data; } /** * Should any processing continue? * * @return bool */ public function should_continue() { /** * Filter whether the current background process should continue running the task * if there is data to be processed. * * If the processing time or memory limits have been exceeded, the value will be false. * If pause or cancel have been requested, the value will be false. * * It is very unlikely that you would want to override a false value with true. * * If false is returned here, it does not necessarily mean background processing is * complete. If there is batch data still to be processed and pause or cancel have not * been requested, it simply means this background process should spawn a new process * for the chain to continue processing and then close itself down. * * @param bool $continue Should the current process continue processing the task? * @param string $chain_id The current background process chain's ID. * * @return bool */ return apply_filters( $this->identifier . '_should_continue', ! ( $this->time_exceeded() || $this->memory_exceeded() || $this->is_paused() || $this->is_cancelled() ), $this->get_chain_id() ); } /** * Get the string used to identify this type of background process. * * @return string */ public function get_identifier() { return $this->identifier; } /** * Return the current background process chain's ID. * * If the chain's ID hasn't been set before this function is first used, * and hasn't been passed as a query arg during dispatch, * the chain ID will be generated before being returned. * * @return string */ public function get_chain_id() { if ( empty( $this->chain_id ) && wp_doing_ajax() ) { check_ajax_referer( $this->identifier, 'nonce' ); if ( ! empty( $_GET[ $this->get_chain_id_arg_name() ] ) ) { $chain_id = sanitize_key( $_GET[ $this->get_chain_id_arg_name() ] ); if ( wp_is_uuid( $chain_id ) ) { $this->chain_id = $chain_id; return $this->chain_id; } } } if ( empty( $this->chain_id ) ) { $this->chain_id = wp_generate_uuid4(); } return $this->chain_id; } /** * Filters the query arguments used during an async request. * * @param array $args Current query args. * * @return array */ public function filter_dispatch_query_args( $args ) { $args[ $this->get_chain_id_arg_name() ] = $this->get_chain_id(); return $args; } /** * Get the query arg name used for passing the chain ID to new processes. * * @return string */ private function get_chain_id_arg_name() { static $chain_id_arg_name; if ( ! empty( $chain_id_arg_name ) ) { return $chain_id_arg_name; } /** * Filter the query arg name used for passing the chain ID to new processes. * * If you encounter problems with using the default query arg name, you can * change it with this filter. * * @param string $chain_id_arg_name Default "chain_id". * * @return string */ $chain_id_arg_name = apply_filters( $this->identifier . '_chain_id_arg_name', self::CHAIN_ID_ARG_NAME ); if ( ! is_string( $chain_id_arg_name ) || empty( $chain_id_arg_name ) ) { $chain_id_arg_name = self::CHAIN_ID_ARG_NAME; } return $chain_id_arg_name; } } a5hleyrich/wp-background-processing/classes/wp-async-request.php 0000644 00000007451 15151523431 0021122 0 ustar 00 <?php /** * WP Async Request * * @package WP-Background-Processing */ /** * Abstract WP_Async_Request class. * * @abstract */ abstract class WP_Async_Request { /** * Prefix * * (default value: 'wp') * * @var string * @access protected */ protected $prefix = 'wp'; /** * Action * * (default value: 'async_request') * * @var string * @access protected */ protected $action = 'async_request'; /** * Identifier * * @var mixed * @access protected */ protected $identifier; /** * Data * * (default value: array()) * * @var array * @access protected */ protected $data = array(); /** * Initiate new async request. */ public function __construct() { $this->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|false HTTP Response array, WP_Error on failure, or false if not attempted. */ 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 query arguments used during an async request. * * @param array $args */ 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 query URL 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' => 5, 'blocking' => false, 'body' => $this->data, 'cookies' => $_COOKIE, // Passing cookies ensures request is performed as initiating user. 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), // Local requests, fine to pass false. ); /** * Filters the post arguments used during an async request. * * @param array $args */ return apply_filters( $this->identifier . '_post_args', $args ); } /** * Maybe handle a dispatched request. * * Check for correct nonce and pass to handler. * * @return void|mixed */ public function maybe_handle() { // Don't lock up other requests while processing. session_write_close(); check_ajax_referer( $this->identifier, 'nonce' ); $this->handle(); return $this->maybe_wp_die(); } /** * Should the process exit with wp_die? * * @param mixed $return What to return if filter says don't die, default is null. * * @return void|mixed */ protected function maybe_wp_die( $return = null ) { /** * Should wp_die be used? * * @return bool */ if ( apply_filters( $this->identifier . '_wp_die', true ) ) { wp_die(); } return $return; } /** * Handle a dispatched request. * * Override this method to perform any actions required * during the async request. */ abstract protected function handle(); } a5hleyrich/wp-background-processing/Makefile 0000644 00000000470 15151523431 0015157 0 ustar 00 .PHONY: test test: test-unit test-style .PHONY: test-unit test-unit: vendor vendor/bin/phpunit .PHONY: test-style test-style: vendor vendor/bin/phpcs vendor: composer.json composer install --ignore-platform-reqs .PHONY: clean clean: rm -rf vendor rm -f tests/.phpunit.result.cache .phpunit.result.cache a5hleyrich/wp-background-processing/.phpcs.xml 0000644 00000005547 15151523431 0015446 0 ustar 00 <?xml version="1.0"?> <ruleset name="WordPress Coding Standards based custom ruleset for your plugin"> <description>Generally-applicable sniffs for WordPress plugins.</description> <!-- What to scan --> <file>.</file> <exclude-pattern>/vendor/</exclude-pattern> <exclude-pattern>/node_modules/</exclude-pattern> <exclude-pattern>/tests/*</exclude-pattern> <!-- How to scan --> <!-- Usage instructions: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Usage --> <!-- Annotated ruleset: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Annotated-ruleset.xml --> <arg value="sp"/> <!-- Show sniff and progress --> <arg name="basepath" value="./"/><!-- Strip the file paths down to the relevant bit --> <arg name="colors"/> <arg name="extensions" value="php"/> <arg name="parallel" value="8"/><!-- Enables parallel processing when available for faster results. --> <!-- Rules: Check PHP version compatibility --> <!-- https://github.com/PHPCompatibility/PHPCompatibility#sniffing-your-code-for-compatibility-with-specific-php-versions --> <config name="testVersion" value="5.6-"/> <!-- https://github.com/PHPCompatibility/PHPCompatibilityWP --> <rule ref="PHPCompatibilityWP"/> <!-- Rules: WordPress Coding Standards --> <!-- https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards --> <!-- https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/wiki/Customizable-sniff-properties --> <config name="minimum_supported_wp_version" value="4.6"/> <rule ref="WordPress"> <!-- Unable to fix --> <exclude name="WordPress.Files.FileName.InvalidClassFileName"/> <exclude name="WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound"/> <exclude name="WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound"/> <exclude name="WordPress.DB.DirectDatabaseQuery.NoCaching"/> <!-- TODO: Maybe fix --> <exclude name="WordPress.WP.CronInterval.ChangeDetected"/> <exclude name="WordPress.DB.DirectDatabaseQuery.DirectQuery"/> </rule> <rule ref="WordPress.NamingConventions.PrefixAllGlobals"> <properties> <!-- Value: replace the function, class, and variable prefixes used. Separate multiple prefixes with a comma. --> <property name="prefixes" type="array" value="wpbp"/> </properties> <!-- TODO: Maybe fix --> <exclude name="WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound"/> </rule> <rule ref="WordPress.WP.I18n"> <properties> <!-- Value: replace the text domain used. --> <property name="text_domain" type="array" value="wp-background-processing"/> </properties> <!-- TODO: Should fix --> <exclude name="WordPress.WP.I18n.MissingArgDomain"/> <exclude name="WordPress.WP.I18n.MissingTranslatorsComment"/> </rule> <rule ref="WordPress.WhiteSpace.ControlStructureSpacing"> <properties> <property name="blank_line_check" value="true"/> </properties> </rule> </ruleset> a5hleyrich/wp-background-processing/.circleci/config.yml 0000644 00000003636 15151523431 0017351 0 ustar 00 workflows: version: 2 main: jobs: - php72-build - php73-build - php74-build - php80-build version: 2 job-references: mysql_image: &mysql_image cimg/mysql:5.7 setup_environment: &setup_environment name: "Setup Environment Variables" command: | echo "export PATH=$HOME/.composer/vendor/bin:$PATH" >> $BASH_ENV source /home/circleci/.bashrc install_dependencies: &install_dependencies name: "Install Dependencies" command: | sudo apt-get update && sudo apt-get install mysql-client subversion php_job: &php_job environment: - WP_TESTS_DIR: "/tmp/wordpress-tests-lib" - WP_CORE_DIR: "/tmp/wordpress/" steps: - checkout - run: php --version - run: composer --version - run: *setup_environment - run: *install_dependencies - run: name: "Run Tests" command: | rm -rf $WP_TESTS_DIR $WP_CORE_DIR bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 latest make test-unit WP_MULTISITE=1 make test-unit make test-style jobs: php56-build: <<: *php_job docker: - image: cimg/php:5.6 - image: *mysql_image php70-build: <<: *php_job docker: - image: cimg/php:7.0 - image: *mysql_image php71-build: <<: *php_job docker: - image: cimg/php:7.1 - image: *mysql_image php72-build: <<: *php_job docker: - image: cimg/php:7.2 - image: *mysql_image php73-build: <<: *php_job docker: - image: cimg/php:7.3 - image: *mysql_image php74-build: <<: *php_job docker: - image: cimg/php:7.4 - image: *mysql_image php80-build: <<: *php_job docker: - image: cimg/php:8.0 - image: *mysql_image php81-build: <<: *php_job docker: - image: cimg/php:8.1 - image: *mysql_image a5hleyrich/wp-background-processing/wp-background-processing.php 0000644 00000001350 15151523431 0021143 0 ustar 00 <?php /** * WP-Background Processing * * @package WP-Background-Processing */ /** * Plugin Name: WP Background Processing * Plugin URI: https://github.com/deliciousbrains/wp-background-processing * Description: Asynchronous requests and background processing in WordPress. * Author: Delicious Brains Inc. * Version: 1.0 * Author URI: https://deliciousbrains.com/ * GitHub Plugin URI: https://github.com/deliciousbrains/wp-background-processing * GitHub Branch: master */ if ( ! class_exists( 'WP_Async_Request' ) ) { require_once plugin_dir_path( __FILE__ ) . 'classes/wp-async-request.php'; } if ( ! class_exists( 'WP_Background_Process' ) ) { require_once plugin_dir_path( __FILE__ ) . 'classes/wp-background-process.php'; } a5hleyrich/wp-background-processing/license.txt 0000644 00000035444 15151523431 0015713 0 ustar 00 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. END OF TERMS AND CONDITIONS donatj/phpuseragentparser/.helpers/constants.php 0000644 00000000556 15151523431 0016220 0 ustar 00 <?php require __DIR__ . '/../vendor/autoload.php'; $class = new ReflectionClass($argv[1]); echo "Predefined helper constants from `{$class->getName()}`\n\n"; echo "| Constant | {$argv[2]} | \n|----------|----------| \n"; foreach( $class->getConstants() as $constant => $value ) { echo "| `{$class->getShortName()}::{$constant}` | {$value} | \n"; } echo "\n"; donatj/phpuseragentparser/Makefile 0000644 00000000730 15151523431 0013405 0 ustar 00 .PHONY: test test: ./vendor/bin/phpunit --coverage-text .PHONY: clean clean: -rm tests/user_agents.json touch tests/user_agents.json .PHONY: generate generate: php bin/user_agent_sorter.php > tests/user_agents.tmp.json && mv tests/user_agents.tmp.json tests/user_agents.dist.json php bin/constant_generator.php .PHONY: init init: php bin/init_user_agent.php > tests/user_agents.tmp.json && mv tests/user_agents.tmp.json tests/user_agents.dist.json make generate donatj/phpuseragentparser/.mddoc.xml 0000644 00000010471 15151523431 0013636 0 ustar 00 <mddoc> <docpage target="README.md"> <autoloader namespace="donatj\UserAgent" type="psr4" root="src" /> <section title="PHP User Agent Parser"> <text><](https://gitter.im/PhpUserAgentParser/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ]]></text> <badge-poser type="version"/> <badge-poser type="downloads"/> <badge-poser type="license"/> <badge-github-action name="donatj/phpUserAgent" workflow-file="ci.yml"/> <section title="What It Is"> <text><![CDATA[ A simple, streamlined PHP user-agent parser! Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php ]]></text> </section> <section title="Upgrading to `1.*`"> <text><![CDATA[ The new `1.*` release **does not break compatibility** with `0.*` and nothing need to change to upgrade. However, the global `parse_user_agent` is now deprecated; it has been replaced with the namespaced `\donatj\UserAgent\parse_user_agent` and functions exactly the same. You can easily replace any existing call to `parse_user_agent` with `\donatj\UserAgent\parse_user_agent` In addition, 1.x adds a convenience object wrapper you may use should you prefer. More information on this is in the Usage section below. ]]></text> </section> <section title="Why Use This"> <text><![CDATA[ You have your choice in user-agent parsers. This one detects **all modern browsers** in a very light, quick, understandable fashion. It is less than 200 lines of code, and consists of just three regular expressions! It can also correctly identify exotic versions of IE others fail on. It offers 100% unit test coverage, is installable via Composer, and is very easy to use. ]]></text> </section> <section title="What It Does Not Do"> <text><![CDATA[ This is not meant as a browser "knowledge engine" but rather a simple parser. Anything not adequately provided directly by the user agent string itself will simply not be provided by this. ]]></text> <section title="OS Versions"> <text>< I created for a client if you want to poke it, I update it from time to time, but frankly if you need to *reliably detect OS Version*, using user-agent isn't the way to do it. I'd go with JavaScript. ]]></text> </section> <section title="Undetectable Browsers"> <text><![CDATA[ - **Brave** - Brave is simply not differentiable from Chrome. This was a design decision on their part. ]]></text> </section> <section title="Undetectable Platforms"> <text><) ]]></text> </section> </section> <section title="Requirements"> <composer-requires/> </section> <section title="Installing"> <text>PHP User Agent is available through Packagist via Composer.</text> <composer-install/> </section> <section title="Usage"> <text>The classic procedural use is as simple as:</text> <source name="examples/procedural.php" lang="php" /> <text>The new object-oriented wrapper form:</text> <source name="examples/object-oriented.php" lang="php" /> </section> <section title="Currently Detected Platforms"> <exec cmd="php .helpers/constants.php 'donatj\UserAgent\Platforms' 'Platform'"/> </section> <section title="Currently Detected Browsers"> <exec cmd="php .helpers/constants.php 'donatj\UserAgent\Browsers' 'Browser'"/> </section> <text><. ]]></text> </section> </docpage> </mddoc> donatj/phpuseragentparser/LICENSE.md 0000644 00000002102 15151523431 0013344 0 ustar 00 The MIT License =============== Copyright (c) 2013 Jesse G. Donat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. donatj/phpuseragentparser/src/UserAgentParser.php 0000644 00000017660 15151523431 0016331 0 ustar 00 <?php /** * @author Jesse G. Donat <donatj@gmail.com> * * @link https://donatstudios.com/PHP-Parser-HTTP_USER_AGENT * @link https://github.com/donatj/PhpUserAgent * * @license MIT https://github.com/donatj/PhpUserAgent/blob/master/LICENSE.md */ namespace { /** * Parses a user agent string into its important parts * * This method is defined for backwards comparability with the old global method. * * @param string|null $u_agent User agent string to parse or null. Uses $_SERVER['HTTP_USER_AGENT'] on NULL * @return string[] an array with 'browser', 'version' and 'platform' keys * @throws \InvalidArgumentException on not having a proper user agent to parse. * * @deprecated This exists for backwards compatibility with 0.x and will likely be removed in 2.x * @see \donatj\UserAgent\parse_user_agent */ function parse_user_agent( $u_agent = null ) { return \donatj\UserAgent\parse_user_agent($u_agent); } } namespace donatj\UserAgent { const PLATFORM = 'platform'; const BROWSER = 'browser'; const BROWSER_VERSION = 'version'; /** * Parses a user agent string into its important parts * * @param string|null $u_agent User agent string to parse or null. Uses $_SERVER['HTTP_USER_AGENT'] on NULL * @return string[] an array with 'browser', 'version' and 'platform' keys * @throws \InvalidArgumentException on not having a proper user agent to parse. */ function parse_user_agent( $u_agent = null ) { if( $u_agent === null && isset($_SERVER['HTTP_USER_AGENT']) ) { $u_agent = (string)$_SERVER['HTTP_USER_AGENT']; } if( $u_agent === null ) { throw new \InvalidArgumentException('parse_user_agent requires a user agent'); } $platform = null; $browser = null; $version = null; $return = [ PLATFORM => &$platform, BROWSER => &$browser, BROWSER_VERSION => &$version ]; if( !$u_agent ) { return $return; } if( preg_match('/\((.*?)\)/m', $u_agent, $parent_matches) ) { preg_match_all(<<<'REGEX' /(?P<platform>BB\d+;|Android|Adr|Symbian|Sailfish|CrOS|Fuchsia|Tizen|iPhone|iPad|iPod|Linux|(?:Open|Net|Free)BSD|Macintosh| Windows(?:\ Phone)?|Silk|linux-gnu|BlackBerry|PlayBook|X11|(?:New\ )?Nintendo\ (?:WiiU?|3?DS|Switch)|Xbox(?:\ One)?) (?:\ [^;]*)? (?:;|$)/imx REGEX , $parent_matches[1], $result); $priority = [ 'Xbox One', 'Xbox', 'Windows Phone', 'Tizen', 'Android', 'FreeBSD', 'NetBSD', 'OpenBSD', 'CrOS', 'Fuchsia', 'X11', 'Sailfish' ]; $result[PLATFORM] = array_unique($result[PLATFORM]); if( count($result[PLATFORM]) > 1 ) { if( $keys = array_intersect($priority, $result[PLATFORM]) ) { $platform = reset($keys); } else { $platform = $result[PLATFORM][0]; } } elseif( isset($result[PLATFORM][0]) ) { $platform = $result[PLATFORM][0]; } } if( $platform == 'linux-gnu' || $platform == 'X11' ) { $platform = 'Linux'; } elseif( $platform == 'CrOS' ) { $platform = 'Chrome OS'; } elseif( $platform == 'Adr' ) { $platform = 'Android'; } elseif( $platform === null ) { if( preg_match_all('%(?P<platform>Android)[:/ ]%ix', $u_agent, $result) ) { $platform = $result[PLATFORM][0]; } } preg_match_all(<<<'REGEX' %(?P<browser>Camino|Kindle(\ Fire)?|Firefox|Iceweasel|IceCat|Safari|MSIE|Trident|AppleWebKit| TizenBrowser|(?:Headless)?Chrome|YaBrowser|Vivaldi|IEMobile|Opera|OPR|Silk|Midori|(?-i:Edge)|EdgA?|CriOS|UCBrowser|Puffin| OculusBrowser|SamsungBrowser|SailfishBrowser|XiaoMi/MiuiBrowser|YaApp_Android|Whale| Baiduspider|Applebot|Facebot|Googlebot|YandexBot|bingbot|Lynx|Version|Wget|curl|ChatGPT-User|GPTBot|OAI-SearchBot| Valve\ Steam\ Tenfoot|Mastodon| NintendoBrowser|PLAYSTATION\ (?:\d|Vita)+) \)?;? (?:[:/ ](?P<version>[0-9A-Z.]+)|/[A-Z]*) %ix REGEX , $u_agent, $result); // If nothing matched, return null (to avoid undefined index errors) if( !isset($result[BROWSER][0], $result[BROWSER_VERSION][0]) ) { if( preg_match('%^(?!Mozilla)(?P<browser>[A-Z0-9\-]+)([/ :](?P<version>[0-9A-Z.]+))?%ix', $u_agent, $result) ) { return [ PLATFORM => $platform ?: null, BROWSER => $result[BROWSER], BROWSER_VERSION => empty($result[BROWSER_VERSION]) ? null : $result[BROWSER_VERSION] ]; } return $return; } if( preg_match('/rv:(?P<version>[0-9A-Z.]+)/i', $u_agent, $rv_result) ) { $rv_result = $rv_result[BROWSER_VERSION]; } $browser = $result[BROWSER][0]; $version = $result[BROWSER_VERSION][0]; $lowerBrowser = array_map('strtolower', $result[BROWSER]); $find = function( $search, &$key = null, &$value = null ) use ( $lowerBrowser ) { $search = (array)$search; foreach( $search as $val ) { $xkey = array_search(strtolower($val), $lowerBrowser); if( $xkey !== false ) { $value = $val; $key = $xkey; return true; } } return false; }; $findT = function( array $search, &$key = null, &$value = null ) use ( $find ) { $value2 = null; if( $find(array_keys($search), $key, $value2) ) { $value = $search[$value2]; return true; } return false; }; $key = 0; $val = ''; if( $findT([ 'OPR' => 'Opera', 'Facebot' => 'iMessageBot', 'UCBrowser' => 'UC Browser', 'YaBrowser' => 'Yandex', 'YaApp_Android' => 'Yandex', 'Iceweasel' => 'Firefox', 'Icecat' => 'Firefox', 'CriOS' => 'Chrome', 'Edg' => 'Edge', 'EdgA' => 'Edge', 'XiaoMi/MiuiBrowser' => 'MiuiBrowser' ], $key, $browser) ) { $version = is_numeric(substr($result[BROWSER_VERSION][$key], 0, 1)) ? $result[BROWSER_VERSION][$key] : null; } elseif( $find('Playstation Vita', $key, $platform) ) { $platform = 'PlayStation Vita'; $browser = 'Browser'; } elseif( $find([ 'Kindle Fire', 'Silk' ], $key, $val) ) { $browser = $val == 'Silk' ? 'Silk' : 'Kindle'; $platform = 'Kindle Fire'; if( !($version = $result[BROWSER_VERSION][$key]) || !is_numeric($version[0]) ) { $version = $result[BROWSER_VERSION][array_search('Version', $result[BROWSER])]; } } elseif( $find('NintendoBrowser', $key) || $platform == 'Nintendo 3DS' ) { $browser = 'NintendoBrowser'; $version = $result[BROWSER_VERSION][$key]; } elseif( $find([ 'Kindle' ], $key, $platform) ) { $browser = $result[BROWSER][$key]; $version = $result[BROWSER_VERSION][$key]; } elseif( $find('Opera', $key, $browser) ) { $find('Version', $key); $version = $result[BROWSER_VERSION][$key]; } elseif( $find('Puffin', $key, $browser) ) { $version = $result[BROWSER_VERSION][$key]; if( strlen($version) > 3 ) { $part = substr($version, -2); if( ctype_upper($part) ) { $version = substr($version, 0, -2); $flags = [ 'IP' => 'iPhone', 'IT' => 'iPad', 'AP' => 'Android', 'AT' => 'Android', 'WP' => 'Windows Phone', 'WT' => 'Windows' ]; if( isset($flags[$part]) ) { $platform = $flags[$part]; } } } } elseif( $find([ 'Googlebot', 'Applebot', 'IEMobile', 'Edge', 'Midori', 'Whale', 'Vivaldi', 'OculusBrowser', 'SamsungBrowser', 'Valve Steam Tenfoot', 'Chrome', 'HeadlessChrome', 'SailfishBrowser' ], $key, $browser) ) { $version = $result[BROWSER_VERSION][$key]; } elseif( $rv_result && $find('Trident') ) { $browser = 'MSIE'; $version = $rv_result; } elseif( $browser == 'AppleWebKit' ) { if( $platform == 'Android' ) { $browser = 'Android Browser'; } elseif( strpos((string)$platform, 'BB') === 0 ) { $browser = 'BlackBerry Browser'; $platform = 'BlackBerry'; } elseif( $platform == 'BlackBerry' || $platform == 'PlayBook' ) { $browser = 'BlackBerry Browser'; } elseif( $find('Safari', $key, $browser) || $find('TizenBrowser', $key, $browser) ) { $version = $result[BROWSER_VERSION][$key]; } elseif( count($result[BROWSER]) ) { $key = count($result[BROWSER]) - 1; $browser = $result[BROWSER][$key]; $version = $result[BROWSER_VERSION][$key]; } if( $find('Version', $key) ) { $version = $result[BROWSER_VERSION][$key]; } } elseif( $pKey = preg_grep('/playstation \d/i', $result[BROWSER]) ) { $pKey = reset($pKey); $platform = 'PlayStation ' . preg_replace('/\D/', '', $pKey); $browser = 'NetFront'; } return $return; } } donatj/phpuseragentparser/src/UserAgent/Platforms.php 0000644 00000002551 15151523431 0017114 0 ustar 00 <?php // DO NOT EDIT THIS FILE - IT IS GENERATED BY constant_generator.php namespace donatj\UserAgent; interface Platforms { const MACINTOSH = 'Macintosh'; const CHROME_OS = 'Chrome OS'; const LINUX = 'Linux'; const WINDOWS = 'Windows'; const ANDROID = 'Android'; const BLACKBERRY = 'BlackBerry'; const FREEBSD = 'FreeBSD'; const FUCHSIA = 'Fuchsia'; const IPAD = 'iPad'; const IPHONE = 'iPhone'; const IPOD = 'iPod'; const KINDLE = 'Kindle'; const KINDLE_FIRE = 'Kindle Fire'; const NETBSD = 'NetBSD'; const NEW_NINTENDO_3DS = 'New Nintendo 3DS'; const NINTENDO_3DS = 'Nintendo 3DS'; const NINTENDO_DS = 'Nintendo DS'; const NINTENDO_SWITCH = 'Nintendo Switch'; const NINTENDO_WII = 'Nintendo Wii'; const NINTENDO_WIIU = 'Nintendo WiiU'; const OPENBSD = 'OpenBSD'; const PLAYBOOK = 'PlayBook'; const PLAYSTATION_3 = 'PlayStation 3'; const PLAYSTATION_4 = 'PlayStation 4'; const PLAYSTATION_5 = 'PlayStation 5'; const PLAYSTATION_VITA = 'PlayStation Vita'; const SAILFISH = 'Sailfish'; const SYMBIAN = 'Symbian'; const TIZEN = 'Tizen'; const WINDOWS_PHONE = 'Windows Phone'; const XBOX = 'Xbox'; const XBOX_ONE = 'Xbox One'; } donatj/phpuseragentparser/src/UserAgent/UserAgent.php 0000644 00000002057 15151523431 0017043 0 ustar 00 <?php namespace donatj\UserAgent; class UserAgent implements UserAgentInterface { /** * @var string|null */ private $platform; /** * @var string|null */ private $browser; /** * @var string|null */ private $browserVersion; /** * UserAgent constructor. * * @param string|null $platform * @param string|null $browser * @param string|null $browserVersion */ public function __construct( $platform, $browser, $browserVersion ) { $this->platform = $platform; $this->browser = $browser; $this->browserVersion = $browserVersion; } /** * @return string|null * @see \donatj\UserAgent\Platforms for a list of tested platforms */ public function platform() { return $this->platform; } /** * @return string|null * @see \donatj\UserAgent\Browsers for a list of tested browsers. */ public function browser() { return $this->browser; } /** * The version string. Formatting depends on the browser. * * @return string|null */ public function browserVersion() { return $this->browserVersion; } } donatj/phpuseragentparser/src/UserAgent/UserAgentParser.php 0000644 00000002201 15151523431 0020207 0 ustar 00 <?php namespace donatj\UserAgent; class UserAgentParser { /** * Parses a user agent string into its important parts, provide an object * * @param string|null $u_agent User agent string to parse or null. Uses $_SERVER['HTTP_USER_AGENT'] on NULL * @return UserAgent an object with 'browser', 'browserVersion' and 'platform' methods * @throws \InvalidArgumentException on not having a proper user agent to parse. * @see \donatj\UserAgent\parse_user_agent() * */ public function parse( $u_agent = null ) { $parsed = parse_user_agent($u_agent); return new UserAgent( $parsed[PLATFORM], $parsed[BROWSER], $parsed[BROWSER_VERSION] ); } /** * Parses a user agent string into its important parts * * @param string|null $u_agent User agent string to parse or null. Uses $_SERVER['HTTP_USER_AGENT'] on NULL * @return UserAgent an object with 'browser', 'browserVersion' and 'platform' methods * @throws \InvalidArgumentException on not having a proper user agent to parse. * @see \donatj\UserAgent\parse_user_agent() * */ public function __invoke( $u_agent = null ) { return $this->parse($u_agent); } } donatj/phpuseragentparser/src/UserAgent/Browsers.php 0000644 00000004451 15151523432 0016755 0 ustar 00 <?php // DO NOT EDIT THIS FILE - IT IS GENERATED BY constant_generator.php namespace donatj\UserAgent; interface Browsers { const ADSBOT_GOOGLE = 'AdsBot-Google'; const ANDROID_BROWSER = 'Android Browser'; const APPLEBOT = 'Applebot'; const BAIDUSPIDER = 'Baiduspider'; const BINGBOT = 'bingbot'; const BLACKBERRY_BROWSER = 'BlackBerry Browser'; const BROWSER = 'Browser'; const BUNJALLOO = 'Bunjalloo'; const CAMINO = 'Camino'; const CHATGPT_USER = 'ChatGPT-User'; const CHROME = 'Chrome'; const CURL = 'curl'; const EDGE = 'Edge'; const FACEBOOKEXTERNALHIT = 'facebookexternalhit'; const FEEDVALIDATOR = 'FeedValidator'; const FIREFOX = 'Firefox'; const GOOGLEBOT = 'Googlebot'; const GOOGLEBOT_IMAGE = 'Googlebot-Image'; const GOOGLEBOT_VIDEO = 'Googlebot-Video'; const GPTBOT = 'GPTBot'; const HEADLESSCHROME = 'HeadlessChrome'; const IEMOBILE = 'IEMobile'; const IMESSAGEBOT = 'iMessageBot'; const KINDLE = 'Kindle'; const LYNX = 'Lynx'; const MASTODON = 'Mastodon'; const MIDORI = 'Midori'; const MIUIBROWSER = 'MiuiBrowser'; const MSIE = 'MSIE'; const MSNBOT_MEDIA = 'msnbot-media'; const NETFRONT = 'NetFront'; const NINTENDOBROWSER = 'NintendoBrowser'; const OAI_SEARCHBOT = 'OAI-SearchBot'; const OCULUSBROWSER = 'OculusBrowser'; const OPERA = 'Opera'; const PUFFIN = 'Puffin'; const SAFARI = 'Safari'; const SAILFISHBROWSER = 'SailfishBrowser'; const SAMSUNGBROWSER = 'SamsungBrowser'; const SILK = 'Silk'; const SLACKBOT = 'Slackbot'; const TELEGRAMBOT = 'TelegramBot'; const TIZENBROWSER = 'TizenBrowser'; const TWITTERBOT = 'Twitterbot'; const UC_BROWSER = 'UC Browser'; const VALVE_STEAM_TENFOOT = 'Valve Steam Tenfoot'; const VIVALDI = 'Vivaldi'; const WGET = 'Wget'; const WHALE = 'Whale'; const WORDPRESS = 'WordPress'; const YANDEX = 'Yandex'; const YANDEXBOT = 'YandexBot'; } donatj/phpuseragentparser/src/UserAgent/UserAgentInterface.php 0000644 00000000717 15151523432 0020666 0 ustar 00 <?php namespace donatj\UserAgent; interface UserAgentInterface { /** * @return string|null * @see \donatj\UserAgent\Platforms for a list of tested platforms */ public function platform(); /** * @return string|null * @see \donatj\UserAgent\Browsers for a list of tested browsers. */ public function browser(); /** * The version string. Formatting depends on the browser. * * @return string|null */ public function browserVersion(); } donatj/phpuseragentparser/examples/procedural.php 0000644 00000000614 15151523432 0016436 0 ustar 00 <?php // if you're using composer require __DIR__ . '/../vendor/autoload.php'; // v0 style global function - @deprecated $uaInfo = parse_user_agent(); // or // modern namespaced function $uaInfo = donatj\UserAgent\parse_user_agent(); echo $uaInfo[donatj\UserAgent\PLATFORM] . PHP_EOL; echo $uaInfo[donatj\UserAgent\BROWSER] . PHP_EOL; echo $uaInfo[donatj\UserAgent\BROWSER_VERSION] . PHP_EOL; donatj/phpuseragentparser/examples/object-oriented.php 0000644 00000000543 15151523432 0017354 0 ustar 00 <?php use donatj\UserAgent\UserAgentParser; // if you're using composer require __DIR__ . '/../vendor/autoload.php'; $parser = new UserAgentParser(); // object-oriented call $ua = $parser->parse(); // or // command style invocation $ua = $parser(); echo $ua->platform() . PHP_EOL; echo $ua->browser() . PHP_EOL; echo $ua->browserVersion() . PHP_EOL; autoload.php 0000644 00000001403 15151523432 0007064 0 ustar 00 <?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, $err); } elseif (!headers_sent()) { echo $err; } } trigger_error( $err, E_USER_ERROR ); } require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitb6b9cb56b2244b2950baac041c453348::getLoader(); cmb2/cmb2/LICENSE 0000644 00000104515 15151523432 0007226 0 ustar 00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 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. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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 <https://www.gnu.org/licenses/>. 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: <program> Copyright (C) <year> <name of author> 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 <https://www.gnu.org/licenses/>. 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 <https://www.gnu.org/licenses/why-not-lgpl.html>. cmb2/cmb2/js/cmb2.min.js 0000644 00000076216 15151523432 0010606 0 ustar 00 window.CMB2=window.CMB2||{},function(window,document,$,cmb,undefined){"use strict";var $document,l10n=window.cmb2_l10,setTimeout=window.setTimeout,$id=function(selector){return $(document.getElementById(selector))},getRowId=function(id,newIterator){return id=id.split("-"),id.splice(id.length-1,1),id.push(newIterator),id.join("-")};cmb.$id=$id;var defaults={idNumber:!1,repeatEls:'input:not([type="button"]),select,textarea,.cmb2-media-status',noEmpty:'input:not([type="button"]):not([type="radio"]):not([type="checkbox"]),textarea',repeatUpdate:'input:not([type="button"]),select,textarea,label',styleBreakPoint:450,mediaHandlers:{},defaults:{time_picker:l10n.defaults.time_picker,date_picker:l10n.defaults.date_picker,color_picker:l10n.defaults.color_picker||{},code_editor:l10n.defaults.code_editor},media:{frames:{}}};cmb.init=function(){$document=$(document),$.extend(cmb,defaults),cmb.trigger("cmb_pre_init");var $metabox=cmb.metabox(),$repeatGroup=$metabox.find(".cmb-repeatable-group");cmb.initPickers($metabox.find('input[type="text"].cmb2-timepicker'),$metabox.find('input[type="text"].cmb2-datepicker'),$metabox.find('input[type="text"].cmb2-colorpicker')),cmb.initCodeEditors($metabox.find(".cmb2-textarea-code:not(.disable-codemirror)")),$('<p><span class="button-secondary cmb-multicheck-toggle">'+l10n.strings.check_toggle+"</span></p>").insertBefore(".cmb2-checkbox-list:not(.no-select-all)"),cmb.makeListSortable(),cmb.makeRepeatableSortable(),$metabox.on("change",".cmb2_upload_file",function(){cmb.media.field=$(this).attr("id"),$id(cmb.media.field+"_id").val("")}).on("click",".cmb-multicheck-toggle",cmb.toggleCheckBoxes).on("click",".cmb2-upload-button",cmb.handleMedia).on("click",".cmb-attach-list li, .cmb2-media-status .img-status img, .cmb2-media-status .file-status > span",cmb.handleFileClick).on("click",".cmb2-remove-file-button",cmb.handleRemoveMedia).on("click",".cmb-add-group-row",cmb.addGroupRow).on("click",".cmb-add-row-button",cmb.addAjaxRow).on("click",".cmb-remove-group-row",cmb.removeGroupRow).on("click",".cmb-remove-row-button",cmb.removeAjaxRow).on("keyup paste focusout",".cmb2-oembed",cmb.maybeOembed).on("cmb2_remove_row",".cmb-repeatable-group",cmb.resetTitlesAndIterator).on("click",".cmbhandle, .cmbhandle + .cmbhandle-title",cmb.toggleHandle),$repeatGroup.length&&$repeatGroup.on("cmb2_add_row",cmb.emptyValue).on("cmb2_add_row",cmb.setDefaults).filter(".sortable").each(function(){$(this).find(".cmb-remove-group-row-button").before('<a class="button-secondary cmb-shift-rows move-up alignleft" href="#"><span class="'+l10n.up_arrow_class+'"></span></a> <a class="button-secondary cmb-shift-rows move-down alignleft" href="#"><span class="'+l10n.down_arrow_class+'"></span></a>')}).on("click",".cmb-shift-rows",cmb.shiftRows),setTimeout(cmb.resizeoEmbeds,500),$(window).on("resize",cmb.resizeoEmbeds),$id("addtag").length&&cmb.listenTagAdd(),$(document).on("cmb_init",cmb.mceEnsureSave),cmb.trigger("cmb_init")},cmb.mceEnsureSave=function(){wp.data&&wp.data.hasOwnProperty("subscribe")&&cmb.canTinyMCE()&&wp.data.subscribe(function(){var editor=wp.data.hasOwnProperty("select")?wp.data.select("core/editor"):null;if(editor&&editor.isSavingPost&&editor.isSavingPost()&&window.tinyMCE.editors.length)for(var i=0;i<window.tinyMCE.editors.length;i++)window.tinyMCE.activeEditor!==window.tinyMCE.editors[i]&&window.tinyMCE.editors[i].save()})},cmb.canTinyMCE=function(){return l10n.user_can_richedit&&window.tinyMCE},cmb.listenTagAdd=function(){$document.ajaxSuccess(function(evt,xhr,settings){settings.data&&settings.data.length&&-1!==settings.data.indexOf("action=add-tag")&&cmb.resetBoxes($id("addtag").find(".cmb2-wrap > .cmb2-metabox"))})},cmb.resetBoxes=function($boxes){$.each($boxes,function(){cmb.resetBox($(this))})},cmb.resetBox=function($box){$box.find(".wp-picker-clear").trigger("click"),$box.find(".cmb2-remove-file-button").trigger("click"),$box.find(".cmb-row.cmb-repeatable-grouping:not(:first-of-type) .cmb-remove-group-row").click(),$box.find(".cmb-repeat-row:not(:first-child)").remove(),$box.find('input:not([type="button"]),select,textarea').each(function(){var $element=$(this),tagName=$element.prop("tagName");if("INPUT"===tagName){var elType=$element.attr("type");"checkbox"===elType||"radio"===elType?$element.prop("checked",!1):$element.val("")}"SELECT"===tagName&&$("option:selected",this).prop("selected",!1),"TEXTAREA"===tagName&&$element.html("")})},cmb.resetTitlesAndIterator=function(evt){if(evt.group){var $table=$(evt.target),groupTitle=$table.find(".cmb-add-group-row").data("grouptitle");$table.find(".cmb-repeatable-grouping").each(function(rowindex){var $row=$(this),prevIterator=parseInt($row.data("iterator"),10);prevIterator!==rowindex&&($row.attr("data-iterator",rowindex).data("iterator",rowindex).attr("id",getRowId($row.attr("id"),rowindex)).find(cmb.repeatEls).each(function(){cmb.updateNameAttr($(this),prevIterator,rowindex)}),cmb.resetGroupTitles($row,rowindex,groupTitle))})}},cmb.resetGroupTitles=function($row,newIterator,groupTitle){if(groupTitle){var $rowTitle=$row.find("h3.cmb-group-title");$rowTitle.length&&$rowTitle.text(groupTitle.replace("{#}",parseInt(newIterator,10)+1))}},cmb.toggleHandle=function(evt){evt.preventDefault(),cmb.trigger("postbox-toggled",$(this).parent(".postbox").toggleClass("closed"))},cmb.toggleCheckBoxes=function(evt){evt.preventDefault();var $this=$(this),$multicheck=$this.closest(".cmb-td").find("input[type=checkbox]:not([disabled])"),$toggled=!$this.data("checked");$multicheck.prop("checked",$toggled).trigger("change"),$this.data("checked",$toggled)},cmb.handleMedia=function(evt){evt.preventDefault();var $el=$(this);cmb.attach_id=!$el.hasClass("cmb2-upload-list")&&$el.closest(".cmb-td").find(".cmb2-upload-file-id").val(),cmb.attach_id="0"!==cmb.attach_id&&cmb.attach_id,cmb.handleFieldMedia($el.prev("input.cmb2-upload-file"),$el.hasClass("cmb2-upload-list"))},cmb.handleFileClick=function(evt){if(!$(evt.target).is("a")){evt.preventDefault();var $el=$(this),$td=$el.closest(".cmb-td"),isList=$td.find(".cmb2-upload-button").hasClass("cmb2-upload-list");cmb.attach_id=isList?$el.find('input[type="hidden"]').data("id"):$td.find(".cmb2-upload-file-id").val(),cmb.attach_id&&cmb.handleFieldMedia($td.find("input.cmb2-upload-file"),isList)}},cmb._handleMedia=function(id,isList){return cmb.handleFieldMedia($id(id),isList)},cmb.handleFieldMedia=function($field,isList){if(wp){var media,handlers,id=$field.attr("id"),fieldData=$field.data(),uid=fieldData.mediaid;if(uid||(uid=_.uniqueId(),$field.attr("data-mediaid",uid).data("mediaid",uid),fieldData.mediaid=uid),handlers=cmb.mediaHandlers,media=cmb.media,media.mediaid=uid,media.field=id,media.$field=$field,media.fieldData=fieldData,media.previewSize=media.fieldData.previewsize,media.sizeName=media.fieldData.sizename,media.fieldName=$field.attr("name"),media.isList=isList,uid in media.frames)return media.frames[uid].open();media.frames[uid]=wp.media({title:cmb.metabox().find('label[for="'+id+'"]').text(),library:media.fieldData.queryargs||{},button:{text:l10n.strings[isList?"upload_files":"upload_file"]},multiple:!!isList&&"add"}),media.frames[uid].states.first().set("filterable","all"),cmb.trigger("cmb_media_modal_init",media),handlers.list=function(selection,returnIt){var attachmentHtml,fileGroup=[];if(handlers.list.templates||(handlers.list.templates={image:wp.template("cmb2-list-image"),file:wp.template("cmb2-list-file")}),selection.each(function(attachment){attachmentHtml=handlers.getAttachmentHtml(attachment,"list"),fileGroup.push(attachmentHtml)}),returnIt)return fileGroup;media.$field.siblings(".cmb2-media-status").append(fileGroup)},handlers.single=function(selection){handlers.single.templates||(handlers.single.templates={image:wp.template("cmb2-single-image"),file:wp.template("cmb2-single-file")});var attachment=selection.first();media.$field.val(attachment.get("url")),media.$field.closest(".cmb-td").find(".cmb2-upload-file-id").val(attachment.get("id"));var attachmentHtml=handlers.getAttachmentHtml(attachment,"single");media.$field.siblings(".cmb2-media-status").slideDown().html(attachmentHtml)},handlers.getAttachmentHtml=function(attachment,templatesId){var isImage="image"===attachment.get("type"),data=handlers.prepareData(attachment,isImage);return handlers[templatesId].templates[isImage?"image":"file"](data)},handlers.prepareData=function(data,image){return image&&handlers.getImageData.call(data,50),data=data.toJSON(),data.mediaField=media.field,data.mediaFieldName=media.fieldName,data.stringRemoveImage=l10n.strings.remove_image,data.stringFile=l10n.strings.file,data.stringDownload=l10n.strings.download,data.stringRemoveFile=l10n.strings.remove_file,data},handlers.getImageData=function(fallbackSize){var previewW=media.previewSize[0]||fallbackSize,previewH=media.previewSize[1]||fallbackSize,url=this.get("url"),width=this.get("width"),height=this.get("height"),sizes=this.get("sizes");return sizes&&(sizes[media.sizeName]?(url=sizes[media.sizeName].url,width=sizes[media.sizeName].width,height=sizes[media.sizeName].height):sizes.large&&(url=sizes.large.url,width=sizes.large.width,height=sizes.large.height)),width>previewW&&(height=Math.floor(previewW*height/width),width=previewW),height>previewH&&(width=Math.floor(previewH*width/height),height=previewH),width||(width=previewW),height||(height="svg"===this.get("filename").split(".").pop()?"100%":previewH),this.set("sizeUrl",url),this.set("sizeWidth",width),this.set("sizeHeight",height),this},handlers.selectFile=function(){var selection=media.frames[uid].state().get("selection"),type=isList?"list":"single";cmb.attach_id&&isList?$('[data-id="'+cmb.attach_id+'"]').parents("li").replaceWith(handlers.list(selection,!0)):handlers[type](selection),cmb.trigger("cmb_media_modal_select",selection,media)},handlers.openModal=function(){var attach,selection=media.frames[uid].state().get("selection");cmb.attach_id?(attach=wp.media.attachment(cmb.attach_id),attach.fetch(),selection.set(attach?[attach]:[])):selection.reset(),cmb.trigger("cmb_media_modal_open",selection,media)},media.frames[uid].on("select",handlers.selectFile).on("open",handlers.openModal),media.frames[uid].open()}},cmb.handleRemoveMedia=function(evt){evt.preventDefault();var $this=$(this);if($this.is(".cmb-attach-list .cmb2-remove-file-button"))return $this.parents(".cmb2-media-item").remove(),!1;var $cell=$this.closest(".cmb-td");return cmb.media.$field=$cell.find(".cmb2-upload-file"),cmb.media.field=cmb.media.$field.attr("id"),cmb.media.$field.val(""),$cell.find(".cmb2-upload-file-id").val(""),$this.parents(".cmb2-media-status").html(""),!1},cmb.cleanRow=function($row,prevNum,group){var $elements=$row.find(cmb.repeatUpdate);if(group){var $other=$row.find("[id]").not(cmb.repeatUpdate);$row.find(".cmb-repeat-table .cmb-repeat-row:not(:first-child)").remove(),$other.length&&$other.each(function(){var $_this=$(this),oldID=$_this.attr("id"),newID=oldID.replace("_"+prevNum,"_"+cmb.idNumber),$buttons=$row.find('[data-selector="'+oldID+'"]');$_this.attr("id",newID),$buttons.length&&$buttons.attr("data-selector",newID).data("selector",newID)})}return $elements.filter(":checked").removeAttr("checked"),$elements.find(":checked").removeAttr("checked"),$elements.filter(":selected").removeAttr("selected"),$elements.find(":selected").removeAttr("selected",!1),cmb.resetGroupTitles($row,cmb.idNumber,$row.data("title")),$elements.each(function(){cmb.elReplacements($(this),prevNum,group)}),cmb},cmb.elReplacements=function($newInput,prevNum,group){var newID,oldID,oldFor=$newInput.attr("for"),oldVal=$newInput.val(),type=$newInput.prop("type"),defVal=cmb.getFieldArg($newInput,"default"),newVal=void 0!==defVal&&!1!==defVal?defVal:"",tagName=$newInput.prop("tagName"),checkable=("radio"===type||"checkbox"===type)&&oldVal,attrs={};if(oldFor)attrs={for:oldFor.replace("_"+prevNum,"_"+cmb.idNumber)};else{var newName,oldName=$newInput.attr("name");oldID=$newInput.attr("id"),group?(newName=oldName?oldName.replace("["+prevNum+"][","["+cmb.idNumber+"]["):"",newID=oldID?oldID.replace("_"+prevNum+"_","_"+cmb.idNumber+"_"):""):(newName=oldName?cmb.replaceLast(oldName,"["+prevNum+"]","["+cmb.idNumber+"]"):"",newID=oldID?cmb.replaceLast(oldID,"_"+prevNum,"_"+cmb.idNumber):""),attrs={id:newID,name:newName}}if("TEXTAREA"===tagName&&$newInput.html(newVal),"SELECT"===tagName&&void 0!==defVal){var $toSelect=$newInput.find('[value="'+defVal+'"]');$toSelect.length&&$toSelect.attr("selected","selected").prop("selected","selected")}return checkable&&($newInput.removeAttr("checked"),void 0!==defVal&&oldVal===defVal&&$newInput.attr("checked","checked").prop("checked","checked")),!group&&$newInput[0].hasAttribute("data-iterator")&&(attrs["data-iterator"]=cmb.idNumber),$newInput.removeClass("hasDatepicker").val(checkable||newVal).attr(attrs),$newInput},cmb.newRowHousekeeping=function($row){var $colorPicker=$row.find(".wp-picker-container"),$list=$row.find(".cmb2-media-status");return $colorPicker.length&&$colorPicker.each(function(){var $td=$(this).parent();$td.html($td.find('input[type="text"].cmb2-colorpicker').attr("style",""))}),$list.length&&$list.empty(),cmb},cmb.afterRowInsert=function($row){cmb.initPickers($row.find('input[type="text"].cmb2-timepicker'),$row.find('input[type="text"].cmb2-datepicker'),$row.find('input[type="text"].cmb2-colorpicker'))},cmb.updateNameAttr=function($el,prevIterator,newIterator){var name=$el.attr("name");if(void 0!==name){var isFileList=$el.attr("id").indexOf("filelist"),from=isFileList?"["+prevIterator+"][":"["+prevIterator+"]",to=isFileList?"["+newIterator+"][":"["+newIterator+"]",newName=name.replace(from,to);$el.attr("name",newName)}},cmb.emptyValue=function(evt,row){$(cmb.noEmpty,row).val("")},cmb.setDefaults=function(evt,row){$(cmb.noEmpty,row).each(function(){var $el=$(this),defVal=cmb.getFieldArg($el,"default");void 0!==defVal&&!1!==defVal&&$el.val(defVal)})},cmb.addGroupRow=function(evt){evt.preventDefault();var $this=$(this);cmb.triggerElement($this,"cmb2_add_group_row_start",$this);var $table=$id($this.data("selector")),$oldRow=$table.find(".cmb-repeatable-grouping").last(),prevNum=parseInt($oldRow.data("iterator"),10);cmb.idNumber=parseInt(prevNum,10)+1;for(var $row=$oldRow.clone(),nodeName=$row.prop("nodeName")||"div";$table.find('.cmb-repeatable-grouping[data-iterator="'+cmb.idNumber+'"]').length>0;)cmb.idNumber++;cmb.newRowHousekeeping($row.data("title",$this.data("grouptitle"))).cleanRow($row,prevNum,!0),$row.find(".cmb-add-row-button").prop("disabled",!1);var $newRow=$("<"+nodeName+' id="'+getRowId($oldRow.attr("id"),cmb.idNumber)+'" class="postbox cmb-row cmb-repeatable-grouping" data-iterator="'+cmb.idNumber+'">'+$row.html()+"</"+nodeName+">");$oldRow.after($newRow),cmb.afterRowInsert($newRow),cmb.makeRepeatableSortable($newRow),cmb.triggerElement($table,{type:"cmb2_add_row",group:!0},$newRow)},cmb.addAjaxRow=function(evt){evt.preventDefault();var $this=$(this),$table=$id($this.data("selector")),$row=$table.find(".empty-row"),prevNum=parseInt($row.find("[data-iterator]").data("iterator"),10);cmb.idNumber=parseInt(prevNum,10)+1;var $emptyrow=$row.clone();cmb.newRowHousekeeping($emptyrow).cleanRow($emptyrow,prevNum),$row.removeClass("empty-row hidden").addClass("cmb-repeat-row"),$row.after($emptyrow),cmb.afterRowInsert($emptyrow),cmb.triggerElement($table,{type:"cmb2_add_row",group:!1},$emptyrow,$row)},cmb.removeGroupRow=function(evt){evt.preventDefault();var $this=$(this),confirmation=$this.data("confirm");if(cmb.resetRow.resetting||!confirmation||window.confirm(confirmation)){var $table=$id($this.data("selector")),$parent=$this.parents(".cmb-repeatable-grouping");if($table.find(".cmb-repeatable-grouping").length<2)return cmb.resetRow($parent.parents(".cmb-repeatable-group").find(".cmb-add-group-row"),$this);cmb.triggerElement($table,"cmb2_remove_group_row_start",$this),$parent.remove(),cmb.triggerElement($table,{type:"cmb2_remove_row",group:!0})}},cmb.removeAjaxRow=function(evt){evt.preventDefault();var $this=$(this);if(!$this.hasClass("button-disabled")){var $parent=$this.parents(".cmb-row"),$table=$this.parents(".cmb-repeat-table");if($table.find(".cmb-row").length<=2)return cmb.resetRow($parent.find(".cmb-add-row-button"),$this);$parent.hasClass("empty-row")&&$parent.prev().addClass("empty-row").removeClass("cmb-repeat-row"),$this.parents(".cmb-repeat-table .cmb-row").remove(),cmb.triggerElement($table,{type:"cmb2_remove_row",group:!1})}},cmb.resetRow=function($addNewBtn,$removeBtn){cmb.resetRow.resetting=!0,$addNewBtn.trigger("click"),$removeBtn.trigger("click"),cmb.resetRow.resetting=!1},cmb.shiftRows=function(evt){evt.preventDefault();var $this=$(this),moveUp=!!$this.hasClass("move-up"),$from=$this.parents(".cmb-repeatable-grouping"),$goto=$from[moveUp?"prev":"next"](".cmb-repeatable-grouping");if(cmb.triggerElement($this,"cmb2_shift_rows_enter",$this,$from,$goto),$goto.length){cmb.triggerElement($this,"cmb2_shift_rows_start",$this,$from,$goto);var fromIterator=$from.attr("data-iterator"),toIterator=$goto.attr("data-iterator");$from.attr("data-iterator",toIterator).find(cmb.repeatEls).each(function(){cmb.updateNameAttr($(this),fromIterator,toIterator)}),$goto.attr("data-iterator",fromIterator).find(cmb.repeatEls).each(function(){cmb.updateNameAttr($(this),toIterator,fromIterator)});var groupTitle=$this.parents(".cmb-repeatable-group").find("[data-grouptitle]").data("grouptitle");groupTitle&&(cmb.resetGroupTitles($from,toIterator,groupTitle),cmb.resetGroupTitles($goto,fromIterator,groupTitle)),$goto[moveUp?"before":"after"]($from),$([document.documentElement,document.body]).animate({scrollTop:$from.offset().top-50},300),cmb.triggerElement($this,"cmb2_shift_rows_complete",$this,$from,$goto)}},cmb.initPickers=function($timePickers,$datePickers,$colorPickers){cmb.trigger("cmb_init_pickers",{time:$timePickers,date:$datePickers,color:$colorPickers}),cmb.initDateTimePickers($timePickers,"timepicker","time_picker"),cmb.initDateTimePickers($datePickers,"datepicker","date_picker"),cmb.initColorPickers($colorPickers)},cmb.initDateTimePickers=function($selector,method,defaultKey){$selector.length&&$selector[method]("destroy").each(function(){var $this=$(this),fieldOpts=$this.data(method)||{},options=$.extend({},cmb.defaults[defaultKey],fieldOpts);$this[method](cmb.datePickerSetupOpts(fieldOpts,options,method))})},cmb.datePickerSetupOpts=function(fieldOpts,options,method){var existing=$.extend({},options);return options.beforeShow=function(input,inst){"timepicker"===method&&cmb.addTimePickerClasses(inst.dpDiv),$id("ui-datepicker-div").addClass("cmb2-element"),"function"==typeof existing.beforeShow&&existing.beforeShow(input,inst)},"timepicker"===method&&(options.onChangeMonthYear=function(year,month,inst,picker){cmb.addTimePickerClasses(inst.dpDiv),"function"==typeof existing.onChangeMonthYear&&existing.onChangeMonthYear(year,month,inst,picker)}),options.onClose=function(dateText,inst){var $picker=$id("ui-datepicker-div").removeClass("cmb2-element").hide();"timepicker"!==method||$(inst.input).val()||inst.input.val($picker.find(".ui_tpicker_time").text()),"function"==typeof existing.onClose&&existing.onClose(dateText,inst)},options},cmb.addTimePickerClasses=function($picker){var func=cmb.addTimePickerClasses;func.count=func.count||0,setTimeout(function(){$picker.find(".ui-priority-secondary").length?($picker.find(".ui-priority-secondary").addClass("button-secondary"),$picker.find(".ui-priority-primary").addClass("button-primary"),func.count=0):func.count<5&&(func.count++,func($picker))},10)},cmb.initColorPickers=function($selector){$selector.length&&("object"==typeof jQuery.wp&&"function"==typeof jQuery.wp.wpColorPicker?$selector.each(function(){var $this=$(this),fieldOpts=$this.data("colorpicker")||{};$this.wpColorPicker($.extend({},cmb.defaults.color_picker,fieldOpts))}):$selector.each(function(i){$(this).after('<div id="picker-'+i+'" style="z-index: 1000; background: #EEE; border: 1px solid #CCC; position: absolute; display: block;"></div>'),$id("picker-"+i).hide().farbtastic($(this))}).focus(function(){$(this).next().show()}).blur(function(){$(this).next().hide()}))},cmb.initCodeEditors=function($selector){cmb.trigger("cmb_init_code_editors",$selector),cmb.defaults.code_editor&&wp&&wp.codeEditor&&$selector.length&&$selector.each(function(){wp.codeEditor.initialize(this.id,cmb.codeEditorArgs($(this).data("codeeditor")))})},cmb.codeEditorArgs=function(overrides){var props=["codemirror","csslint","jshint","htmlhint"],args=$.extend({},cmb.defaults.code_editor);overrides=overrides||{};for(var i=props.length-1;i>=0;i--)overrides.hasOwnProperty(props[i])&&(args[props[i]]=$.extend({},args[props[i]]||{},overrides[props[i]]));return args},cmb.makeListSortable=function(){var $filelist=cmb.metabox().find(".cmb2-media-status.cmb-attach-list");$filelist.length&&$filelist.sortable({cursor:"move"}).disableSelection()},cmb.makeRepeatableSortable=function($row){var $repeatables=($row||cmb.metabox()).find(".cmb-repeat-table .cmb-field-list");$repeatables.length&&$repeatables.sortable({items:".cmb-repeat-row",cursor:"move",cancel:"input,textarea,button,select,option,.CodeMirror"})},cmb.maybeOembed=function(evt){var $this=$(this);({focusout:function(){setTimeout(function(){cmb.spinner(".cmb2-metabox",!0)},2e3)},keyup:function(){var betw=function(min,max){return evt.which<=max&&evt.which>=min};(betw(48,90)||betw(96,111)||betw(8,9)||187===evt.which||190===evt.which)&&cmb.doAjax($this,evt)},paste:function(){setTimeout(function(){cmb.doAjax($this)},100)}})[evt.type]()},cmb.resizeoEmbeds=function(){cmb.metabox().each(function(){var $this=$(this),$tableWrap=$this.parents(".inside"),isSide=$this.parents(".inner-sidebar").length||$this.parents("#side-sortables").length,isSmall=isSide,isSmallest=!1;if(!$tableWrap.length)return!0;var tableW=$tableWrap.width();cmb.styleBreakPoint>tableW&&(isSmall=!0,isSmallest=cmb.styleBreakPoint-62>tableW),tableW=isSmall?tableW:Math.round(.82*$tableWrap.width()*.97);var newWidth=tableW-30;if(!isSmall||isSide||isSmallest||(newWidth-=75),newWidth>639)return!0;var $embeds=$this.find(".cmb-type-oembed .embed-status"),$children=$embeds.children().not(".cmb2-remove-wrapper");if(!$children.length)return!0;$children.each(function(){var $this=$(this),iwidth=$this.width(),iheight=$this.height(),_newWidth=newWidth;$this.parents(".cmb-repeat-row").length&&!isSmall&&(_newWidth=newWidth-91,_newWidth=785>tableW?_newWidth-15:_newWidth);var newHeight=Math.round(_newWidth*iheight/iwidth);$this.width(_newWidth).height(newHeight)})})},cmb.doAjax=function($obj){var oembed_url=$obj.val();if(!(oembed_url.length<6)){var field_id=$obj.attr("id"),$context=$obj.closest(".cmb-td"),$embed_container=$context.find(".embed-status"),$embed_wrap=$context.find(".embed_wrap"),$child_el=$embed_container.find(":first-child"),oembed_width=$embed_container.length&&$child_el.length?$child_el.width():$obj.width();cmb.log("oembed_url",oembed_url,field_id),cmb.spinner($context),$embed_wrap.html(""),setTimeout(function(){$(".cmb2-oembed:focus").val()===oembed_url&&$.ajax({type:"post",dataType:"json",url:l10n.ajaxurl,data:{action:"cmb2_oembed_handler",oembed_url:oembed_url,oembed_width:oembed_width>300?oembed_width:300,field_id:field_id,object_id:$obj.data("objectid"),object_type:$obj.data("objecttype"),cmb2_ajax_nonce:l10n.ajax_nonce},success:function(response){cmb.log(response),cmb.spinner($context,!0),$embed_wrap.html(response.data)}})},500)}},cmb.metabox=function(){return cmb.$metabox?cmb.$metabox:(cmb.$metabox=$(".cmb2-wrap > .cmb2-metabox"),cmb.$metabox)},cmb.spinner=function($context,hide){var m=hide?"removeClass":"addClass";$(".cmb-spinner",$context)[m]("is-active")},cmb.trigger=function(evtName){var args=Array.prototype.slice.call(arguments,1);args.push(cmb),$document.trigger(evtName,args)},cmb.triggerElement=function($el,evtName){var args=Array.prototype.slice.call(arguments,2);args.push(cmb),$el.trigger(evtName,args)},cmb.getFieldArg=function(hash,arg){return cmb.getField(hash)[arg]},cmb.getFields=function(filterCb){if("function"==typeof filterCb){var fields=[];return $.each(l10n.fields,function(hash,field){filterCb(field,hash)&&fields.push(field)}),fields}return l10n.fields},cmb.getField=function(hash){var field={};if(hash=hash instanceof jQuery?hash.data("hash"):hash)try{if(l10n.fields[hash])throw new Error(hash);cmb.getFields(function(field){if("function"==typeof hash){if(hash(field))throw new Error(field.hash)}else if(field.id&&field.id===hash)throw new Error(field.hash)})}catch(e){field=l10n.fields[e.message]}return field},cmb.log=function(){l10n.script_debug&&console&&"function"==typeof console.log&&console.log.apply(console,arguments)},cmb.replaceLast=function(string,search,replace){var n=string.lastIndexOf(search);return string.slice(0,n)+string.slice(n).replace(search,replace)},$(cmb.init)}(window,document,jQuery,window.CMB2),window.CMB2=window.CMB2||{},window.CMB2.wysiwyg=window.CMB2.wysiwyg||{},function(window,document,$,cmb,wysiwyg,undefined){"use strict";function delayedInit(){0===toBeDestroyed.length?toBeInitialized.forEach(function(toInit){toBeInitialized.splice(toBeInitialized.indexOf(toInit),1),wysiwyg.init.apply(wysiwyg,toInit)}):window.setTimeout(delayedInit,100)}function delayedDestroy(){toBeDestroyed.forEach(function(id){toBeDestroyed.splice(toBeDestroyed.indexOf(id),1),wysiwyg.destroy(id)})}function getGroupData(data){var groupid=data.groupid,fieldid=data.fieldid;return all[groupid]&&all[groupid][fieldid]||(all[groupid]=all[groupid]||{},all[groupid][fieldid]={template:wp.template("cmb2-wysiwyg-"+groupid+"-"+fieldid),defaults:{mce:$.extend({},tinyMCEPreInit.mceInit["cmb2_i_"+groupid+fieldid]),qt:$.extend({},tinyMCEPreInit.qtInit["cmb2_i_"+groupid+fieldid])}},delete tinyMCEPreInit.mceInit["cmb2_i_"+groupid+fieldid],delete tinyMCEPreInit.qtInit["cmb2_i_"+groupid+fieldid]),all[groupid][fieldid]}function initOptions(options){var prop,newSettings,newQTS,nameRegex=new RegExp("cmb2_n_"+options.groupid+options.fieldid,"g"),idRegex=new RegExp("cmb2_i_"+options.groupid+options.fieldid,"g");if(void 0===tinyMCEPreInit.mceInit[options.id]){newSettings=$.extend({},options.defaults.mce);for(prop in newSettings)"string"==typeof newSettings[prop]&&(newSettings[prop]=newSettings[prop].replace(idRegex,options.id).replace(nameRegex,options.name));tinyMCEPreInit.mceInit[options.id]=newSettings}if(void 0===tinyMCEPreInit.qtInit[options.id]){newQTS=$.extend({},options.defaults.qt);for(prop in newQTS)"string"==typeof newQTS[prop]&&(newQTS[prop]=newQTS[prop].replace(idRegex,options.id).replace(nameRegex,options.name));tinyMCEPreInit.qtInit[options.id]=newQTS}}var toBeDestroyed=[],toBeInitialized=[],all=wysiwyg.all={};wysiwyg.initAll=function(){var $this,data,initiated;$(".cmb2-wysiwyg-placeholder").each(function(){$this=$(this),data=$this.data(),data.groupid&&(data.id=$this.attr("id"),data.name=$this.attr("name"),data.value=$this.val(),wysiwyg.init($this,data,!1),initiated=!0)}),!0===initiated&&(void 0!==window.QTags&&window.QTags._buttonsInit(),$(document).on("cmb2_add_row",wysiwyg.addRow).on("cmb2_remove_group_row_start",wysiwyg.destroyRowEditors).on("cmb2_shift_rows_start",wysiwyg.shiftStart).on("cmb2_shift_rows_complete",wysiwyg.shiftComplete))},wysiwyg.addRow=function(evt,$row){wysiwyg.initRow($row,evt)},wysiwyg.destroyRowEditors=function(evt,$btn){wysiwyg.destroy($btn.parents(".cmb-repeatable-grouping").find(".wp-editor-area").attr("id"))},wysiwyg.shiftStart=function(evt,$btn,$from,$to){$from.add($to).find(".wp-editor-wrap textarea").each(function(){wysiwyg.destroy($(this).attr("id"))})},wysiwyg.shiftComplete=function(evt,$btn,$from,$to){$from.add($to).each(function(){wysiwyg.initRow($(this),evt)})},wysiwyg.initRow=function($row,evt){var $toReplace,data,defVal;$row.find(".cmb2-wysiwyg-inner-wrap").each(function(){$toReplace=$(this),data=$toReplace.data(),defVal=cmb.getFieldArg(data.hash,"default",""),defVal=void 0!==defVal&&!1!==defVal?defVal:"",data.iterator=$row.data("iterator"),data.fieldid=data.id,data.id=data.groupid+"_"+data.iterator+"_"+data.fieldid,data.name=data.groupid+"["+data.iterator+"]["+data.fieldid+"]",data.value="cmb2_add_row"!==evt.type&&$toReplace.find(".wp-editor-area").length?$toReplace.find(".wp-editor-area").val():defVal,0===toBeDestroyed.length?wysiwyg.init($toReplace,data):(toBeInitialized.push([$toReplace,data]),window.setTimeout(delayedInit,100))})},wysiwyg.init=function($toReplace,data,buttonsInit){if(!data.groupid)return!1;var mceActive=cmb.canTinyMCE(),qtActive="function"==typeof window.quicktags;$.extend(data,getGroupData(data)),initOptions(data),$toReplace.replaceWith(data.template(data)),mceActive&&window.tinyMCE.init(tinyMCEPreInit.mceInit[data.id]),qtActive&&window.quicktags(tinyMCEPreInit.qtInit[data.id]),mceActive&&$(document.getElementById(data.id)).parents(".wp-editor-wrap").removeClass("html-active").addClass("tmce-active"),!1!==buttonsInit&&void 0!==window.QTags&&window.QTags._buttonsInit()},wysiwyg.destroy=function(id){if(cmb.canTinyMCE()){var editor=tinyMCE.get(id);null!==editor&&void 0!==editor?(editor.destroy(),void 0===tinyMCEPreInit.mceInit[id]&&delete tinyMCEPreInit.mceInit[id],void 0===tinyMCEPreInit.qtInit[id]&&delete tinyMCEPreInit.qtInit[id]):-1===toBeDestroyed.indexOf(id)&&(toBeDestroyed.push(id),window.setTimeout(delayedDestroy,100))}},$(document).on("cmb_init",wysiwyg.initAll)}(window,document,jQuery,window.CMB2,window.CMB2.wysiwyg),window.CMB2=window.CMB2||{},window.CMB2.charcounter=window.CMB2.charcounter||{},function(window,document,$,cmb,counter){"use strict";if(!wp.utils||!wp.utils.WordCounter)return cmb.log("Cannot find wp.utils!");counter.counters={};var counters=counter.counters,wpCounter=new wp.utils.WordCounter;counter.updateCounter=function(field_id){if(!counters.hasOwnProperty(field_id))return null;var instance=counters[field_id],wysiwyg=instance.editor&&!instance.editor.isHidden(),text=wysiwyg?instance.editor.getContent({format:"raw"}):cmb.$id(field_id).val().trim(),count=wpCounter.count(text,instance.type),exceeded=instance.max&&count>instance.max,val=instance.max?instance.max-count:count;return instance.$el.parents(".cmb2-char-counter-wrap")[exceeded?"addClass":"removeClass"]("cmb2-max-exceeded"),instance.$el.val(val).outerWidth(8*String(val).length+15+"px"),count},counter.instantiate=function($el){var data=$el.data();if(!(data.fieldId in counters)){var instance={$el:$el,max:data.max,type:"words"===data.counterType?"words":"characters_including_spaces",editor:!1};counters[data.fieldId]=instance,counter.updateCounter(data.fieldId)}},counter.initAll=function(){$(".cmb2-char-counter").each(function(){counter.instantiate($(this))})},counter.initWysiwyg=function(evt,editor){editor.id in counters&&(counters[editor.id].editor=editor,editor.on("nodechange keyup",counter.countWysiwyg))},counter.addRow=function(evt,$row){$row.find(".cmb2-char-counter").each(function(){var $this=$(this),id=$this.attr("id"),field_id=id.replace(/^char-counter-/,"");$this.attr("data-field-id",field_id).data("field-id",field_id),counter.instantiate($this)})},counter.cleanCounters=function(){var field_id,remove=[];for(field_id in counters)document.getElementById(field_id)||remove.push(field_id);remove.length&&_.each(remove,function(field_id){delete counters[field_id]})},counter.countWysiwyg=_.throttle(function(evt){return evt.hasOwnProperty("element")?counter.updateCounter($(evt.element).data("id")):evt.hasOwnProperty("currentTarget")?counter.updateCounter($(evt.currentTarget).data("id")):void 0}),counter.countTextarea=_.throttle(function(evt){counter.updateCounter(evt.currentTarget.id)},400),$(document).on("cmb_init",counter.initAll).on("tinymce-editor-init",counter.initWysiwyg).on("cmb2_add_row",counter.addRow).on("cmb2_remove_row",counter.cleanCounters).on("input keyup",".cmb2-count-chars",counter.countTextarea)}(window,document,jQuery,window.CMB2,window.CMB2.charcounter); cmb2/cmb2/js/cmb2.js 0000644 00000115542 15151523432 0010020 0 ustar 00 /** * Controls the behaviours of custom metabox fields. * * @author CMB2 team * @see https://github.com/CMB2/CMB2 */ /** * Custom jQuery for Custom Metaboxes and Fields */ window.CMB2 = window.CMB2 || {}; (function(window, document, $, cmb, undefined){ 'use strict'; // localization strings var l10n = window.cmb2_l10; var setTimeout = window.setTimeout; var $document; var $id = function( selector ) { return $( document.getElementById( selector ) ); }; var getRowId = function( id, newIterator ) { id = id.split('-'); id.splice(id.length - 1, 1); id.push( newIterator ); return id.join('-'); }; cmb.$id = $id; var defaults = { idNumber : false, repeatEls : 'input:not([type="button"]),select,textarea,.cmb2-media-status', noEmpty : 'input:not([type="button"]):not([type="radio"]):not([type="checkbox"]),textarea', repeatUpdate : 'input:not([type="button"]),select,textarea,label', styleBreakPoint : 450, mediaHandlers : {}, defaults : { time_picker : l10n.defaults.time_picker, date_picker : l10n.defaults.date_picker, color_picker : l10n.defaults.color_picker || {}, code_editor : l10n.defaults.code_editor, }, media : { frames : {}, }, }; cmb.init = function() { $document = $( document ); // Setup the CMB2 object defaults. $.extend( cmb, defaults ); cmb.trigger( 'cmb_pre_init' ); var $metabox = cmb.metabox(); var $repeatGroup = $metabox.find('.cmb-repeatable-group'); // Init time/date/color pickers cmb.initPickers( $metabox.find('input[type="text"].cmb2-timepicker'), $metabox.find('input[type="text"].cmb2-datepicker'), $metabox.find('input[type="text"].cmb2-colorpicker') ); // Init code editors. cmb.initCodeEditors( $metabox.find( '.cmb2-textarea-code:not(.disable-codemirror)' ) ); // Insert toggle button into DOM wherever there is multicheck. credit: Genesis Framework $( '<p><span class="button-secondary cmb-multicheck-toggle">' + l10n.strings.check_toggle + '</span></p>' ).insertBefore( '.cmb2-checkbox-list:not(.no-select-all)' ); // Make File List drag/drop sortable: cmb.makeListSortable(); // Make Repeatable fields drag/drop sortable: cmb.makeRepeatableSortable(); $metabox .on( 'change', '.cmb2_upload_file', function() { cmb.media.field = $( this ).attr( 'id' ); $id( cmb.media.field + '_id' ).val(''); }) // Media/file management .on( 'click', '.cmb-multicheck-toggle', cmb.toggleCheckBoxes ) .on( 'click', '.cmb2-upload-button', cmb.handleMedia ) .on( 'click', '.cmb-attach-list li, .cmb2-media-status .img-status img, .cmb2-media-status .file-status > span', cmb.handleFileClick ) .on( 'click', '.cmb2-remove-file-button', cmb.handleRemoveMedia ) // Repeatable content .on( 'click', '.cmb-add-group-row', cmb.addGroupRow ) .on( 'click', '.cmb-add-row-button', cmb.addAjaxRow ) .on( 'click', '.cmb-remove-group-row', cmb.removeGroupRow ) .on( 'click', '.cmb-remove-row-button', cmb.removeAjaxRow ) // Ajax oEmbed display .on( 'keyup paste focusout', '.cmb2-oembed', cmb.maybeOembed ) // Reset titles when removing a row .on( 'cmb2_remove_row', '.cmb-repeatable-group', cmb.resetTitlesAndIterator ) .on( 'click', '.cmbhandle, .cmbhandle + .cmbhandle-title', cmb.toggleHandle ); if ( $repeatGroup.length ) { $repeatGroup .on( 'cmb2_add_row', cmb.emptyValue ) .on( 'cmb2_add_row', cmb.setDefaults ) .filter('.sortable').each( function() { // Add sorting arrows $( this ).find( '.cmb-remove-group-row-button' ).before( '<a class="button-secondary cmb-shift-rows move-up alignleft" href="#"><span class="'+ l10n.up_arrow_class +'"></span></a> <a class="button-secondary cmb-shift-rows move-down alignleft" href="#"><span class="'+ l10n.down_arrow_class +'"></span></a>' ); }) .on( 'click', '.cmb-shift-rows', cmb.shiftRows ); } // on pageload setTimeout( cmb.resizeoEmbeds, 500); // and on window resize $( window ).on( 'resize', cmb.resizeoEmbeds ); if ( $id( 'addtag' ).length ) { cmb.listenTagAdd(); } $( document ).on( 'cmb_init', cmb.mceEnsureSave ); cmb.trigger( 'cmb_init' ); }; // Handles updating tiny mce instances when saving a gutenberg post. // https://github.com/CMB2/CMB2/issues/1156 cmb.mceEnsureSave = function() { // If no wp.data, do not proceed (no gutenberg) if ( ! wp.data || ! wp.data.hasOwnProperty('subscribe') ) { return; } // If the current user cannot richedit, or MCE is not available, bail. if ( ! cmb.canTinyMCE() ) { return; } wp.data.subscribe( function() { var editor = wp.data.hasOwnProperty('select') ? wp.data.select( 'core/editor' ) : null; // the post is currently being saved && we have tinymce editors if ( editor && editor.isSavingPost && editor.isSavingPost() && window.tinyMCE.editors.length ) { for ( var i = 0; i < window.tinyMCE.editors.length; i++ ) { if ( window.tinyMCE.activeEditor !== window.tinyMCE.editors[i] ) { window.tinyMCE.editors[i].save(); } } } }); }; cmb.canTinyMCE = function() { return l10n.user_can_richedit && window.tinyMCE; }; cmb.listenTagAdd = function() { $document.ajaxSuccess( function( evt, xhr, settings ) { if ( settings.data && settings.data.length && -1 !== settings.data.indexOf( 'action=add-tag' ) ) { cmb.resetBoxes( $id( 'addtag' ).find( '.cmb2-wrap > .cmb2-metabox' ) ); } }); }; cmb.resetBoxes = function( $boxes ) { $.each( $boxes, function() { cmb.resetBox( $( this ) ); }); }; cmb.resetBox = function( $box ) { $box.find( '.wp-picker-clear' ).trigger( 'click' ); $box.find( '.cmb2-remove-file-button' ).trigger( 'click' ); $box.find( '.cmb-row.cmb-repeatable-grouping:not(:first-of-type) .cmb-remove-group-row' ).click(); $box.find( '.cmb-repeat-row:not(:first-child)' ).remove(); $box.find( 'input:not([type="button"]),select,textarea' ).each( function() { var $element = $( this ); var tagName = $element.prop('tagName'); if ( 'INPUT' === tagName ) { var elType = $element.attr( 'type' ); if ( 'checkbox' === elType || 'radio' === elType ) { $element.prop( 'checked', false ); } else { $element.val( '' ); } } if ( 'SELECT' === tagName ) { $( 'option:selected', this ).prop( 'selected', false ); } if ( 'TEXTAREA' === tagName ) { $element.html( '' ); } }); }; cmb.resetTitlesAndIterator = function( evt ) { if ( ! evt.group ) { return; } var $table = $( evt.target ); var groupTitle = $table.find( '.cmb-add-group-row' ).data( 'grouptitle' ); // Loop repeatable group table rows $table.find( '.cmb-repeatable-grouping' ).each( function( rowindex ) { var $row = $( this ); var prevIterator = parseInt( $row.data( 'iterator' ), 10 ); if ( prevIterator === rowindex ) { return; } // Reset rows iterator $row .attr( 'data-iterator', rowindex ) .data( 'iterator', rowindex ) .attr('id', getRowId( $row.attr('id'), rowindex ) ) .find( cmb.repeatEls ).each( function() { cmb.updateNameAttr( $( this ), prevIterator, rowindex ); }); cmb.resetGroupTitles( $row, rowindex, groupTitle ); }); }; cmb.resetGroupTitles = function( $row, newIterator, groupTitle ) { if ( groupTitle ) { var $rowTitle = $row.find( 'h3.cmb-group-title' ); // Reset rows title if ( $rowTitle.length ) { $rowTitle.text( groupTitle.replace( '{#}', parseInt( newIterator, 10 ) + 1 ) ); } } }; cmb.toggleHandle = function( evt ) { evt.preventDefault(); cmb.trigger( 'postbox-toggled', $( this ).parent('.postbox').toggleClass('closed') ); }; cmb.toggleCheckBoxes = function( evt ) { evt.preventDefault(); var $this = $( this ); var $multicheck = $this.closest( '.cmb-td' ).find( 'input[type=checkbox]:not([disabled])' ); var $toggled = ! $this.data( 'checked' ); $multicheck.prop( 'checked', $toggled ).trigger( 'change' ); $this.data( 'checked', $toggled ); }; cmb.handleMedia = function( evt ) { evt.preventDefault(); var $el = $( this ); cmb.attach_id = ! $el.hasClass( 'cmb2-upload-list' ) ? $el.closest( '.cmb-td' ).find( '.cmb2-upload-file-id' ).val() : false; // Clean up default 0 value cmb.attach_id = '0' !== cmb.attach_id ? cmb.attach_id : false; cmb.handleFieldMedia( $el.prev('input.cmb2-upload-file'), $el.hasClass( 'cmb2-upload-list' ) ); }; cmb.handleFileClick = function( evt ) { if ( $( evt.target ).is( 'a' ) ) { return; } evt.preventDefault(); var $el = $( this ); var $td = $el.closest( '.cmb-td' ); var isList = $td.find( '.cmb2-upload-button' ).hasClass( 'cmb2-upload-list' ); cmb.attach_id = isList ? $el.find( 'input[type="hidden"]' ).data( 'id' ) : $td.find( '.cmb2-upload-file-id' ).val(); if ( cmb.attach_id ) { cmb.handleFieldMedia( $td.find( 'input.cmb2-upload-file' ), isList ); } }; // Leaving this in for back-compat... cmb._handleMedia = function( id, isList ) { return cmb.handleFieldMedia( $id( id ), isList ); }; cmb.handleFieldMedia = function( $field, isList ) { if ( ! wp ) { return; } var id = $field.attr('id'); var fieldData = $field.data(); var media, handlers; // Get/set unique id since actual id cold _not_ be unique due to bad replacements, etc... var uid = fieldData.mediaid; if ( ! uid ) { uid = _.uniqueId(); $field.attr('data-mediaid', uid).data('mediaid', uid); fieldData.mediaid = uid; } handlers = cmb.mediaHandlers; media = cmb.media; media.mediaid = uid; media.field = id; media.$field = $field; media.fieldData = fieldData; media.previewSize = media.fieldData.previewsize; media.sizeName = media.fieldData.sizename; media.fieldName = $field.attr('name'); media.isList = isList; // If this field's media frame already exists, reopen it. if ( uid in media.frames ) { return media.frames[ uid ].open(); } // Create the media frame. media.frames[ uid ] = wp.media( { title: cmb.metabox().find('label[for="' + id + '"]').text(), library : media.fieldData.queryargs || {}, button: { text: l10n.strings[ isList ? 'upload_files' : 'upload_file' ] }, multiple: isList ? 'add' : false } ); // Enable the additional media filters: https://github.com/CMB2/CMB2/issues/873 media.frames[ uid ].states.first().set( 'filterable', 'all' ); cmb.trigger( 'cmb_media_modal_init', media ); handlers.list = function( selection, returnIt ) { // Setup our fileGroup array var fileGroup = []; var attachmentHtml; if ( ! handlers.list.templates ) { handlers.list.templates = { image : wp.template( 'cmb2-list-image' ), file : wp.template( 'cmb2-list-file' ), }; } // Loop through each attachment selection.each( function( attachment ) { // Image preview or standard generic output if it's not an image. attachmentHtml = handlers.getAttachmentHtml( attachment, 'list' ); // Add our file to our fileGroup array fileGroup.push( attachmentHtml ); }); if ( ! returnIt ) { // Append each item from our fileGroup array to .cmb2-media-status media.$field.siblings( '.cmb2-media-status' ).append( fileGroup ); } else { return fileGroup; } }; handlers.single = function( selection ) { if ( ! handlers.single.templates ) { handlers.single.templates = { image : wp.template( 'cmb2-single-image' ), file : wp.template( 'cmb2-single-file' ), }; } // Only get one file from the uploader var attachment = selection.first(); media.$field.val( attachment.get( 'url' ) ); media.$field.closest( '.cmb-td' ).find('.cmb2-upload-file-id') .val( attachment.get( 'id' ) ); // Image preview or standard generic output if it's not an image. var attachmentHtml = handlers.getAttachmentHtml( attachment, 'single' ); // add/display our output media.$field.siblings( '.cmb2-media-status' ).slideDown().html( attachmentHtml ); }; handlers.getAttachmentHtml = function( attachment, templatesId ) { var isImage = 'image' === attachment.get( 'type' ); var data = handlers.prepareData( attachment, isImage ); // Image preview or standard generic output if it's not an image. return handlers[ templatesId ].templates[ isImage ? 'image' : 'file' ]( data ); }; handlers.prepareData = function( data, image ) { if ( image ) { // Set the correct image size data handlers.getImageData.call( data, 50 ); } data = data.toJSON(); data.mediaField = media.field; data.mediaFieldName = media.fieldName; data.stringRemoveImage = l10n.strings.remove_image; data.stringFile = l10n.strings.file; data.stringDownload = l10n.strings.download; data.stringRemoveFile = l10n.strings.remove_file; return data; }; handlers.getImageData = function( fallbackSize ) { // Preview size dimensions var previewW = media.previewSize[0] || fallbackSize; var previewH = media.previewSize[1] || fallbackSize; // Image dimensions and url var url = this.get( 'url' ); var width = this.get( 'width' ); var height = this.get( 'height' ); var sizes = this.get( 'sizes' ); // Get the correct dimensions and url if a named size is set and exists // fallback to the 'large' size if ( sizes ) { if ( sizes[ media.sizeName ] ) { url = sizes[ media.sizeName ].url; width = sizes[ media.sizeName ].width; height = sizes[ media.sizeName ].height; } else if ( sizes.large ) { url = sizes.large.url; width = sizes.large.width; height = sizes.large.height; } } // Fit the image in to the preview size, keeping the correct aspect ratio if ( width > previewW ) { height = Math.floor( previewW * height / width ); width = previewW; } if ( height > previewH ) { width = Math.floor( previewH * width / height ); height = previewH; } if ( ! width ) { width = previewW; } if ( ! height ) { height = 'svg' === this.get( 'filename' ).split( '.' ).pop() ? '100%' : previewH; } this.set( 'sizeUrl', url ); this.set( 'sizeWidth', width ); this.set( 'sizeHeight', height ); return this; }; handlers.selectFile = function() { var selection = media.frames[ uid ].state().get( 'selection' ); var type = isList ? 'list' : 'single'; if ( cmb.attach_id && isList ) { $( '[data-id="'+ cmb.attach_id +'"]' ).parents( 'li' ).replaceWith( handlers.list( selection, true ) ); } else { handlers[type]( selection ); } cmb.trigger( 'cmb_media_modal_select', selection, media ); }; handlers.openModal = function() { var selection = media.frames[ uid ].state().get( 'selection' ); var attach; if ( ! cmb.attach_id ) { selection.reset(); } else { attach = wp.media.attachment( cmb.attach_id ); attach.fetch(); selection.set( attach ? [ attach ] : [] ); } cmb.trigger( 'cmb_media_modal_open', selection, media ); }; // When a file is selected, run a callback. media.frames[ uid ] .on( 'select', handlers.selectFile ) .on( 'open', handlers.openModal ); // Finally, open the modal media.frames[ uid ].open(); }; cmb.handleRemoveMedia = function( evt ) { evt.preventDefault(); var $this = $( this ); if ( $this.is( '.cmb-attach-list .cmb2-remove-file-button' ) ) { $this.parents( '.cmb2-media-item' ).remove(); return false; } var $cell = $this.closest( '.cmb-td' ); cmb.media.$field = $cell.find('.cmb2-upload-file'); cmb.media.field = cmb.media.$field.attr('id'); cmb.media.$field.val(''); $cell.find('.cmb2-upload-file-id').val(''); $this.parents('.cmb2-media-status').html(''); return false; }; cmb.cleanRow = function( $row, prevNum, group ) { var $elements = $row.find( cmb.repeatUpdate ); if ( group ) { var $other = $row.find( '[id]' ).not( cmb.repeatUpdate ); // Remove extra ajaxed rows $row.find('.cmb-repeat-table .cmb-repeat-row:not(:first-child)').remove(); // Update all elements w/ an ID if ( $other.length ) { $other.each( function() { var $_this = $( this ); var oldID = $_this.attr( 'id' ); var newID = oldID.replace( '_'+ prevNum, '_'+ cmb.idNumber ); var $buttons = $row.find('[data-selector="'+ oldID +'"]'); $_this.attr( 'id', newID ); // Replace data-selector vars if ( $buttons.length ) { $buttons.attr( 'data-selector', newID ).data( 'selector', newID ); } }); } } $elements.filter( ':checked' ).removeAttr( 'checked' ); $elements.find( ':checked' ).removeAttr( 'checked' ); $elements.filter( ':selected' ).removeAttr( 'selected' ); $elements.find( ':selected' ).removeAttr( 'selected', false ); cmb.resetGroupTitles( $row, cmb.idNumber, $row.data( 'title' ) ); $elements.each( function() { cmb.elReplacements( $( this ), prevNum, group ); } ); return cmb; }; cmb.elReplacements = function( $newInput, prevNum, group ) { var oldFor = $newInput.attr( 'for' ); var oldVal = $newInput.val(); var type = $newInput.prop( 'type' ); var defVal = cmb.getFieldArg( $newInput, 'default' ); var newVal = 'undefined' !== typeof defVal && false !== defVal ? defVal : ''; var tagName = $newInput.prop('tagName'); var checkable = 'radio' === type || 'checkbox' === type ? oldVal : false; var attrs = {}; var newID, oldID; if ( oldFor ) { attrs = { 'for' : oldFor.replace( '_'+ prevNum, '_'+ cmb.idNumber ) }; } else { var oldName = $newInput.attr( 'name' ); var newName; oldID = $newInput.attr( 'id' ); // Handle adding groups vs rows. if ( group ) { // Expect another bracket after group's index closing bracket. newName = oldName ? oldName.replace( '['+ prevNum +'][', '['+ cmb.idNumber +'][' ) : ''; // Expect another underscore after group's index trailing underscore. newID = oldID ? oldID.replace( '_' + prevNum + '_', '_' + cmb.idNumber + '_' ) : ''; } else { // Row indexes are at the very end of the string. newName = oldName ? cmb.replaceLast( oldName, '[' + prevNum + ']', '[' + cmb.idNumber + ']' ) : ''; newID = oldID ? cmb.replaceLast( oldID, '_' + prevNum, '_' + cmb.idNumber ) : ''; } attrs = { id: newID, name: newName }; } // Clear out textarea values if ( 'TEXTAREA' === tagName ) { $newInput.html( newVal ); } if ( 'SELECT' === tagName && 'undefined' !== typeof defVal ) { var $toSelect = $newInput.find( '[value="'+ defVal + '"]' ); if ( $toSelect.length ) { $toSelect.attr( 'selected', 'selected' ).prop( 'selected', 'selected' ); } } if ( checkable ) { $newInput.removeAttr( 'checked' ); if ( 'undefined' !== typeof defVal && oldVal === defVal ) { $newInput.attr( 'checked', 'checked' ).prop( 'checked', 'checked' ); } } if ( ! group && $newInput[0].hasAttribute( 'data-iterator' ) ) { attrs['data-iterator'] = cmb.idNumber; } $newInput .removeClass( 'hasDatepicker' ) .val( checkable ? checkable : newVal ).attr( attrs ); return $newInput; }; cmb.newRowHousekeeping = function( $row ) { var $colorPicker = $row.find( '.wp-picker-container' ); var $list = $row.find( '.cmb2-media-status' ); if ( $colorPicker.length ) { // Need to clean-up colorpicker before appending $colorPicker.each( function() { var $td = $( this ).parent(); $td.html( $td.find( 'input[type="text"].cmb2-colorpicker' ).attr('style', '') ); }); } // Need to clean-up colorpicker before appending if ( $list.length ) { $list.empty(); } return cmb; }; cmb.afterRowInsert = function( $row ) { // Init pickers from new row cmb.initPickers( $row.find('input[type="text"].cmb2-timepicker'), $row.find('input[type="text"].cmb2-datepicker'), $row.find('input[type="text"].cmb2-colorpicker') ); }; cmb.updateNameAttr = function ( $el, prevIterator, newIterator ) { var name = $el.attr( 'name' ); // get current name // If name is defined if ( 'undefined' !== typeof name ) { var isFileList = $el.attr( 'id' ).indexOf('filelist'); // Update field name attributes so data is not orphaned when a row is removed and post is saved var from = isFileList ? '[' + prevIterator + '][' : '[' + prevIterator + ']'; var to = isFileList ? '[' + newIterator + '][' : '[' + newIterator + ']'; var newName = name.replace( from, to ); // New name with replaced iterator $el.attr( 'name', newName ); } }; cmb.emptyValue = function( evt, row ) { $( cmb.noEmpty, row ).val( '' ); }; cmb.setDefaults = function( evt, row ) { $( cmb.noEmpty, row ).each( function() { var $el = $(this); var defVal = cmb.getFieldArg( $el, 'default' ); if ( 'undefined' !== typeof defVal && false !== defVal ) { $el.val( defVal ); } }); }; cmb.addGroupRow = function( evt ) { evt.preventDefault(); var $this = $( this ); // before anything significant happens cmb.triggerElement( $this, 'cmb2_add_group_row_start', $this ); var $table = $id( $this.data('selector') ); var $oldRow = $table.find('.cmb-repeatable-grouping').last(); var prevNum = parseInt( $oldRow.data('iterator'), 10 ); cmb.idNumber = parseInt( prevNum, 10 ) + 1; var $row = $oldRow.clone(); var nodeName = $row.prop('nodeName') || 'div'; // Make sure the next number doesn't exist. while ( $table.find( '.cmb-repeatable-grouping[data-iterator="'+ cmb.idNumber +'"]' ).length > 0 ) { cmb.idNumber++; } cmb.newRowHousekeeping( $row.data( 'title', $this.data( 'grouptitle' ) ) ).cleanRow( $row, prevNum, true ); $row.find( '.cmb-add-row-button' ).prop( 'disabled', false ); var $newRow = $( '<' + nodeName + ' id="'+ getRowId( $oldRow.attr('id'), cmb.idNumber ) +'" class="postbox cmb-row cmb-repeatable-grouping" data-iterator="'+ cmb.idNumber +'">'+ $row.html() +'</' + nodeName + '>' ); $oldRow.after( $newRow ); cmb.afterRowInsert( $newRow ); cmb.makeRepeatableSortable( $newRow ); cmb.triggerElement( $table, { type: 'cmb2_add_row', group: true }, $newRow ); }; cmb.addAjaxRow = function( evt ) { evt.preventDefault(); var $this = $( this ); var $table = $id( $this.data('selector') ); var $row = $table.find('.empty-row'); var prevNum = parseInt( $row.find('[data-iterator]').data('iterator'), 10 ); cmb.idNumber = parseInt( prevNum, 10 ) + 1; var $emptyrow = $row.clone(); cmb.newRowHousekeeping( $emptyrow ).cleanRow( $emptyrow, prevNum ); $row.removeClass('empty-row hidden').addClass('cmb-repeat-row'); $row.after( $emptyrow ); cmb.afterRowInsert( $emptyrow ); cmb.triggerElement( $table, { type: 'cmb2_add_row', group: false }, $emptyrow, $row ); }; cmb.removeGroupRow = function( evt ) { evt.preventDefault(); var $this = $( this ); var confirmation = $this.data('confirm'); // Process further only if deletion confirmation enabled and user agreed. if ( ! cmb.resetRow.resetting && confirmation && ! window.confirm( confirmation ) ) { return; } var $table = $id( $this.data('selector') ); var $parent = $this.parents('.cmb-repeatable-grouping'); var number = $table.find('.cmb-repeatable-grouping').length; if ( number < 2 ) { return cmb.resetRow( $parent.parents('.cmb-repeatable-group').find( '.cmb-add-group-row' ), $this ); } cmb.triggerElement( $table, 'cmb2_remove_group_row_start', $this ); $parent.remove(); cmb.triggerElement( $table, { type: 'cmb2_remove_row', group: true } ); }; cmb.removeAjaxRow = function( evt ) { evt.preventDefault(); var $this = $( this ); // Check if disabled if ( $this.hasClass( 'button-disabled' ) ) { return; } var $parent = $this.parents('.cmb-row'); var $table = $this.parents('.cmb-repeat-table'); var number = $table.find('.cmb-row').length; if ( number <= 2 ) { return cmb.resetRow( $parent.find( '.cmb-add-row-button' ), $this ); } if ( $parent.hasClass('empty-row') ) { $parent.prev().addClass( 'empty-row' ).removeClass('cmb-repeat-row'); } $this.parents('.cmb-repeat-table .cmb-row').remove(); cmb.triggerElement( $table, { type: 'cmb2_remove_row', group: false } ); }; cmb.resetRow = function( $addNewBtn, $removeBtn ) { cmb.resetRow.resetting = true; // Click the "add new" button followed by the "remove this" button // in order to reset the repeat row to empty values. $addNewBtn.trigger( 'click' ); $removeBtn.trigger( 'click' ); cmb.resetRow.resetting = false; }; cmb.shiftRows = function( evt ) { evt.preventDefault(); var $this = $( this ); var moveUp = $this.hasClass( 'move-up' ) ? true : false; var $from = $this.parents( '.cmb-repeatable-grouping' ); var $goto = $from[ moveUp ? 'prev' : 'next' ]( '.cmb-repeatable-grouping' ); // Before shift occurs. cmb.triggerElement( $this, 'cmb2_shift_rows_enter', $this, $from, $goto ); if ( ! $goto.length ) { return; } // About to shift cmb.triggerElement( $this, 'cmb2_shift_rows_start', $this, $from, $goto ); var fromIterator = $from.attr('data-iterator'); var toIterator = $goto.attr('data-iterator'); // Replace name attributes in both groups. $from.attr( 'data-iterator', toIterator ).find( cmb.repeatEls ).each( function() { cmb.updateNameAttr( $( this ), fromIterator, toIterator ); }); $goto.attr( 'data-iterator', fromIterator ).find( cmb.repeatEls ).each( function() { cmb.updateNameAttr( $( this ), toIterator, fromIterator ); }); // Replace titles in both groups. var groupTitle = $this.parents( '.cmb-repeatable-group' ).find('[data-grouptitle]').data( 'grouptitle' ); if ( groupTitle ) { cmb.resetGroupTitles( $from, toIterator, groupTitle ); cmb.resetGroupTitles( $goto, fromIterator, groupTitle ); } // Now move the group to it's destination. $goto[moveUp ? 'before' : 'after']( $from ); // Scroll to the top of the shifted group. $([document.documentElement, document.body]).animate({ scrollTop: $from.offset().top - 50 }, 300); // shift done cmb.triggerElement( $this, 'cmb2_shift_rows_complete', $this, $from, $goto ); }; cmb.initPickers = function( $timePickers, $datePickers, $colorPickers ) { cmb.trigger( 'cmb_init_pickers', { time: $timePickers, date: $datePickers, color: $colorPickers } ); // Initialize jQuery UI timepickers cmb.initDateTimePickers( $timePickers, 'timepicker', 'time_picker' ); // Initialize jQuery UI datepickers cmb.initDateTimePickers( $datePickers, 'datepicker', 'date_picker' ); // Initialize color picker cmb.initColorPickers( $colorPickers ); }; cmb.initDateTimePickers = function( $selector, method, defaultKey ) { if ( $selector.length ) { $selector[ method ]( 'destroy' ).each( function() { var $this = $( this ); var fieldOpts = $this.data( method ) || {}; var options = $.extend( {}, cmb.defaults[ defaultKey ], fieldOpts ); $this[ method ]( cmb.datePickerSetupOpts( fieldOpts, options, method ) ); } ); } }; cmb.datePickerSetupOpts = function( fieldOpts, options, method ) { var existing = $.extend( {}, options ); options.beforeShow = function( input, inst ) { if ( 'timepicker' === method ) { cmb.addTimePickerClasses( inst.dpDiv ); } // Wrap datepicker w/ class to narrow the scope of jQuery UI CSS and prevent conflicts $id( 'ui-datepicker-div' ).addClass( 'cmb2-element' ); // Let's be sure to call beforeShow if it was added if ( 'function' === typeof existing.beforeShow ) { existing.beforeShow( input, inst ); } }; if ( 'timepicker' === method ) { options.onChangeMonthYear = function( year, month, inst, picker ) { cmb.addTimePickerClasses( inst.dpDiv ); // Let's be sure to call onChangeMonthYear if it was added if ( 'function' === typeof existing.onChangeMonthYear ) { existing.onChangeMonthYear( year, month, inst, picker ); } }; } options.onClose = function( dateText, inst ) { // Remove the class when we're done with it (and hide to remove FOUC). var $picker = $id( 'ui-datepicker-div' ).removeClass( 'cmb2-element' ).hide(); if ( 'timepicker' === method && ! $( inst.input ).val() ) { // Set the timepicker field value if it's empty. inst.input.val( $picker.find( '.ui_tpicker_time' ).text() ); } // Let's be sure to call onClose if it was added if ( 'function' === typeof existing.onClose ) { existing.onClose( dateText, inst ); } }; return options; }; // Adds classes to timepicker buttons. cmb.addTimePickerClasses = function( $picker ) { var func = cmb.addTimePickerClasses; func.count = func.count || 0; // Wait a bit to let the timepicker render, since these are pre-render events. setTimeout( function() { if ( $picker.find( '.ui-priority-secondary' ).length ) { $picker.find( '.ui-priority-secondary' ).addClass( 'button-secondary' ); $picker.find( '.ui-priority-primary' ).addClass( 'button-primary' ); func.count = 0; } else if ( func.count < 5 ) { func.count++; func( $picker ); } }, 10 ); }; cmb.initColorPickers = function( $selector ) { if ( ! $selector.length ) { return; } if ( 'object' === typeof jQuery.wp && 'function' === typeof jQuery.wp.wpColorPicker ) { $selector.each( function() { var $this = $( this ); var fieldOpts = $this.data( 'colorpicker' ) || {}; $this.wpColorPicker( $.extend( {}, cmb.defaults.color_picker, fieldOpts ) ); } ); } else { $selector.each( function( i ) { $( this ).after( '<div id="picker-' + i + '" style="z-index: 1000; background: #EEE; border: 1px solid #CCC; position: absolute; display: block;"></div>' ); $id( 'picker-' + i ).hide().farbtastic( $( this ) ); } ) .focus( function() { $( this ).next().show(); } ) .blur( function() { $( this ).next().hide(); } ); } }; cmb.initCodeEditors = function( $selector ) { cmb.trigger( 'cmb_init_code_editors', $selector ); if ( ! cmb.defaults.code_editor || ! wp || ! wp.codeEditor || ! $selector.length ) { return; } $selector.each( function() { wp.codeEditor.initialize( this.id, cmb.codeEditorArgs( $( this ).data( 'codeeditor' ) ) ); } ); }; cmb.codeEditorArgs = function( overrides ) { var props = [ 'codemirror', 'csslint', 'jshint', 'htmlhint' ]; var args = $.extend( {}, cmb.defaults.code_editor ); overrides = overrides || {}; for ( var i = props.length - 1; i >= 0; i-- ) { if ( overrides.hasOwnProperty( props[i] ) ) { args[ props[i] ] = $.extend( {}, args[ props[i] ] || {}, overrides[ props[i] ] ); } } return args; }; cmb.makeListSortable = function() { var $filelist = cmb.metabox().find( '.cmb2-media-status.cmb-attach-list' ); if ( $filelist.length ) { $filelist.sortable({ cursor: 'move' }).disableSelection(); } }; cmb.makeRepeatableSortable = function( $row ) { var $repeatables = ($row || cmb.metabox()).find( '.cmb-repeat-table .cmb-field-list' ); if ( $repeatables.length ) { $repeatables.sortable({ items : '.cmb-repeat-row', cursor: 'move', // The default "cancel" attributes are: "input,textarea,button,select,option". // We are appending .CodeMirror. // See https://api.jqueryui.com/sortable/#option-cancel cancel: 'input,textarea,button,select,option,.CodeMirror' }); } }; cmb.maybeOembed = function( evt ) { var $this = $( this ); var m = { focusout : function() { setTimeout( function() { // if it's been 2 seconds, hide our spinner cmb.spinner( '.cmb2-metabox', true ); }, 2000); }, keyup : function() { var betw = function( min, max ) { return ( evt.which <= max && evt.which >= min ); }; // Only Ajax on normal keystrokes if ( betw( 48, 90 ) || betw( 96, 111 ) || betw( 8, 9 ) || evt.which === 187 || evt.which === 190 ) { // fire our ajax function cmb.doAjax( $this, evt ); } }, paste : function() { // paste event is fired before the value is filled, so wait a bit setTimeout( function() { cmb.doAjax( $this ); }, 100); } }; m[ evt.type ](); }; /** * Resize oEmbed videos to fit in their respective metaboxes * * @since 0.9.4 * * @return {return} */ cmb.resizeoEmbeds = function() { cmb.metabox().each( function() { var $this = $( this ); var $tableWrap = $this.parents('.inside'); var isSide = $this.parents('.inner-sidebar').length || $this.parents( '#side-sortables' ).length; var isSmall = isSide; var isSmallest = false; if ( ! $tableWrap.length ) { return true; // continue } // Calculate new width var tableW = $tableWrap.width(); if ( cmb.styleBreakPoint > tableW ) { isSmall = true; isSmallest = ( cmb.styleBreakPoint - 62 ) > tableW; } tableW = isSmall ? tableW : Math.round(($tableWrap.width() * 0.82)*0.97); var newWidth = tableW - 30; if ( isSmall && ! isSide && ! isSmallest ) { newWidth = newWidth - 75; } if ( newWidth > 639 ) { return true; // continue } var $embeds = $this.find('.cmb-type-oembed .embed-status'); var $children = $embeds.children().not('.cmb2-remove-wrapper'); if ( ! $children.length ) { return true; // continue } $children.each( function() { var $this = $( this ); var iwidth = $this.width(); var iheight = $this.height(); var _newWidth = newWidth; if ( $this.parents( '.cmb-repeat-row' ).length && ! isSmall ) { // Make room for our repeatable "remove" button column _newWidth = newWidth - 91; _newWidth = 785 > tableW ? _newWidth - 15 : _newWidth; } // Calc new height var newHeight = Math.round((_newWidth * iheight)/iwidth); $this.width(_newWidth).height(newHeight); }); }); }; // function for running our ajax cmb.doAjax = function( $obj ) { // get typed value var oembed_url = $obj.val(); // only proceed if the field contains more than 6 characters if ( oembed_url.length < 6 ) { return; } // get field id var field_id = $obj.attr('id'); var $context = $obj.closest( '.cmb-td' ); var $embed_container = $context.find( '.embed-status' ); var $embed_wrap = $context.find( '.embed_wrap' ); var $child_el = $embed_container.find( ':first-child' ); var oembed_width = $embed_container.length && $child_el.length ? $child_el.width() : $obj.width(); cmb.log( 'oembed_url', oembed_url, field_id ); // show our spinner cmb.spinner( $context ); // clear out previous results $embed_wrap.html(''); // and run our ajax function setTimeout( function() { // if they haven't typed in 500 ms if ( $( '.cmb2-oembed:focus' ).val() !== oembed_url ) { return; } $.ajax({ type : 'post', dataType : 'json', url : l10n.ajaxurl, data : { 'action' : 'cmb2_oembed_handler', 'oembed_url' : oembed_url, 'oembed_width' : oembed_width > 300 ? oembed_width : 300, 'field_id' : field_id, 'object_id' : $obj.data( 'objectid' ), 'object_type' : $obj.data( 'objecttype' ), 'cmb2_ajax_nonce' : l10n.ajax_nonce }, success: function(response) { cmb.log( response ); // hide our spinner cmb.spinner( $context, true ); // and populate our results from ajax response $embed_wrap.html( response.data ); } }); }, 500); }; /** * Gets jQuery object containing all CMB metaboxes. Caches the result. * * @since 1.0.2 * * @return {Object} jQuery object containing all CMB metaboxes. */ cmb.metabox = function() { if ( cmb.$metabox ) { return cmb.$metabox; } cmb.$metabox = $('.cmb2-wrap > .cmb2-metabox'); return cmb.$metabox; }; /** * Starts/stops contextual spinner. * * @since 1.0.1 * * @param {object} $context The jQuery parent/context object. * @param {bool} hide Whether to hide the spinner (will show by default). * * @return {void} */ cmb.spinner = function( $context, hide ) { var m = hide ? 'removeClass' : 'addClass'; $('.cmb-spinner', $context )[ m ]( 'is-active' ); }; /** * Triggers a jQuery event on the document object. * * @since 2.2.3 * * @param {string} evtName The name of the event to trigger. * * @return {void} */ cmb.trigger = function( evtName ) { var args = Array.prototype.slice.call( arguments, 1 ); args.push( cmb ); $document.trigger( evtName, args ); }; /** * Triggers a jQuery event on the given jQuery object. * * @since 2.2.3 * * @param {object} $el The jQuery element object. * @param {string} evtName The name of the event to trigger. * * @return {void} */ cmb.triggerElement = function( $el, evtName ) { var args = Array.prototype.slice.call( arguments, 2 ); args.push( cmb ); $el.trigger( evtName, args ); }; /** * Get an argument for a given field. * * @since 2.5.0 * * @param {string|object} hash The field hash, id, or a jQuery object for a field. * @param {string} arg The argument to get on the field. * * @return {mixed} The argument value. */ cmb.getFieldArg = function( hash, arg ) { return cmb.getField( hash )[ arg ]; }; /** * Get a field object instances. Can be filtered by passing in a filter callback function. * e.g. `const fileFields = CMB2.getFields(f => 'file' === f.type);` * * @since 2.5.0 * * @param {mixed} filterCb An optional filter callback function. * * @return array An array of field object instances. */ cmb.getFields = function( filterCb ) { if ( 'function' === typeof filterCb ) { var fields = []; $.each( l10n.fields, function( hash, field ) { if ( filterCb( field, hash ) ) { fields.push( field ); } }); return fields; } return l10n.fields; }; /** * Get a field object instance by hash or id. * * @since 2.5.0 * * @param {string|object} hash The field hash, id, or a jQuery object for a field. * * @return {object} The field object or an empty object. */ cmb.getField = function( hash ) { var field = {}; hash = hash instanceof jQuery ? hash.data( 'hash' ) : hash; if ( hash ) { try { if ( l10n.fields[ hash ] ) { throw new Error( hash ); } cmb.getFields( function( field ) { if ( 'function' === typeof hash ) { if ( hash( field ) ) { throw new Error( field.hash ); } } else if ( field.id && field.id === hash ) { throw new Error( field.hash ); } }); } catch( e ) { field = l10n.fields[ e.message ]; } } return field; }; /** * Safely log things if query var is set. Accepts same parameters as console.log. * * @since 1.0.0 * * @return {void} */ cmb.log = function() { if ( l10n.script_debug && console && 'function' === typeof console.log ) { console.log.apply(console, arguments); } }; /** * Replace the last occurrence of a string. * * @since 2.2.6 * * @param {string} string String to search/replace. * @param {string} search String to search. * @param {string} replace String to replace search with. * * @return {string} Possibly modified string. */ cmb.replaceLast = function( string, search, replace ) { // find the index of last time word was used var n = string.lastIndexOf( search ); // slice the string in 2, one from the start to the lastIndexOf // and then replace the word in the rest return string.slice( 0, n ) + string.slice( n ).replace( search, replace ); }; // Kick it off! $( cmb.init ); })(window, document, jQuery, window.CMB2); cmb2/cmb2/js/jquery-ui-timepicker-addon.min.js 0000644 00000115656 15151523432 0015134 0 ustar 00 /*! jQuery Timepicker Addon - v1.5.0 - 2014-09-01 * http://trentrichardson.com/examples/timepicker * Copyright (c) 2014 Trent Richardson; Licensed MIT */ (function($){if($.ui.timepicker=$.ui.timepicker||{},!$.ui.timepicker.version){$.extend($.ui,{timepicker:{version:"1.5.0"}});var Timepicker=function(){this.regional=[],this.regional[""]={currentText:"Now",closeText:"Done",amNames:["AM","A"],pmNames:["PM","P"],timeFormat:"HH:mm",timeSuffix:"",timeOnlyTitle:"Choose Time",timeText:"Time",hourText:"Hour",minuteText:"Minute",secondText:"Second",millisecText:"Millisecond",microsecText:"Microsecond",timezoneText:"Time Zone",isRTL:!1},this._defaults={showButtonPanel:!0,timeOnly:!1,timeOnlyShowDate:!1,showHour:null,showMinute:null,showSecond:null,showMillisec:null,showMicrosec:null,showTimezone:null,showTime:!0,stepHour:1,stepMinute:1,stepSecond:1,stepMillisec:1,stepMicrosec:1,hour:0,minute:0,second:0,millisec:0,microsec:0,timezone:null,hourMin:0,minuteMin:0,secondMin:0,millisecMin:0,microsecMin:0,hourMax:23,minuteMax:59,secondMax:59,millisecMax:999,microsecMax:999,minDateTime:null,maxDateTime:null,maxTime:null,minTime:null,onSelect:null,hourGrid:0,minuteGrid:0,secondGrid:0,millisecGrid:0,microsecGrid:0,alwaysSetTime:!0,separator:" ",altFieldTimeOnly:!0,altTimeFormat:null,altSeparator:null,altTimeSuffix:null,altRedirectFocus:!0,pickerTimeFormat:null,pickerTimeSuffix:null,showTimepicker:!0,timezoneList:null,addSliderAccess:!1,sliderAccessArgs:null,controlType:"slider",defaultValue:null,parse:"strict"},$.extend(this._defaults,this.regional[""])};$.extend(Timepicker.prototype,{$input:null,$altInput:null,$timeObj:null,inst:null,hour_slider:null,minute_slider:null,second_slider:null,millisec_slider:null,microsec_slider:null,timezone_select:null,maxTime:null,minTime:null,hour:0,minute:0,second:0,millisec:0,microsec:0,timezone:null,hourMinOriginal:null,minuteMinOriginal:null,secondMinOriginal:null,millisecMinOriginal:null,microsecMinOriginal:null,hourMaxOriginal:null,minuteMaxOriginal:null,secondMaxOriginal:null,millisecMaxOriginal:null,microsecMaxOriginal:null,ampm:"",formattedDate:"",formattedTime:"",formattedDateTime:"",timezoneList:null,units:["hour","minute","second","millisec","microsec"],support:{},control:null,setDefaults:function(e){return extendRemove(this._defaults,e||{}),this},_newInst:function($input,opts){var tp_inst=new Timepicker,inlineSettings={},fns={},overrides,i;for(var attrName in this._defaults)if(this._defaults.hasOwnProperty(attrName)){var attrValue=$input.attr("time:"+attrName);if(attrValue)try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}overrides={beforeShow:function(e,t){return $.isFunction(tp_inst._defaults.evnts.beforeShow)?tp_inst._defaults.evnts.beforeShow.call($input[0],e,t,tp_inst):void 0},onChangeMonthYear:function(e,t,i){tp_inst._updateDateTime(i),$.isFunction(tp_inst._defaults.evnts.onChangeMonthYear)&&tp_inst._defaults.evnts.onChangeMonthYear.call($input[0],e,t,i,tp_inst)},onClose:function(e,t){tp_inst.timeDefined===!0&&""!==$input.val()&&tp_inst._updateDateTime(t),$.isFunction(tp_inst._defaults.evnts.onClose)&&tp_inst._defaults.evnts.onClose.call($input[0],e,t,tp_inst)}};for(i in overrides)overrides.hasOwnProperty(i)&&(fns[i]=opts[i]||null);tp_inst._defaults=$.extend({},this._defaults,inlineSettings,opts,overrides,{evnts:fns,timepicker:tp_inst}),tp_inst.amNames=$.map(tp_inst._defaults.amNames,function(e){return e.toUpperCase()}),tp_inst.pmNames=$.map(tp_inst._defaults.pmNames,function(e){return e.toUpperCase()}),tp_inst.support=detectSupport(tp_inst._defaults.timeFormat+(tp_inst._defaults.pickerTimeFormat?tp_inst._defaults.pickerTimeFormat:"")+(tp_inst._defaults.altTimeFormat?tp_inst._defaults.altTimeFormat:"")),"string"==typeof tp_inst._defaults.controlType?("slider"===tp_inst._defaults.controlType&&$.ui.slider===void 0&&(tp_inst._defaults.controlType="select"),tp_inst.control=tp_inst._controls[tp_inst._defaults.controlType]):tp_inst.control=tp_inst._defaults.controlType;var timezoneList=[-720,-660,-600,-570,-540,-480,-420,-360,-300,-270,-240,-210,-180,-120,-60,0,60,120,180,210,240,270,300,330,345,360,390,420,480,525,540,570,600,630,660,690,720,765,780,840];null!==tp_inst._defaults.timezoneList&&(timezoneList=tp_inst._defaults.timezoneList);var tzl=timezoneList.length,tzi=0,tzv=null;if(tzl>0&&"object"!=typeof timezoneList[0])for(;tzl>tzi;tzi++)tzv=timezoneList[tzi],timezoneList[tzi]={value:tzv,label:$.timepicker.timezoneOffsetString(tzv,tp_inst.support.iso8601)};return tp_inst._defaults.timezoneList=timezoneList,tp_inst.timezone=null!==tp_inst._defaults.timezone?$.timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone):-1*(new Date).getTimezoneOffset(),tp_inst.hour=tp_inst._defaults.hour<tp_inst._defaults.hourMin?tp_inst._defaults.hourMin:tp_inst._defaults.hour>tp_inst._defaults.hourMax?tp_inst._defaults.hourMax:tp_inst._defaults.hour,tp_inst.minute=tp_inst._defaults.minute<tp_inst._defaults.minuteMin?tp_inst._defaults.minuteMin:tp_inst._defaults.minute>tp_inst._defaults.minuteMax?tp_inst._defaults.minuteMax:tp_inst._defaults.minute,tp_inst.second=tp_inst._defaults.second<tp_inst._defaults.secondMin?tp_inst._defaults.secondMin:tp_inst._defaults.second>tp_inst._defaults.secondMax?tp_inst._defaults.secondMax:tp_inst._defaults.second,tp_inst.millisec=tp_inst._defaults.millisec<tp_inst._defaults.millisecMin?tp_inst._defaults.millisecMin:tp_inst._defaults.millisec>tp_inst._defaults.millisecMax?tp_inst._defaults.millisecMax:tp_inst._defaults.millisec,tp_inst.microsec=tp_inst._defaults.microsec<tp_inst._defaults.microsecMin?tp_inst._defaults.microsecMin:tp_inst._defaults.microsec>tp_inst._defaults.microsecMax?tp_inst._defaults.microsecMax:tp_inst._defaults.microsec,tp_inst.ampm="",tp_inst.$input=$input,tp_inst._defaults.altField&&(tp_inst.$altInput=$(tp_inst._defaults.altField),tp_inst._defaults.altRedirectFocus===!0&&tp_inst.$altInput.css({cursor:"pointer"}).focus(function(){$input.trigger("focus")})),(0===tp_inst._defaults.minDate||0===tp_inst._defaults.minDateTime)&&(tp_inst._defaults.minDate=new Date),(0===tp_inst._defaults.maxDate||0===tp_inst._defaults.maxDateTime)&&(tp_inst._defaults.maxDate=new Date),void 0!==tp_inst._defaults.minDate&&tp_inst._defaults.minDate instanceof Date&&(tp_inst._defaults.minDateTime=new Date(tp_inst._defaults.minDate.getTime())),void 0!==tp_inst._defaults.minDateTime&&tp_inst._defaults.minDateTime instanceof Date&&(tp_inst._defaults.minDate=new Date(tp_inst._defaults.minDateTime.getTime())),void 0!==tp_inst._defaults.maxDate&&tp_inst._defaults.maxDate instanceof Date&&(tp_inst._defaults.maxDateTime=new Date(tp_inst._defaults.maxDate.getTime())),void 0!==tp_inst._defaults.maxDateTime&&tp_inst._defaults.maxDateTime instanceof Date&&(tp_inst._defaults.maxDate=new Date(tp_inst._defaults.maxDateTime.getTime())),tp_inst.$input.bind("focus",function(){tp_inst._onFocus()}),tp_inst},_addTimePicker:function(e){var t=this.$altInput&&this._defaults.altFieldTimeOnly?this.$input.val()+" "+this.$altInput.val():this.$input.val();this.timeDefined=this._parseTime(t),this._limitMinMaxDateTime(e,!1),this._injectTimePicker()},_parseTime:function(e,t){if(this.inst||(this.inst=$.datepicker._getInst(this.$input[0])),t||!this._defaults.timeOnly){var i=$.datepicker._get(this.inst,"dateFormat");try{var s=parseDateTimeInternal(i,this._defaults.timeFormat,e,$.datepicker._getFormatConfig(this.inst),this._defaults);if(!s.timeObj)return!1;$.extend(this,s.timeObj)}catch(a){return $.timepicker.log("Error parsing the date/time string: "+a+"\ndate/time string = "+e+"\ntimeFormat = "+this._defaults.timeFormat+"\ndateFormat = "+i),!1}return!0}var n=$.datepicker.parseTime(this._defaults.timeFormat,e,this._defaults);return n?($.extend(this,n),!0):!1},_injectTimePicker:function(){var e=this.inst.dpDiv,t=this.inst.settings,i=this,s="",a="",n=null,r={},l={},o=null,c=0,u=0;if(0===e.find("div.ui-timepicker-div").length&&t.showTimepicker){var m=' style="display:none;"',d='<div class="ui-timepicker-div'+(t.isRTL?" ui-timepicker-rtl":"")+'"><dl>'+'<dt class="ui_tpicker_time_label"'+(t.showTime?"":m)+">"+t.timeText+"</dt>"+'<dd class="ui_tpicker_time"'+(t.showTime?"":m)+"></dd>";for(c=0,u=this.units.length;u>c;c++){if(s=this.units[c],a=s.substr(0,1).toUpperCase()+s.substr(1),n=null!==t["show"+a]?t["show"+a]:this.support[s],r[s]=parseInt(t[s+"Max"]-(t[s+"Max"]-t[s+"Min"])%t["step"+a],10),l[s]=0,d+='<dt class="ui_tpicker_'+s+'_label"'+(n?"":m)+">"+t[s+"Text"]+"</dt>"+'<dd class="ui_tpicker_'+s+'"><div class="ui_tpicker_'+s+'_slider"'+(n?"":m)+"></div>",n&&t[s+"Grid"]>0){if(d+='<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>',"hour"===s)for(var h=t[s+"Min"];r[s]>=h;h+=parseInt(t[s+"Grid"],10)){l[s]++;var p=$.datepicker.formatTime(this.support.ampm?"hht":"HH",{hour:h},t);d+='<td data-for="'+s+'">'+p+"</td>"}else for(var _=t[s+"Min"];r[s]>=_;_+=parseInt(t[s+"Grid"],10))l[s]++,d+='<td data-for="'+s+'">'+(10>_?"0":"")+_+"</td>";d+="</tr></table></div>"}d+="</dd>"}var f=null!==t.showTimezone?t.showTimezone:this.support.timezone;d+='<dt class="ui_tpicker_timezone_label"'+(f?"":m)+">"+t.timezoneText+"</dt>",d+='<dd class="ui_tpicker_timezone" '+(f?"":m)+"></dd>",d+="</dl></div>";var g=$(d);for(t.timeOnly===!0&&(g.prepend('<div class="ui-widget-header ui-helper-clearfix ui-corner-all"><div class="ui-datepicker-title">'+t.timeOnlyTitle+"</div>"+"</div>"),e.find(".ui-datepicker-header, .ui-datepicker-calendar").hide()),c=0,u=i.units.length;u>c;c++)s=i.units[c],a=s.substr(0,1).toUpperCase()+s.substr(1),n=null!==t["show"+a]?t["show"+a]:this.support[s],i[s+"_slider"]=i.control.create(i,g.find(".ui_tpicker_"+s+"_slider"),s,i[s],t[s+"Min"],r[s],t["step"+a]),n&&t[s+"Grid"]>0&&(o=100*l[s]*t[s+"Grid"]/(r[s]-t[s+"Min"]),g.find(".ui_tpicker_"+s+" table").css({width:o+"%",marginLeft:t.isRTL?"0":o/(-2*l[s])+"%",marginRight:t.isRTL?o/(-2*l[s])+"%":"0",borderCollapse:"collapse"}).find("td").click(function(){var e=$(this),t=e.html(),a=parseInt(t.replace(/[^0-9]/g),10),n=t.replace(/[^apm]/gi),r=e.data("for");"hour"===r&&(-1!==n.indexOf("p")&&12>a?a+=12:-1!==n.indexOf("a")&&12===a&&(a=0)),i.control.value(i,i[r+"_slider"],s,a),i._onTimeChange(),i._onSelectHandler()}).css({cursor:"pointer",width:100/l[s]+"%",textAlign:"center",overflow:"hidden"}));if(this.timezone_select=g.find(".ui_tpicker_timezone").append("<select></select>").find("select"),$.fn.append.apply(this.timezone_select,$.map(t.timezoneList,function(e){return $("<option />").val("object"==typeof e?e.value:e).text("object"==typeof e?e.label:e)})),this.timezone!==void 0&&null!==this.timezone&&""!==this.timezone){var M=-1*new Date(this.inst.selectedYear,this.inst.selectedMonth,this.inst.selectedDay,12).getTimezoneOffset();M===this.timezone?selectLocalTimezone(i):this.timezone_select.val(this.timezone)}else this.hour!==void 0&&null!==this.hour&&""!==this.hour?this.timezone_select.val(t.timezone):selectLocalTimezone(i);this.timezone_select.change(function(){i._onTimeChange(),i._onSelectHandler()});var v=e.find(".ui-datepicker-buttonpane");if(v.length?v.before(g):e.append(g),this.$timeObj=g.find(".ui_tpicker_time"),null!==this.inst){var k=this.timeDefined;this._onTimeChange(),this.timeDefined=k}if(this._defaults.addSliderAccess){var T=this._defaults.sliderAccessArgs,D=this._defaults.isRTL;T.isRTL=D,setTimeout(function(){if(0===g.find(".ui-slider-access").length){g.find(".ui-slider:visible").sliderAccess(T);var e=g.find(".ui-slider-access:eq(0)").outerWidth(!0);e&&g.find("table:visible").each(function(){var t=$(this),i=t.outerWidth(),s=(""+t.css(D?"marginRight":"marginLeft")).replace("%",""),a=i-e,n=s*a/i+"%",r={width:a,marginRight:0,marginLeft:0};r[D?"marginRight":"marginLeft"]=n,t.css(r)})}},10)}i._limitMinMaxDateTime(this.inst,!0)}},_limitMinMaxDateTime:function(e,t){var i=this._defaults,s=new Date(e.selectedYear,e.selectedMonth,e.selectedDay);if(this._defaults.showTimepicker){if(null!==$.datepicker._get(e,"minDateTime")&&void 0!==$.datepicker._get(e,"minDateTime")&&s){var a=$.datepicker._get(e,"minDateTime"),n=new Date(a.getFullYear(),a.getMonth(),a.getDate(),0,0,0,0);(null===this.hourMinOriginal||null===this.minuteMinOriginal||null===this.secondMinOriginal||null===this.millisecMinOriginal||null===this.microsecMinOriginal)&&(this.hourMinOriginal=i.hourMin,this.minuteMinOriginal=i.minuteMin,this.secondMinOriginal=i.secondMin,this.millisecMinOriginal=i.millisecMin,this.microsecMinOriginal=i.microsecMin),e.settings.timeOnly||n.getTime()===s.getTime()?(this._defaults.hourMin=a.getHours(),this.hour<=this._defaults.hourMin?(this.hour=this._defaults.hourMin,this._defaults.minuteMin=a.getMinutes(),this.minute<=this._defaults.minuteMin?(this.minute=this._defaults.minuteMin,this._defaults.secondMin=a.getSeconds(),this.second<=this._defaults.secondMin?(this.second=this._defaults.secondMin,this._defaults.millisecMin=a.getMilliseconds(),this.millisec<=this._defaults.millisecMin?(this.millisec=this._defaults.millisecMin,this._defaults.microsecMin=a.getMicroseconds()):(this.microsec<this._defaults.microsecMin&&(this.microsec=this._defaults.microsecMin),this._defaults.microsecMin=this.microsecMinOriginal)):(this._defaults.millisecMin=this.millisecMinOriginal,this._defaults.microsecMin=this.microsecMinOriginal)):(this._defaults.secondMin=this.secondMinOriginal,this._defaults.millisecMin=this.millisecMinOriginal,this._defaults.microsecMin=this.microsecMinOriginal)):(this._defaults.minuteMin=this.minuteMinOriginal,this._defaults.secondMin=this.secondMinOriginal,this._defaults.millisecMin=this.millisecMinOriginal,this._defaults.microsecMin=this.microsecMinOriginal)):(this._defaults.hourMin=this.hourMinOriginal,this._defaults.minuteMin=this.minuteMinOriginal,this._defaults.secondMin=this.secondMinOriginal,this._defaults.millisecMin=this.millisecMinOriginal,this._defaults.microsecMin=this.microsecMinOriginal)}if(null!==$.datepicker._get(e,"maxDateTime")&&void 0!==$.datepicker._get(e,"maxDateTime")&&s){var r=$.datepicker._get(e,"maxDateTime"),l=new Date(r.getFullYear(),r.getMonth(),r.getDate(),0,0,0,0);(null===this.hourMaxOriginal||null===this.minuteMaxOriginal||null===this.secondMaxOriginal||null===this.millisecMaxOriginal)&&(this.hourMaxOriginal=i.hourMax,this.minuteMaxOriginal=i.minuteMax,this.secondMaxOriginal=i.secondMax,this.millisecMaxOriginal=i.millisecMax,this.microsecMaxOriginal=i.microsecMax),e.settings.timeOnly||l.getTime()===s.getTime()?(this._defaults.hourMax=r.getHours(),this.hour>=this._defaults.hourMax?(this.hour=this._defaults.hourMax,this._defaults.minuteMax=r.getMinutes(),this.minute>=this._defaults.minuteMax?(this.minute=this._defaults.minuteMax,this._defaults.secondMax=r.getSeconds(),this.second>=this._defaults.secondMax?(this.second=this._defaults.secondMax,this._defaults.millisecMax=r.getMilliseconds(),this.millisec>=this._defaults.millisecMax?(this.millisec=this._defaults.millisecMax,this._defaults.microsecMax=r.getMicroseconds()):(this.microsec>this._defaults.microsecMax&&(this.microsec=this._defaults.microsecMax),this._defaults.microsecMax=this.microsecMaxOriginal)):(this._defaults.millisecMax=this.millisecMaxOriginal,this._defaults.microsecMax=this.microsecMaxOriginal)):(this._defaults.secondMax=this.secondMaxOriginal,this._defaults.millisecMax=this.millisecMaxOriginal,this._defaults.microsecMax=this.microsecMaxOriginal)):(this._defaults.minuteMax=this.minuteMaxOriginal,this._defaults.secondMax=this.secondMaxOriginal,this._defaults.millisecMax=this.millisecMaxOriginal,this._defaults.microsecMax=this.microsecMaxOriginal)):(this._defaults.hourMax=this.hourMaxOriginal,this._defaults.minuteMax=this.minuteMaxOriginal,this._defaults.secondMax=this.secondMaxOriginal,this._defaults.millisecMax=this.millisecMaxOriginal,this._defaults.microsecMax=this.microsecMaxOriginal)}if(null!==e.settings.minTime){var o=new Date("01/01/1970 "+e.settings.minTime);this.hour<o.getHours()?(this.hour=this._defaults.hourMin=o.getHours(),this.minute=this._defaults.minuteMin=o.getMinutes()):this.hour===o.getHours()&&this.minute<o.getMinutes()?this.minute=this._defaults.minuteMin=o.getMinutes():this._defaults.hourMin<o.getHours()?(this._defaults.hourMin=o.getHours(),this._defaults.minuteMin=o.getMinutes()):this._defaults.minuteMin=this._defaults.hourMin===o.getHours()===this.hour&&this._defaults.minuteMin<o.getMinutes()?o.getMinutes():0}if(null!==e.settings.maxTime){var c=new Date("01/01/1970 "+e.settings.maxTime);this.hour>c.getHours()?(this.hour=this._defaults.hourMax=c.getHours(),this.minute=this._defaults.minuteMax=c.getMinutes()):this.hour===c.getHours()&&this.minute>c.getMinutes()?this.minute=this._defaults.minuteMax=c.getMinutes():this._defaults.hourMax>c.getHours()?(this._defaults.hourMax=c.getHours(),this._defaults.minuteMax=c.getMinutes()):this._defaults.minuteMax=this._defaults.hourMax===c.getHours()===this.hour&&this._defaults.minuteMax>c.getMinutes()?c.getMinutes():59}if(void 0!==t&&t===!0){var u=parseInt(this._defaults.hourMax-(this._defaults.hourMax-this._defaults.hourMin)%this._defaults.stepHour,10),m=parseInt(this._defaults.minuteMax-(this._defaults.minuteMax-this._defaults.minuteMin)%this._defaults.stepMinute,10),d=parseInt(this._defaults.secondMax-(this._defaults.secondMax-this._defaults.secondMin)%this._defaults.stepSecond,10),h=parseInt(this._defaults.millisecMax-(this._defaults.millisecMax-this._defaults.millisecMin)%this._defaults.stepMillisec,10),p=parseInt(this._defaults.microsecMax-(this._defaults.microsecMax-this._defaults.microsecMin)%this._defaults.stepMicrosec,10);this.hour_slider&&(this.control.options(this,this.hour_slider,"hour",{min:this._defaults.hourMin,max:u,step:this._defaults.stepHour}),this.control.value(this,this.hour_slider,"hour",this.hour-this.hour%this._defaults.stepHour)),this.minute_slider&&(this.control.options(this,this.minute_slider,"minute",{min:this._defaults.minuteMin,max:m,step:this._defaults.stepMinute}),this.control.value(this,this.minute_slider,"minute",this.minute-this.minute%this._defaults.stepMinute)),this.second_slider&&(this.control.options(this,this.second_slider,"second",{min:this._defaults.secondMin,max:d,step:this._defaults.stepSecond}),this.control.value(this,this.second_slider,"second",this.second-this.second%this._defaults.stepSecond)),this.millisec_slider&&(this.control.options(this,this.millisec_slider,"millisec",{min:this._defaults.millisecMin,max:h,step:this._defaults.stepMillisec}),this.control.value(this,this.millisec_slider,"millisec",this.millisec-this.millisec%this._defaults.stepMillisec)),this.microsec_slider&&(this.control.options(this,this.microsec_slider,"microsec",{min:this._defaults.microsecMin,max:p,step:this._defaults.stepMicrosec}),this.control.value(this,this.microsec_slider,"microsec",this.microsec-this.microsec%this._defaults.stepMicrosec))}}},_onTimeChange:function(){if(this._defaults.showTimepicker){var e=this.hour_slider?this.control.value(this,this.hour_slider,"hour"):!1,t=this.minute_slider?this.control.value(this,this.minute_slider,"minute"):!1,i=this.second_slider?this.control.value(this,this.second_slider,"second"):!1,s=this.millisec_slider?this.control.value(this,this.millisec_slider,"millisec"):!1,a=this.microsec_slider?this.control.value(this,this.microsec_slider,"microsec"):!1,n=this.timezone_select?this.timezone_select.val():!1,r=this._defaults,l=r.pickerTimeFormat||r.timeFormat,o=r.pickerTimeSuffix||r.timeSuffix;"object"==typeof e&&(e=!1),"object"==typeof t&&(t=!1),"object"==typeof i&&(i=!1),"object"==typeof s&&(s=!1),"object"==typeof a&&(a=!1),"object"==typeof n&&(n=!1),e!==!1&&(e=parseInt(e,10)),t!==!1&&(t=parseInt(t,10)),i!==!1&&(i=parseInt(i,10)),s!==!1&&(s=parseInt(s,10)),a!==!1&&(a=parseInt(a,10)),n!==!1&&(n=""+n);var c=r[12>e?"amNames":"pmNames"][0],u=e!==parseInt(this.hour,10)||t!==parseInt(this.minute,10)||i!==parseInt(this.second,10)||s!==parseInt(this.millisec,10)||a!==parseInt(this.microsec,10)||this.ampm.length>0&&12>e!=(-1!==$.inArray(this.ampm.toUpperCase(),this.amNames))||null!==this.timezone&&n!==""+this.timezone;u&&(e!==!1&&(this.hour=e),t!==!1&&(this.minute=t),i!==!1&&(this.second=i),s!==!1&&(this.millisec=s),a!==!1&&(this.microsec=a),n!==!1&&(this.timezone=n),this.inst||(this.inst=$.datepicker._getInst(this.$input[0])),this._limitMinMaxDateTime(this.inst,!0)),this.support.ampm&&(this.ampm=c),this.formattedTime=$.datepicker.formatTime(r.timeFormat,this,r),this.$timeObj&&(l===r.timeFormat?this.$timeObj.text(this.formattedTime+o):this.$timeObj.text($.datepicker.formatTime(l,this,r)+o)),this.timeDefined=!0,u&&this._updateDateTime()}},_onSelectHandler:function(){var e=this._defaults.onSelect||this.inst.settings.onSelect,t=this.$input?this.$input[0]:null;e&&t&&e.apply(t,[this.formattedDateTime,this])},_updateDateTime:function(e){e=this.inst||e;var t=e.currentYear>0?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(e.selectedYear,e.selectedMonth,e.selectedDay),i=$.datepicker._daylightSavingAdjust(t),s=$.datepicker._get(e,"dateFormat"),a=$.datepicker._getFormatConfig(e),n=null!==i&&this.timeDefined;this.formattedDate=$.datepicker.formatDate(s,null===i?new Date:i,a);var r=this.formattedDate;if(""===e.lastVal&&(e.currentYear=e.selectedYear,e.currentMonth=e.selectedMonth,e.currentDay=e.selectedDay),this._defaults.timeOnly===!0&&this._defaults.timeOnlyShowDate===!1?r=this.formattedTime:(this._defaults.timeOnly!==!0&&(this._defaults.alwaysSetTime||n)||this._defaults.timeOnly===!0&&this._defaults.timeOnlyShowDate===!0)&&(r+=this._defaults.separator+this.formattedTime+this._defaults.timeSuffix),this.formattedDateTime=r,this._defaults.showTimepicker)if(this.$altInput&&this._defaults.timeOnly===!1&&this._defaults.altFieldTimeOnly===!0)this.$altInput.val(this.formattedTime),this.$input.val(this.formattedDate);else if(this.$altInput){this.$input.val(r);var l="",o=null!==this._defaults.altSeparator?this._defaults.altSeparator:this._defaults.separator,c=null!==this._defaults.altTimeSuffix?this._defaults.altTimeSuffix:this._defaults.timeSuffix;this._defaults.timeOnly||(l=this._defaults.altFormat?$.datepicker.formatDate(this._defaults.altFormat,null===i?new Date:i,a):this.formattedDate,l&&(l+=o)),l+=null!==this._defaults.altTimeFormat?$.datepicker.formatTime(this._defaults.altTimeFormat,this,this._defaults)+c:this.formattedTime+c,this.$altInput.val(l)}else this.$input.val(r);else this.$input.val(this.formattedDate);this.$input.trigger("change")},_onFocus:function(){if(!this.$input.val()&&this._defaults.defaultValue){this.$input.val(this._defaults.defaultValue);var e=$.datepicker._getInst(this.$input.get(0)),t=$.datepicker._get(e,"timepicker");if(t&&t._defaults.timeOnly&&e.input.val()!==e.lastVal)try{$.datepicker._updateDatepicker(e)}catch(i){$.timepicker.log(i)}}},_controls:{slider:{create:function(e,t,i,s,a,n,r){var l=e._defaults.isRTL;return t.prop("slide",null).slider({orientation:"horizontal",value:l?-1*s:s,min:l?-1*n:a,max:l?-1*a:n,step:r,slide:function(t,s){e.control.value(e,$(this),i,l?-1*s.value:s.value),e._onTimeChange()},stop:function(){e._onSelectHandler()}})},options:function(e,t,i,s,a){if(e._defaults.isRTL){if("string"==typeof s)return"min"===s||"max"===s?void 0!==a?t.slider(s,-1*a):Math.abs(t.slider(s)):t.slider(s);var n=s.min,r=s.max;return s.min=s.max=null,void 0!==n&&(s.max=-1*n),void 0!==r&&(s.min=-1*r),t.slider(s)}return"string"==typeof s&&void 0!==a?t.slider(s,a):t.slider(s)},value:function(e,t,i,s){return e._defaults.isRTL?void 0!==s?t.slider("value",-1*s):Math.abs(t.slider("value")):void 0!==s?t.slider("value",s):t.slider("value")}},select:{create:function(e,t,i,s,a,n,r){for(var l='<select class="ui-timepicker-select ui-state-default ui-corner-all" data-unit="'+i+'" data-min="'+a+'" data-max="'+n+'" data-step="'+r+'">',o=e._defaults.pickerTimeFormat||e._defaults.timeFormat,c=a;n>=c;c+=r)l+='<option value="'+c+'"'+(c===s?" selected":"")+">",l+="hour"===i?$.datepicker.formatTime($.trim(o.replace(/[^ht ]/gi,"")),{hour:c},e._defaults):"millisec"===i||"microsec"===i||c>=10?c:"0"+(""+c),l+="</option>";return l+="</select>",t.children("select").remove(),$(l).appendTo(t).change(function(){e._onTimeChange(),e._onSelectHandler()}),t},options:function(e,t,i,s,a){var n={},r=t.children("select");if("string"==typeof s){if(void 0===a)return r.data(s);n[s]=a}else n=s;return e.control.create(e,t,r.data("unit"),r.val(),n.min||r.data("min"),n.max||r.data("max"),n.step||r.data("step"))},value:function(e,t,i,s){var a=t.children("select");return void 0!==s?a.val(s):a.val()}}}}),$.fn.extend({timepicker:function(e){e=e||{};var t=Array.prototype.slice.call(arguments);return"object"==typeof e&&(t[0]=$.extend(e,{timeOnly:!0})),$(this).each(function(){$.fn.datetimepicker.apply($(this),t)})},datetimepicker:function(e){e=e||{};var t=arguments;return"string"==typeof e?"getDate"===e||"option"===e&&2===t.length&&"string"==typeof t[1]?$.fn.datepicker.apply($(this[0]),t):this.each(function(){var e=$(this);e.datepicker.apply(e,t)}):this.each(function(){var t=$(this);t.datepicker($.timepicker._newInst(t,e)._defaults)})}}),$.datepicker.parseDateTime=function(e,t,i,s,a){var n=parseDateTimeInternal(e,t,i,s,a);if(n.timeObj){var r=n.timeObj;n.date.setHours(r.hour,r.minute,r.second,r.millisec),n.date.setMicroseconds(r.microsec)}return n.date},$.datepicker.parseTime=function(e,t,i){var s=extendRemove(extendRemove({},$.timepicker._defaults),i||{});-1!==e.replace(/\'.*?\'/g,"").indexOf("Z");var a=function(e,t,i){var s,a=function(e,t){var i=[];return e&&$.merge(i,e),t&&$.merge(i,t),i=$.map(i,function(e){return e.replace(/[.*+?|()\[\]{}\\]/g,"\\$&")}),"("+i.join("|")+")?"},n=function(e){var t=e.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g),i={h:-1,m:-1,s:-1,l:-1,c:-1,t:-1,z:-1};if(t)for(var s=0;t.length>s;s++)-1===i[(""+t[s]).charAt(0)]&&(i[(""+t[s]).charAt(0)]=s+1);return i},r="^"+(""+e).replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g,function(e){var t=e.length;switch(e.charAt(0).toLowerCase()){case"h":return 1===t?"(\\d?\\d)":"(\\d{"+t+"})";case"m":return 1===t?"(\\d?\\d)":"(\\d{"+t+"})";case"s":return 1===t?"(\\d?\\d)":"(\\d{"+t+"})";case"l":return"(\\d?\\d?\\d)";case"c":return"(\\d?\\d?\\d)";case"z":return"(z|[-+]\\d\\d:?\\d\\d|\\S+)?";case"t":return a(i.amNames,i.pmNames);default:return"("+e.replace(/\'/g,"").replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g,function(e){return"\\"+e})+")?"}}).replace(/\s/g,"\\s?")+i.timeSuffix+"$",l=n(e),o="";s=t.match(RegExp(r,"i"));var c={hour:0,minute:0,second:0,millisec:0,microsec:0};return s?(-1!==l.t&&(void 0===s[l.t]||0===s[l.t].length?(o="",c.ampm=""):(o=-1!==$.inArray(s[l.t].toUpperCase(),i.amNames)?"AM":"PM",c.ampm=i["AM"===o?"amNames":"pmNames"][0])),-1!==l.h&&(c.hour="AM"===o&&"12"===s[l.h]?0:"PM"===o&&"12"!==s[l.h]?parseInt(s[l.h],10)+12:Number(s[l.h])),-1!==l.m&&(c.minute=Number(s[l.m])),-1!==l.s&&(c.second=Number(s[l.s])),-1!==l.l&&(c.millisec=Number(s[l.l])),-1!==l.c&&(c.microsec=Number(s[l.c])),-1!==l.z&&void 0!==s[l.z]&&(c.timezone=$.timepicker.timezoneOffsetNumber(s[l.z])),c):!1},n=function(e,t,i){try{var s=new Date("2012-01-01 "+t);if(isNaN(s.getTime())&&(s=new Date("2012-01-01T"+t),isNaN(s.getTime())&&(s=new Date("01/01/2012 "+t),isNaN(s.getTime()))))throw"Unable to parse time with native Date: "+t;return{hour:s.getHours(),minute:s.getMinutes(),second:s.getSeconds(),millisec:s.getMilliseconds(),microsec:s.getMicroseconds(),timezone:-1*s.getTimezoneOffset()}}catch(n){try{return a(e,t,i)}catch(r){$.timepicker.log("Unable to parse \ntimeString: "+t+"\ntimeFormat: "+e)}}return!1};return"function"==typeof s.parse?s.parse(e,t,s):"loose"===s.parse?n(e,t,s):a(e,t,s)},$.datepicker.formatTime=function(e,t,i){i=i||{},i=$.extend({},$.timepicker._defaults,i),t=$.extend({hour:0,minute:0,second:0,millisec:0,microsec:0,timezone:null},t);var s=e,a=i.amNames[0],n=parseInt(t.hour,10);return n>11&&(a=i.pmNames[0]),s=s.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g,function(e){switch(e){case"HH":return("0"+n).slice(-2);case"H":return n;case"hh":return("0"+convert24to12(n)).slice(-2);case"h":return convert24to12(n);case"mm":return("0"+t.minute).slice(-2);case"m":return t.minute;case"ss":return("0"+t.second).slice(-2);case"s":return t.second;case"l":return("00"+t.millisec).slice(-3);case"c":return("00"+t.microsec).slice(-3);case"z":return $.timepicker.timezoneOffsetString(null===t.timezone?i.timezone:t.timezone,!1);case"Z":return $.timepicker.timezoneOffsetString(null===t.timezone?i.timezone:t.timezone,!0);case"T":return a.charAt(0).toUpperCase();case"TT":return a.toUpperCase();case"t":return a.charAt(0).toLowerCase();case"tt":return a.toLowerCase();default:return e.replace(/'/g,"")}})},$.datepicker._base_selectDate=$.datepicker._selectDate,$.datepicker._selectDate=function(e,t){var i,s=this._getInst($(e)[0]),a=this._get(s,"timepicker");a&&s.settings.showTimepicker?(a._limitMinMaxDateTime(s,!0),i=s.inline,s.inline=s.stay_open=!0,this._base_selectDate(e,t),s.inline=i,s.stay_open=!1,this._notifyChange(s),this._updateDatepicker(s)):this._base_selectDate(e,t)},$.datepicker._base_updateDatepicker=$.datepicker._updateDatepicker,$.datepicker._updateDatepicker=function(e){var t=e.input[0];if(!($.datepicker._curInst&&$.datepicker._curInst!==e&&$.datepicker._datepickerShowing&&$.datepicker._lastInput!==t||"boolean"==typeof e.stay_open&&e.stay_open!==!1)){this._base_updateDatepicker(e);var i=this._get(e,"timepicker");i&&i._addTimePicker(e)}},$.datepicker._base_doKeyPress=$.datepicker._doKeyPress,$.datepicker._doKeyPress=function(e){var t=$.datepicker._getInst(e.target),i=$.datepicker._get(t,"timepicker");if(i&&$.datepicker._get(t,"constrainInput")){var s=i.support.ampm,a=null!==i._defaults.showTimezone?i._defaults.showTimezone:i.support.timezone,n=$.datepicker._possibleChars($.datepicker._get(t,"dateFormat")),r=(""+i._defaults.timeFormat).replace(/[hms]/g,"").replace(/TT/g,s?"APM":"").replace(/Tt/g,s?"AaPpMm":"").replace(/tT/g,s?"AaPpMm":"").replace(/T/g,s?"AP":"").replace(/tt/g,s?"apm":"").replace(/t/g,s?"ap":"")+" "+i._defaults.separator+i._defaults.timeSuffix+(a?i._defaults.timezoneList.join(""):"")+i._defaults.amNames.join("")+i._defaults.pmNames.join("")+n,l=String.fromCharCode(void 0===e.charCode?e.keyCode:e.charCode);return e.ctrlKey||" ">l||!n||r.indexOf(l)>-1}return $.datepicker._base_doKeyPress(e)},$.datepicker._base_updateAlternate=$.datepicker._updateAlternate,$.datepicker._updateAlternate=function(e){var t=this._get(e,"timepicker");if(t){var i=t._defaults.altField;if(i){var s=(t._defaults.altFormat||t._defaults.dateFormat,this._getDate(e)),a=$.datepicker._getFormatConfig(e),n="",r=t._defaults.altSeparator?t._defaults.altSeparator:t._defaults.separator,l=t._defaults.altTimeSuffix?t._defaults.altTimeSuffix:t._defaults.timeSuffix,o=null!==t._defaults.altTimeFormat?t._defaults.altTimeFormat:t._defaults.timeFormat;n+=$.datepicker.formatTime(o,t,t._defaults)+l,t._defaults.timeOnly||t._defaults.altFieldTimeOnly||null===s||(n=t._defaults.altFormat?$.datepicker.formatDate(t._defaults.altFormat,s,a)+r+n:t.formattedDate+r+n),$(i).val(e.input.val()?n:"")}}else $.datepicker._base_updateAlternate(e)},$.datepicker._base_doKeyUp=$.datepicker._doKeyUp,$.datepicker._doKeyUp=function(e){var t=$.datepicker._getInst(e.target),i=$.datepicker._get(t,"timepicker");if(i&&i._defaults.timeOnly&&t.input.val()!==t.lastVal)try{$.datepicker._updateDatepicker(t)}catch(s){$.timepicker.log(s)}return $.datepicker._base_doKeyUp(e)},$.datepicker._base_gotoToday=$.datepicker._gotoToday,$.datepicker._gotoToday=function(e){var t=this._getInst($(e)[0]);t.dpDiv,this._base_gotoToday(e);var i=this._get(t,"timepicker");selectLocalTimezone(i);var s=new Date;this._setTime(t,s),this._setDate(t,s)},$.datepicker._disableTimepickerDatepicker=function(e){var t=this._getInst(e);if(t){var i=this._get(t,"timepicker");$(e).datepicker("getDate"),i&&(t.settings.showTimepicker=!1,i._defaults.showTimepicker=!1,i._updateDateTime(t))}},$.datepicker._enableTimepickerDatepicker=function(e){var t=this._getInst(e);if(t){var i=this._get(t,"timepicker");$(e).datepicker("getDate"),i&&(t.settings.showTimepicker=!0,i._defaults.showTimepicker=!0,i._addTimePicker(t),i._updateDateTime(t))}},$.datepicker._setTime=function(e,t){var i=this._get(e,"timepicker");if(i){var s=i._defaults; i.hour=t?t.getHours():s.hour,i.minute=t?t.getMinutes():s.minute,i.second=t?t.getSeconds():s.second,i.millisec=t?t.getMilliseconds():s.millisec,i.microsec=t?t.getMicroseconds():s.microsec,i._limitMinMaxDateTime(e,!0),i._onTimeChange(),i._updateDateTime(e)}},$.datepicker._setTimeDatepicker=function(e,t,i){var s=this._getInst(e);if(s){var a=this._get(s,"timepicker");if(a){this._setDateFromField(s);var n;t&&("string"==typeof t?(a._parseTime(t,i),n=new Date,n.setHours(a.hour,a.minute,a.second,a.millisec),n.setMicroseconds(a.microsec)):(n=new Date(t.getTime()),n.setMicroseconds(t.getMicroseconds())),"Invalid Date"==""+n&&(n=void 0),this._setTime(s,n))}}},$.datepicker._base_setDateDatepicker=$.datepicker._setDateDatepicker,$.datepicker._setDateDatepicker=function(e,t){var i=this._getInst(e),s=t;if(i){"string"==typeof t&&(s=new Date(t),s.getTime()||(this._base_setDateDatepicker.apply(this,arguments),s=$(e).datepicker("getDate")));var a,n=this._get(i,"timepicker");s instanceof Date?(a=new Date(s.getTime()),a.setMicroseconds(s.getMicroseconds())):a=s,n&&a&&(n.support.timezone||null!==n._defaults.timezone||(n.timezone=-1*a.getTimezoneOffset()),s=$.timepicker.timezoneAdjust(s,n.timezone),a=$.timepicker.timezoneAdjust(a,n.timezone)),this._updateDatepicker(i),this._base_setDateDatepicker.apply(this,arguments),this._setTimeDatepicker(e,a,!0)}},$.datepicker._base_getDateDatepicker=$.datepicker._getDateDatepicker,$.datepicker._getDateDatepicker=function(e,t){var i=this._getInst(e);if(i){var s=this._get(i,"timepicker");if(s){void 0===i.lastVal&&this._setDateFromField(i,t);var a=this._getDate(i);return a&&s._parseTime($(e).val(),s.timeOnly)&&(a.setHours(s.hour,s.minute,s.second,s.millisec),a.setMicroseconds(s.microsec),null!=s.timezone&&(s.support.timezone||null!==s._defaults.timezone||(s.timezone=-1*a.getTimezoneOffset()),a=$.timepicker.timezoneAdjust(a,s.timezone))),a}return this._base_getDateDatepicker(e,t)}},$.datepicker._base_parseDate=$.datepicker.parseDate,$.datepicker.parseDate=function(e,t,i){var s;try{s=this._base_parseDate(e,t,i)}catch(a){if(!(a.indexOf(":")>=0))throw a;s=this._base_parseDate(e,t.substring(0,t.length-(a.length-a.indexOf(":")-2)),i),$.timepicker.log("Error parsing the date string: "+a+"\ndate string = "+t+"\ndate format = "+e)}return s},$.datepicker._base_formatDate=$.datepicker._formatDate,$.datepicker._formatDate=function(e){var t=this._get(e,"timepicker");return t?(t._updateDateTime(e),t.$input.val()):this._base_formatDate(e)},$.datepicker._base_optionDatepicker=$.datepicker._optionDatepicker,$.datepicker._optionDatepicker=function(e,t,i){var s,a=this._getInst(e);if(!a)return null;var n=this._get(a,"timepicker");if(n){var r,l,o,c,u=null,m=null,d=null,h=n._defaults.evnts,p={};if("string"==typeof t){if("minDate"===t||"minDateTime"===t)u=i;else if("maxDate"===t||"maxDateTime"===t)m=i;else if("onSelect"===t)d=i;else if(h.hasOwnProperty(t)){if(i===void 0)return h[t];p[t]=i,s={}}}else if("object"==typeof t){t.minDate?u=t.minDate:t.minDateTime?u=t.minDateTime:t.maxDate?m=t.maxDate:t.maxDateTime&&(m=t.maxDateTime);for(r in h)h.hasOwnProperty(r)&&t[r]&&(p[r]=t[r])}for(r in p)p.hasOwnProperty(r)&&(h[r]=p[r],s||(s=$.extend({},t)),delete s[r]);if(s&&isEmptyObject(s))return;if(u?(u=0===u?new Date:new Date(u),n._defaults.minDate=u,n._defaults.minDateTime=u):m?(m=0===m?new Date:new Date(m),n._defaults.maxDate=m,n._defaults.maxDateTime=m):d&&(n._defaults.onSelect=d),u||m)return c=$(e),o=c.datetimepicker("getDate"),l=this._base_optionDatepicker.call($.datepicker,e,s||t,i),c.datetimepicker("setDate",o),l}return void 0===i?this._base_optionDatepicker.call($.datepicker,e,t):this._base_optionDatepicker.call($.datepicker,e,s||t,i)};var isEmptyObject=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return!1;return!0},extendRemove=function(e,t){$.extend(e,t);for(var i in t)(null===t[i]||void 0===t[i])&&(e[i]=t[i]);return e},detectSupport=function(e){var t=e.replace(/'.*?'/g,"").toLowerCase(),i=function(e,t){return-1!==e.indexOf(t)?!0:!1};return{hour:i(t,"h"),minute:i(t,"m"),second:i(t,"s"),millisec:i(t,"l"),microsec:i(t,"c"),timezone:i(t,"z"),ampm:i(t,"t")&&i(e,"h"),iso8601:i(e,"Z")}},convert24to12=function(e){return e%=12,0===e&&(e=12),e+""},computeEffectiveSetting=function(e,t){return e&&e[t]?e[t]:$.timepicker._defaults[t]},splitDateTime=function(e,t){var i=computeEffectiveSetting(t,"separator"),s=computeEffectiveSetting(t,"timeFormat"),a=s.split(i),n=a.length,r=e.split(i),l=r.length;return l>1?{dateString:r.splice(0,l-n).join(i),timeString:r.splice(0,n).join(i)}:{dateString:e,timeString:""}},parseDateTimeInternal=function(e,t,i,s,a){var n,r,l;if(r=splitDateTime(i,a),n=$.datepicker._base_parseDate(e,r.dateString,s),""===r.timeString)return{date:n};if(l=$.datepicker.parseTime(t,r.timeString,a),!l)throw"Wrong time format";return{date:n,timeObj:l}},selectLocalTimezone=function(e,t){if(e&&e.timezone_select){var i=t||new Date;e.timezone_select.val(-i.getTimezoneOffset())}};$.timepicker=new Timepicker,$.timepicker.timezoneOffsetString=function(e,t){if(isNaN(e)||e>840||-720>e)return e;var i=e,s=i%60,a=(i-s)/60,n=t?":":"",r=(i>=0?"+":"-")+("0"+Math.abs(a)).slice(-2)+n+("0"+Math.abs(s)).slice(-2);return"+00:00"===r?"Z":r},$.timepicker.timezoneOffsetNumber=function(e){var t=(""+e).replace(":","");return"Z"===t.toUpperCase()?0:/^(\-|\+)\d{4}$/.test(t)?("-"===t.substr(0,1)?-1:1)*(60*parseInt(t.substr(1,2),10)+parseInt(t.substr(3,2),10)):e},$.timepicker.timezoneAdjust=function(e,t){var i=$.timepicker.timezoneOffsetNumber(t);return isNaN(i)||e.setMinutes(e.getMinutes()+-e.getTimezoneOffset()-i),e},$.timepicker.timeRange=function(e,t,i){return $.timepicker.handleRange("timepicker",e,t,i)},$.timepicker.datetimeRange=function(e,t,i){$.timepicker.handleRange("datetimepicker",e,t,i)},$.timepicker.dateRange=function(e,t,i){$.timepicker.handleRange("datepicker",e,t,i)},$.timepicker.handleRange=function(e,t,i,s){function a(a,n){var r=t[e]("getDate"),l=i[e]("getDate"),o=a[e]("getDate");if(null!==r){var c=new Date(r.getTime()),u=new Date(r.getTime());c.setMilliseconds(c.getMilliseconds()+s.minInterval),u.setMilliseconds(u.getMilliseconds()+s.maxInterval),s.minInterval>0&&c>l?i[e]("setDate",c):s.maxInterval>0&&l>u?i[e]("setDate",u):r>l&&n[e]("setDate",o)}}function n(t,i,a){if(t.val()){var n=t[e].call(t,"getDate");null!==n&&s.minInterval>0&&("minDate"===a&&n.setMilliseconds(n.getMilliseconds()+s.minInterval),"maxDate"===a&&n.setMilliseconds(n.getMilliseconds()-s.minInterval)),n.getTime&&i[e].call(i,"option",a,n)}}s=$.extend({},{minInterval:0,maxInterval:0,start:{},end:{}},s);var r=!1;return"timepicker"===e&&(r=!0,e="datetimepicker"),$.fn[e].call(t,$.extend({timeOnly:r,onClose:function(){a($(this),i)},onSelect:function(){n($(this),i,"minDate")}},s,s.start)),$.fn[e].call(i,$.extend({timeOnly:r,onClose:function(){a($(this),t)},onSelect:function(){n($(this),t,"maxDate")}},s,s.end)),a(t,i),n(t,i,"minDate"),n(i,t,"maxDate"),$([t.get(0),i.get(0)])},$.timepicker.log=function(){window.console&&window.console.log.apply(window.console,Array.prototype.slice.call(arguments))},$.timepicker._util={_extendRemove:extendRemove,_isEmptyObject:isEmptyObject,_convert24to12:convert24to12,_detectSupport:detectSupport,_selectLocalTimezone:selectLocalTimezone,_computeEffectiveSetting:computeEffectiveSetting,_splitDateTime:splitDateTime,_parseDateTimeInternal:parseDateTimeInternal},Date.prototype.getMicroseconds||(Date.prototype.microseconds=0,Date.prototype.getMicroseconds=function(){return this.microseconds},Date.prototype.setMicroseconds=function(e){return this.setMilliseconds(this.getMilliseconds()+Math.floor(e/1e3)),this.microseconds=e%1e3,this}),$.timepicker.version="1.5.0"}})(jQuery); cmb2/cmb2/js/index.php 0000644 00000000033 15151523432 0010443 0 ustar 00 <?php // Silence is golden cmb2/cmb2/css/cmb2.min.css 0000644 00000100251 15151523432 0011121 0 ustar 00 @charset "UTF-8";.cmb2-wrap{margin:0}.cmb2-wrap input,.cmb2-wrap textarea{max-width:100%}.cmb2-wrap input[type=text].cmb2-oembed{width:100%}.cmb2-wrap textarea{width:500px;padding:8px}.cmb2-wrap textarea.cmb2-textarea-code{font-family:"Courier 10 Pitch",Courier,monospace;line-height:16px}.cmb2-wrap input.cmb2-text-small,.cmb2-wrap input.cmb2-timepicker{width:100px}.cmb2-wrap input.cmb2-text-money{width:90px}.cmb2-wrap input.cmb2-text-medium{width:230px}.cmb2-wrap input.cmb2-upload-file{width:65%}.cmb2-wrap input.ed_button{padding:2px 4px}.cmb2-wrap input:not([type=hidden])+.button-secondary,.cmb2-wrap input:not([type=hidden])+input,.cmb2-wrap input:not([type=hidden])+select{margin-left:20px}.cmb2-wrap ul{margin:0}.cmb2-wrap li{font-size:14px;line-height:16px;margin:1px 0 5px 0}.cmb2-wrap select{font-size:14px;margin-top:3px}.cmb2-wrap input:focus,.cmb2-wrap textarea:focus{background:#fffff8}.cmb2-wrap input[type=radio]{margin:0 5px 0 0;padding:0}.cmb2-wrap input[type=checkbox]{margin:0 5px 0 0;padding:0}.cmb2-wrap .button-secondary,.cmb2-wrap button{white-space:nowrap}.cmb2-wrap .mceLayout{border:1px solid #e9e9e9!important}.cmb2-wrap .mceIframeContainer{background:#fff}.cmb2-wrap .meta_mce{width:97%}.cmb2-wrap .meta_mce textarea{width:100%}.cmb2-wrap .cmb-multicheck-toggle{margin-top:-1em}.cmb2-wrap .wp-picker-clear.button,.cmb2-wrap .wp-picker-default.button{margin-left:6px;padding:2px 8px}.cmb2-wrap .cmb-row{margin:0}.cmb2-wrap .cmb-row:after{content:'';clear:both;display:block;width:100%}.cmb2-wrap .cmb-row.cmb-repeat .cmb2-metabox-description{padding-top:0;padding-bottom:1em}body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type=radio]::before{margin:.1875rem}@media screen and (max-width:782px){body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type=radio]::before{margin:.4375rem}}.cmb2-metabox{clear:both;margin:0}.cmb2-metabox .cmb-field-list>.cmb-row:first-of-type>.cmb-td,.cmb2-metabox .cmb-field-list>.cmb-row:first-of-type>.cmb-th,.cmb2-metabox>.cmb-row:first-of-type>.cmb-td,.cmb2-metabox>.cmb-row:first-of-type>.cmb-th{border:0}.cmb-add-row{margin:1.8em 0 0}.cmb-nested .cmb-td,.cmb-repeatable-group .cmb-th,.cmb-repeatable-group:first-of-type{border:0}.cmb-repeatable-group:last-of-type,.cmb-row:last-of-type,.cmb2-wrap .cmb-row:last-of-type{border-bottom:0}.cmb-repeatable-grouping{border:1px solid #e9e9e9;padding:0 1em}.cmb-repeatable-grouping.cmb-row{margin:0 0 .8em}.cmb-th{color:#222;float:left;font-weight:600;padding:20px 10px 20px 0;vertical-align:top;width:200px}@media (max-width:450px){.cmb-th{font-size:1.2em;display:block;float:none;padding-bottom:1em;text-align:left;width:100%}.cmb-th label{display:block;margin-top:0;margin-bottom:.5em}}.cmb-td{line-height:1.3;max-width:100%;padding:15px 10px;vertical-align:middle}.cmb-type-title .cmb-td{padding:0}.cmb-th label{display:block;padding:5px 0}.cmb-th+.cmb-td{float:left}.cmb-td .cmb-td{padding-bottom:1em}.cmb-remove-row{text-align:right}.empty-row.hidden{display:none}.cmb-repeat-table{background-color:#fafafa;border:1px solid #e1e1e1}.cmb-repeat-table .cmb-row.cmb-repeat-row{position:relative;counter-increment:el;margin:0;padding:10px 10px 10px 50px;border-bottom:none!important}.cmb-repeat-table .cmb-row.cmb-repeat-row+.cmb-repeat-row{border-top:solid 1px #e9e9e9}.cmb-repeat-table .cmb-row.cmb-repeat-row.ui-sortable-helper{outline:dashed 2px #e9e9e9!important}.cmb-repeat-table .cmb-row.cmb-repeat-row:before{content:counter(el);display:block;top:0;left:0;position:absolute;width:35px;height:100%;line-height:35px;cursor:move;color:#757575;text-align:center;border-right:solid 1px #e9e9e9}.cmb-repeat-table .cmb-row.cmb-repeat-row .cmb-td{margin:0;padding:0}.cmb-repeat-table+.cmb-add-row{margin:0}.cmb-repeat-table+.cmb-add-row:before{content:'';width:1px;height:1.6em;display:block;margin-left:17px;background-color:#dcdcdc}.cmb-repeat-table .cmb-remove-row{top:7px;right:7px;position:absolute;width:auto;margin-left:0;padding:0!important;display:none}.cmb-repeat-table .cmb-remove-row>.cmb-remove-row-button{font-size:20px;text-indent:-1000px;overflow:hidden;position:relative;height:auto;line-height:1;padding:0 10px 0}.cmb-repeat-table .cmb-remove-row>.cmb-remove-row-button:before{content:"";font-family:Dashicons;speak:none;font-weight:400;font-variant:normal;text-transform:none;line-height:1;-webkit-font-smoothing:antialiased;margin:0;text-indent:0;position:absolute;top:0;left:0;width:100%;height:100%;text-align:center;line-height:1.3}.cmb-repeat-table .cmb-repeat-row:hover .cmb-remove-row{display:block}.cmb-repeatable-group .cmb-th{padding:5px}.cmb-repeatable-group .cmb-group-title{background-color:#e9e9e9;padding:8px 12px 8px 2.2em;margin:0 -1em;min-height:1.5em;font-size:14px;line-height:1.4}.cmb-repeatable-group .cmb-group-title h4{border:0;margin:0;font-size:1.2em;font-weight:500;padding:.5em .75em}.cmb-repeatable-group .cmb-group-title .cmb-th{display:block;width:100%}.cmb-repeatable-group .cmb-group-description .cmb-th{font-size:1.2em;display:block;float:none;padding-bottom:1em;text-align:left;width:100%}.cmb-repeatable-group .cmb-group-description .cmb-th label{display:block;margin-top:0;margin-bottom:.5em}.cmb-repeatable-group .cmb-shift-rows{margin-right:1em}.cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-up-alt2{margin-top:.15em}.cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-down-alt2{margin-top:.2em}.cmb-repeatable-group .cmb2-upload-button{float:right}p.cmb2-metabox-description{color:#666;letter-spacing:.01em;margin:0;padding-top:.5em}span.cmb2-metabox-description{color:#666;letter-spacing:.01em}.cmb2-metabox-title{margin:0 0 5px 0;padding:5px 0 0 0;font-size:14px}.cmb-inline ul{padding:4px 0 0 0}.cmb-inline li{display:inline-block;padding-right:18px}.cmb-type-textarea-code pre{margin:0}.cmb2-media-status .img-status{clear:none;display:inline-block;vertical-align:middle;margin-right:10px;width:auto}.cmb2-media-status .img-status img{max-width:350px;height:auto}.cmb2-media-status .embed-status,.cmb2-media-status .img-status img{background:#eee;border:5px solid #fff;outline:1px solid #e9e9e9;box-shadow:inset 0 0 15px rgba(0,0,0,.3),inset 0 0 0 1px rgba(0,0,0,.05);background-image:linear-gradient(45deg,#d0d0d0 25%,transparent 25%,transparent 75%,#d0d0d0 75%,#d0d0d0),linear-gradient(45deg,#d0d0d0 25%,transparent 25%,transparent 75%,#d0d0d0 75%,#d0d0d0);background-position:0 0,10px 10px;background-size:20px 20px;border-radius:2px;-moz-border-radius:2px;margin:15px 0 0 0}.cmb2-media-status .embed-status{float:left;max-width:800px}.cmb2-media-status .embed-status,.cmb2-media-status .img-status{position:relative}.cmb2-media-status .embed-status .cmb2-remove-file-button,.cmb2-media-status .img-status .cmb2-remove-file-button{background:url(../images/ico-delete.png);height:16px;left:-5px;position:absolute;text-indent:-9999px;top:-5px;width:16px}.cmb2-media-status .img-status .cmb2-remove-file-button{top:10px}.cmb2-media-status .file-status>span,.cmb2-media-status .img-status img{cursor:pointer}.cmb2-media-status.cmb-attach-list .file-status>span,.cmb2-media-status.cmb-attach-list .img-status img{cursor:move}.cmb-type-file-list .cmb2-media-status .img-status{clear:none;vertical-align:middle;width:auto;margin-right:10px;margin-bottom:10px;margin-top:0}.cmb-attach-list li{clear:both;display:inline-block;width:100%;margin-top:5px;margin-bottom:10px}.cmb-attach-list li img{float:left;margin-right:10px}.cmb2-remove-wrapper{margin:0}.child-cmb2 .cmb-th{text-align:left}.cmb2-indented-hierarchy{padding-left:1.5em}@media (max-width:450px){.cmb-td,.cmb-th,.cmb-th+.cmb-td{display:block;float:none;width:100%}}#poststuff .cmb-group-title{margin-left:-1em;margin-right:-1em;min-height:1.5em}#poststuff .repeatable .cmb-group-title{padding-left:2.2em}.cmb-type-group .cmb2-wrap,.cmb2-postbox .cmb2-wrap{margin:0}.cmb-type-group .cmb2-wrap>.cmb-field-list>.cmb-row,.cmb2-postbox .cmb2-wrap>.cmb-field-list>.cmb-row{padding:1.8em 0}.cmb-type-group .cmb2-wrap input[type=text].cmb2-oembed,.cmb2-postbox .cmb2-wrap input[type=text].cmb2-oembed{width:100%}.cmb-type-group .cmb-row,.cmb2-postbox .cmb-row{padding:0 0 1.8em;margin:0 0 .8em}.cmb-type-group .cmb-row .cmbhandle,.cmb2-postbox .cmb-row .cmbhandle{right:-1em;position:relative;color:#222}.cmb-type-group .cmb-repeatable-grouping,.cmb2-postbox .cmb-repeatable-grouping{padding:0 1em;max-width:100%;min-width:1px!important}.cmb-type-group .cmb-repeatable-group>.cmb-row,.cmb2-postbox .cmb-repeatable-group>.cmb-row{padding-bottom:0}.cmb-type-group .cmb-th,.cmb2-postbox .cmb-th{width:18%;padding:0 2% 0 0}.cmb-type-group .cmb-td,.cmb2-postbox .cmb-td{margin-bottom:0;padding:0;line-height:1.3}.cmb-type-group .cmb-th+.cmb-td,.cmb2-postbox .cmb-th+.cmb-td{width:80%;float:right}.cmb-type-group .cmb-repeatable-group:not(:last-of-type),.cmb-type-group .cmb-row:not(:last-of-type),.cmb2-postbox .cmb-repeatable-group:not(:last-of-type),.cmb2-postbox .cmb-row:not(:last-of-type){border-bottom:1px solid #e9e9e9}@media (max-width:450px){.cmb-type-group .cmb-repeatable-group:not(:last-of-type),.cmb-type-group .cmb-row:not(:last-of-type),.cmb2-postbox .cmb-repeatable-group:not(:last-of-type),.cmb2-postbox .cmb-row:not(:last-of-type){border-bottom:0}}.cmb-type-group .cmb-remove-field-row,.cmb-type-group .cmb-repeat-group-field,.cmb2-postbox .cmb-remove-field-row,.cmb2-postbox .cmb-repeat-group-field{padding-top:1.8em}.cmb-type-group .button-secondary .dashicons,.cmb2-postbox .button-secondary .dashicons{line-height:1.3}.cmb-type-group .button-secondary.move-down .dashicons,.cmb-type-group .button-secondary.move-up .dashicons,.cmb2-postbox .button-secondary.move-down .dashicons,.cmb2-postbox .button-secondary.move-up .dashicons{line-height:1.1}.cmb-type-group .button-secondary.cmb-add-group-row .dashicons,.cmb2-postbox .button-secondary.cmb-add-group-row .dashicons{line-height:1.5}.js .cmb2-postbox.context-box .handlediv{text-align:center}.js .cmb2-postbox.context-box .toggle-indicator:before{content:"\f142";display:inline-block;font:normal 20px/1 dashicons;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-decoration:none!important}.js .cmb2-postbox.context-box.closed .toggle-indicator:before{content:"\f140"}.cmb2-postbox.context-box{margin-bottom:10px}.cmb2-postbox.context-box.context-before_permalink-box{margin-top:10px}.cmb2-postbox.context-box.context-after_title-box{margin-top:10px}.cmb2-postbox.context-box.context-after_editor-box{margin-top:20px;margin-bottom:0}.cmb2-postbox.context-box.context-form_top-box{margin-top:10px}.cmb2-postbox.context-box.context-form_top-box .hndle{font-size:14px;padding:8px 12px;margin:0;line-height:1.4}.cmb2-postbox.context-box .hndle{cursor:auto}.cmb2-context-wrap{margin-top:10px}.cmb2-context-wrap.cmb2-context-wrap-form_top{margin-right:300px;width:auto}.cmb2-context-wrap.cmb2-context-wrap-no-title .cmb2-metabox{padding:10px}.cmb2-context-wrap .cmb-th{padding:0 2% 0 0;width:18%}.cmb2-context-wrap .cmb-td{width:80%;padding:0}.cmb2-context-wrap .cmb-row{margin-bottom:10px}.cmb2-context-wrap .cmb-row:last-of-type{margin-bottom:0}@media only screen and (max-width:850px){.cmb2-context-wrap.cmb2-context-wrap-form_top{margin-right:0}}.cmb2-options-page{max-width:1200px}.cmb2-options-page.wrap>h2{margin-bottom:1em}.cmb2-options-page .cmb2-metabox>.cmb-row{padding:1em;margin-top:-1px;background:#fff;border:1px solid #e9e9e9;box-shadow:0 1px 1px rgba(0,0,0,.05)}.cmb2-options-page .cmb2-metabox>.cmb-row>.cmb-th{padding:0;font-weight:initial}.cmb2-options-page .cmb2-metabox>.cmb-row>.cmb-th+.cmb-td{float:none;padding:0 0 0 1em;margin-left:200px}@media (max-width:450px){.cmb2-options-page .cmb2-metabox>.cmb-row>.cmb-th+.cmb-td{padding:0;margin-left:0}}.cmb2-options-page .cmb2-wrap .cmb-type-title{margin-top:1em;padding:.6em 1em;background-color:#fafafa}.cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-title{font-size:12px;margin-top:0;margin-bottom:0;text-transform:uppercase}.cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-description{padding-top:.25em}.cmb2-options-page .cmb-repeatable-group .cmb-group-description .cmb-th{padding:0 0 .8em 0}.cmb2-options-page .cmb-repeatable-group .cmb-group-name{font-size:16px;margin-top:0;margin-bottom:0}.cmb2-options-page .cmb-repeatable-group .cmb-th>.cmb2-metabox-description{font-weight:400;padding-bottom:0!important}#addtag .cmb-th{float:none;width:auto;padding:20px 0 0}#addtag .cmb-td{padding:0}#addtag .cmb-th+.cmb-td{float:none}#addtag select{max-width:100%}#addtag .cmb2-metabox{padding-bottom:20px}#addtag .cmb-row li label{display:inline}#poststuff .cmb-repeatable-group h2{margin:0}.edit-tags-php .cmb2-metabox-title,.profile-php .cmb2-metabox-title,.user-edit-php .cmb2-metabox-title{font-size:1.4em}.cmb2-no-box-wrap .cmb-spinner,.cmb2-postbox .cmb-spinner{float:left;display:none}.cmb-spinner{display:none}.cmb-spinner.is-active{display:block}#side-sortables .cmb2-wrap>.cmb-field-list>.cmb-row,.inner-sidebar .cmb2-wrap>.cmb-field-list>.cmb-row{padding:1.4em 0}#side-sortables .cmb2-wrap input[type=text]:not(.wp-color-picker),.inner-sidebar .cmb2-wrap input[type=text]:not(.wp-color-picker){width:100%}#side-sortables .cmb2-wrap input+input:not(.wp-picker-clear),#side-sortables .cmb2-wrap input+select,.inner-sidebar .cmb2-wrap input+input:not(.wp-picker-clear),.inner-sidebar .cmb2-wrap input+select{margin-left:0;margin-top:1em;display:block}#side-sortables .cmb2-wrap input.cmb2-text-money,.inner-sidebar .cmb2-wrap input.cmb2-text-money{max-width:70%}#side-sortables .cmb2-wrap input.cmb2-text-money+.cmb2-metabox-description,.inner-sidebar .cmb2-wrap input.cmb2-text-money+.cmb2-metabox-description{display:block}#side-sortables .cmb2-wrap label,.inner-sidebar .cmb2-wrap label{display:block;font-weight:700;padding:0 0 5px}#side-sortables textarea,.inner-sidebar textarea{max-width:99%}#side-sortables .cmb-repeatable-group,.inner-sidebar .cmb-repeatable-group{border-bottom:1px solid #e9e9e9}#side-sortables .cmb-type-group>.cmb-td>.cmb-repeatable-group,.inner-sidebar .cmb-type-group>.cmb-td>.cmb-repeatable-group{border-bottom:0;margin-bottom:-1.4em}#side-sortables .cmb-td:not(.cmb-remove-row),#side-sortables .cmb-th,#side-sortables .cmb-th+.cmb-td,.inner-sidebar .cmb-td:not(.cmb-remove-row),.inner-sidebar .cmb-th,.inner-sidebar .cmb-th+.cmb-td{width:100%;display:block;float:none}#side-sortables .closed .inside,.inner-sidebar .closed .inside{display:none}#side-sortables .cmb-th,.inner-sidebar .cmb-th{display:block;float:none;padding-bottom:1em;text-align:left;width:100%;padding-left:0;padding-right:0}#side-sortables .cmb-th label,.inner-sidebar .cmb-th label{display:block;margin-top:0;margin-bottom:.5em}#side-sortables .cmb-th label,.inner-sidebar .cmb-th label{font-size:14px;line-height:1.4em}#side-sortables .cmb-group-description .cmb-th,.inner-sidebar .cmb-group-description .cmb-th{padding-top:0}#side-sortables .cmb-group-description .cmb2-metabox-description,.inner-sidebar .cmb-group-description .cmb2-metabox-description{padding:0}#side-sortables .cmb-group-title .cmb-th,.inner-sidebar .cmb-group-title .cmb-th{padding:0}#side-sortables .cmb-repeatable-grouping+.cmb-repeatable-grouping,.inner-sidebar .cmb-repeatable-grouping+.cmb-repeatable-grouping{margin-top:1em}#side-sortables .cmb2-media-status .embed-status img,#side-sortables .cmb2-media-status .img-status img,.inner-sidebar .cmb2-media-status .embed-status img,.inner-sidebar .cmb2-media-status .img-status img{max-width:90%;height:auto}#side-sortables .cmb2-list label,.inner-sidebar .cmb2-list label{display:inline;font-weight:400}#side-sortables .cmb2-metabox-description,.inner-sidebar .cmb2-metabox-description{display:block;padding:7px 0 0}#side-sortables .cmb-type-checkbox .cmb-td label,#side-sortables .cmb-type-checkbox .cmb2-metabox-description,.inner-sidebar .cmb-type-checkbox .cmb-td label,.inner-sidebar .cmb-type-checkbox .cmb2-metabox-description{font-weight:400;display:inline}#side-sortables .cmb-row .cmb2-metabox-description,.inner-sidebar .cmb-row .cmb2-metabox-description{padding-bottom:1.8em}#side-sortables .cmb2-metabox-title,.inner-sidebar .cmb2-metabox-title{font-size:1.2em;font-style:italic}#side-sortables .cmb-remove-row,.inner-sidebar .cmb-remove-row{clear:both;padding-top:12px;padding-bottom:0}#side-sortables .cmb2-upload-button,.inner-sidebar .cmb2-upload-button{clear:both;margin-top:12px}.cmb2-metabox .cmbhandle{color:#757575;float:right;width:27px;height:30px;cursor:pointer;right:-1em;position:relative}.cmb2-metabox .cmbhandle:before{content:'\f142';right:12px;font:normal 20px/1 dashicons;speak:none;display:inline-block;padding:8px 10px;top:0;position:relative;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-decoration:none!important}.cmb2-metabox .postbox.closed .cmbhandle:before{content:'\f140'}.cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row{-webkit-appearance:none!important;background:0 0!important;border:none!important;position:absolute;left:0;top:.5em;line-height:1em;padding:2px 6px 3px;opacity:.5}.cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]){cursor:pointer;color:#a00;opacity:1}.cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]):hover{color:red}* html .cmb2-element.ui-helper-clearfix{height:1%}.cmb2-element .ui-datepicker,.cmb2-element.ui-datepicker{padding:0;margin:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;background-color:#fff;border:1px solid #dfdfdf;border-top:none;-webkit-box-shadow:0 3px 6px rgba(0,0,0,.075);box-shadow:0 3px 6px rgba(0,0,0,.075);min-width:17em;width:auto}.cmb2-element .ui-datepicker *,.cmb2-element.ui-datepicker *{padding:0;font-family:"Open Sans",sans-serif;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.cmb2-element .ui-datepicker table,.cmb2-element.ui-datepicker table{font-size:13px;margin:0;border:none;border-collapse:collapse}.cmb2-element .ui-datepicker .ui-datepicker-header,.cmb2-element .ui-datepicker .ui-widget-header,.cmb2-element.ui-datepicker .ui-datepicker-header,.cmb2-element.ui-datepicker .ui-widget-header{background-image:none;border:none;color:#fff;font-weight:400}.cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover,.cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover{background:0 0;border-color:transparent;cursor:pointer}.cmb2-element .ui-datepicker .ui-datepicker-title,.cmb2-element.ui-datepicker .ui-datepicker-title{margin:0;padding:10px 0;color:#fff;font-size:14px;line-height:14px;text-align:center}.cmb2-element .ui-datepicker .ui-datepicker-title select,.cmb2-element.ui-datepicker .ui-datepicker-title select{margin-top:-8px;margin-bottom:-8px}.cmb2-element .ui-datepicker .ui-datepicker-next,.cmb2-element .ui-datepicker .ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-datepicker-next,.cmb2-element.ui-datepicker .ui-datepicker-prev{position:relative;top:0;height:34px;width:34px}.cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-next,.cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-next,.cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-prev{border:none}.cmb2-element .ui-datepicker .ui-datepicker-prev,.cmb2-element .ui-datepicker .ui-datepicker-prev-hover,.cmb2-element.ui-datepicker .ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-datepicker-prev-hover{left:0}.cmb2-element .ui-datepicker .ui-datepicker-next,.cmb2-element .ui-datepicker .ui-datepicker-next-hover,.cmb2-element.ui-datepicker .ui-datepicker-next,.cmb2-element.ui-datepicker .ui-datepicker-next-hover{right:0}.cmb2-element .ui-datepicker .ui-datepicker-next span,.cmb2-element .ui-datepicker .ui-datepicker-prev span,.cmb2-element.ui-datepicker .ui-datepicker-next span,.cmb2-element.ui-datepicker .ui-datepicker-prev span{display:none}.cmb2-element .ui-datepicker .ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-datepicker-prev{float:left}.cmb2-element .ui-datepicker .ui-datepicker-next,.cmb2-element.ui-datepicker .ui-datepicker-next{float:right}.cmb2-element .ui-datepicker .ui-datepicker-next:before,.cmb2-element .ui-datepicker .ui-datepicker-prev:before,.cmb2-element.ui-datepicker .ui-datepicker-next:before,.cmb2-element.ui-datepicker .ui-datepicker-prev:before{font:normal 20px/34px dashicons;padding-left:7px;color:#fff;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;width:34px;height:34px}.cmb2-element .ui-datepicker .ui-datepicker-prev:before,.cmb2-element.ui-datepicker .ui-datepicker-prev:before{content:'\f341'}.cmb2-element .ui-datepicker .ui-datepicker-next:before,.cmb2-element.ui-datepicker .ui-datepicker-next:before{content:'\f345'}.cmb2-element .ui-datepicker .ui-datepicker-next-hover:before,.cmb2-element .ui-datepicker .ui-datepicker-prev-hover:before,.cmb2-element.ui-datepicker .ui-datepicker-next-hover:before,.cmb2-element.ui-datepicker .ui-datepicker-prev-hover:before{opacity:.7}.cmb2-element .ui-datepicker select.ui-datepicker-month,.cmb2-element .ui-datepicker select.ui-datepicker-year,.cmb2-element.ui-datepicker select.ui-datepicker-month,.cmb2-element.ui-datepicker select.ui-datepicker-year{width:33%;background:0 0;border-color:transparent;box-shadow:none;color:#fff}.cmb2-element .ui-datepicker select.ui-datepicker-month option,.cmb2-element .ui-datepicker select.ui-datepicker-year option,.cmb2-element.ui-datepicker select.ui-datepicker-month option,.cmb2-element.ui-datepicker select.ui-datepicker-year option{color:#333}.cmb2-element .ui-datepicker thead,.cmb2-element.ui-datepicker thead{color:#fff;font-weight:600}.cmb2-element .ui-datepicker thead th,.cmb2-element.ui-datepicker thead th{font-weight:400}.cmb2-element .ui-datepicker th,.cmb2-element.ui-datepicker th{padding:10px}.cmb2-element .ui-datepicker td,.cmb2-element.ui-datepicker td{padding:0;border:1px solid #f4f4f4}.cmb2-element .ui-datepicker td.ui-datepicker-other-month,.cmb2-element.ui-datepicker td.ui-datepicker-other-month{border:transparent}.cmb2-element .ui-datepicker td.ui-datepicker-week-end,.cmb2-element.ui-datepicker td.ui-datepicker-week-end{background-color:#f4f4f4;border:1px solid #f4f4f4}.cmb2-element .ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today,.cmb2-element.ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today{-webkit-box-shadow:inset 0 0 1px 0 rgba(0,0,0,.1);-moz-box-shadow:inset 0 0 1px 0 rgba(0,0,0,.1);box-shadow:inset 0 0 1px 0 rgba(0,0,0,.1)}.cmb2-element .ui-datepicker td.ui-datepicker-today,.cmb2-element.ui-datepicker td.ui-datepicker-today{background-color:#f0f0c0}.cmb2-element .ui-datepicker td.ui-datepicker-current-day,.cmb2-element.ui-datepicker td.ui-datepicker-current-day{background:#bd8}.cmb2-element .ui-datepicker td .ui-state-default,.cmb2-element.ui-datepicker td .ui-state-default{background:0 0;border:none;text-align:center;text-decoration:none;width:auto;display:block;padding:5px 10px;font-weight:400;color:#444}.cmb2-element .ui-datepicker td.ui-state-disabled .ui-state-default,.cmb2-element.ui-datepicker td.ui-state-disabled .ui-state-default{opacity:.5}.cmb2-element .ui-datepicker .ui-datepicker-header,.cmb2-element .ui-datepicker .ui-widget-header,.cmb2-element.ui-datepicker .ui-datepicker-header,.cmb2-element.ui-datepicker .ui-widget-header{background:#00a0d2}.cmb2-element .ui-datepicker thead,.cmb2-element.ui-datepicker thead{background:#32373c}.cmb2-element .ui-datepicker td .ui-state-active,.cmb2-element .ui-datepicker td .ui-state-hover,.cmb2-element.ui-datepicker td .ui-state-active,.cmb2-element.ui-datepicker td .ui-state-hover{background:#0073aa;color:#fff}.cmb2-element .ui-datepicker .ui-timepicker-div,.cmb2-element.ui-datepicker .ui-timepicker-div{font-size:14px}.cmb2-element .ui-datepicker .ui-timepicker-div dl,.cmb2-element.ui-datepicker .ui-timepicker-div dl{text-align:left;padding:0 .6em}.cmb2-element .ui-datepicker .ui-timepicker-div dl dt,.cmb2-element.ui-datepicker .ui-timepicker-div dl dt{float:left;clear:left;padding:0 0 0 5px}.cmb2-element .ui-datepicker .ui-timepicker-div dl dd,.cmb2-element.ui-datepicker .ui-timepicker-div dl dd{margin:0 10px 10px 40%}.cmb2-element .ui-datepicker .ui-timepicker-div dl dd select,.cmb2-element.ui-datepicker .ui-timepicker-div dl dd select{width:100%}.cmb2-element .ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane,.cmb2-element.ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane{padding:.6em;text-align:left}.cmb2-element .ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-primary,.cmb2-element .ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-secondary,.cmb2-element.ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-primary,.cmb2-element.ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-secondary{padding:0 10px 1px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;margin:0 .6em .4em .4em}.admin-color-fresh .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-fresh .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-fresh .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-fresh .cmb2-element.ui-datepicker .ui-widget-header{background:#00a0d2}.admin-color-fresh .cmb2-element .ui-datepicker thead,.admin-color-fresh .cmb2-element.ui-datepicker thead{background:#32373c}.admin-color-fresh .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-fresh .cmb2-element.ui-datepicker td .ui-state-hover{background:#0073aa;color:#fff}.admin-color-blue .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-blue .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-blue .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-blue .cmb2-element.ui-datepicker .ui-widget-header{background:#52accc}.admin-color-blue .cmb2-element .ui-datepicker thead,.admin-color-blue .cmb2-element.ui-datepicker thead{background:#4796b3}.admin-color-blue .cmb2-element .ui-datepicker td .ui-state-active,.admin-color-blue .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-blue .cmb2-element.ui-datepicker td .ui-state-active,.admin-color-blue .cmb2-element.ui-datepicker td .ui-state-hover{background:#096484;color:#fff}.admin-color-blue .cmb2-element .ui-datepicker td.ui-datepicker-today,.admin-color-blue .cmb2-element.ui-datepicker td.ui-datepicker-today{background:#eee}.admin-color-coffee .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-coffee .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-coffee .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-coffee .cmb2-element.ui-datepicker .ui-widget-header{background:#59524c}.admin-color-coffee .cmb2-element .ui-datepicker thead,.admin-color-coffee .cmb2-element.ui-datepicker thead{background:#46403c}.admin-color-coffee .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-coffee .cmb2-element.ui-datepicker td .ui-state-hover{background:#c7a589;color:#fff}.admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-widget-header{background:#523f6d}.admin-color-ectoplasm .cmb2-element .ui-datepicker thead,.admin-color-ectoplasm .cmb2-element.ui-datepicker thead{background:#413256}.admin-color-ectoplasm .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-ectoplasm .cmb2-element.ui-datepicker td .ui-state-hover{background:#a3b745;color:#fff}.admin-color-midnight .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-midnight .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-midnight .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-midnight .cmb2-element.ui-datepicker .ui-widget-header{background:#363b3f}.admin-color-midnight .cmb2-element .ui-datepicker thead,.admin-color-midnight .cmb2-element.ui-datepicker thead{background:#26292c}.admin-color-midnight .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-midnight .cmb2-element.ui-datepicker td .ui-state-hover{background:#e14d43;color:#fff}.admin-color-ocean .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-ocean .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-ocean .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-ocean .cmb2-element.ui-datepicker .ui-widget-header{background:#738e96}.admin-color-ocean .cmb2-element .ui-datepicker thead,.admin-color-ocean .cmb2-element.ui-datepicker thead{background:#627c83}.admin-color-ocean .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-ocean .cmb2-element.ui-datepicker td .ui-state-hover{background:#9ebaa0;color:#fff}.admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover,.admin-color-sunrise .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover,.admin-color-sunrise .cmb2-element.ui-datepicker .ui-widget-header{background:#cf4944}.admin-color-sunrise .cmb2-element .ui-datepicker th,.admin-color-sunrise .cmb2-element.ui-datepicker th{border-color:#be3631;background:#be3631}.admin-color-sunrise .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-sunrise .cmb2-element.ui-datepicker td .ui-state-hover{background:#dd823b;color:#fff}.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-light .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-light .cmb2-element.ui-datepicker .ui-widget-header{background:#e5e5e5}.admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-month,.admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-year,.admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-month,.admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-year{color:#555}.admin-color-light .cmb2-element .ui-datepicker thead,.admin-color-light .cmb2-element.ui-datepicker thead{background:#888}.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-next:before,.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-prev:before,.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-title,.admin-color-light .cmb2-element .ui-datepicker td .ui-state-default,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-next:before,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-prev:before,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-title,.admin-color-light .cmb2-element.ui-datepicker td .ui-state-default{color:#555}.admin-color-light .cmb2-element .ui-datepicker td .ui-state-active,.admin-color-light .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-light .cmb2-element.ui-datepicker td .ui-state-active,.admin-color-light .cmb2-element.ui-datepicker td .ui-state-hover{background:#ccc}.admin-color-light .cmb2-element .ui-datepicker td.ui-datepicker-today,.admin-color-light .cmb2-element.ui-datepicker td.ui-datepicker-today{background:#eee}.admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-widget-header{background:#56b274}.admin-color-bbp-evergreen .cmb2-element .ui-datepicker thead,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker thead{background:#36533f}.admin-color-bbp-evergreen .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker td .ui-state-hover{background:#446950;color:#fff}.admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-widget-header{background:#4ca26a}.admin-color-bbp-mint .cmb2-element .ui-datepicker thead,.admin-color-bbp-mint .cmb2-element.ui-datepicker thead{background:#4f6d59}.admin-color-bbp-mint .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-bbp-mint .cmb2-element.ui-datepicker td .ui-state-hover{background:#5fb37c;color:#fff}.cmb2-char-counter-wrap{margin:.5em 0 1em}.cmb2-char-counter-wrap input[type=text]{font-size:12px;width:25px}.cmb2-char-counter-wrap.cmb2-max-exceeded input[type=text]{border-color:#a00!important}.cmb2-char-counter-wrap.cmb2-max-exceeded .cmb2-char-max-msg{display:inline-block}.cmb2-char-max-msg{color:#a00;display:none;font-weight:600;margin-left:1em} cmb2/cmb2/css/cmb2.css 0000644 00000144202 15151523432 0010343 0 ustar 00 /*! * CMB2 - v2.11.0 - 2024-04-02 * https://cmb2.io * Copyright (c) 2024 * Licensed GPLv2+ */ @charset "UTF-8"; /*-------------------------------------------------------------- * Main Wrap --------------------------------------------------------------*/ /* line 5, sass/partials/_main_wrap.scss */ .cmb2-wrap { margin: 0; } /* line 8, sass/partials/_main_wrap.scss */ .cmb2-wrap input, .cmb2-wrap textarea { max-width: 100%; } /* line 15, sass/partials/_main_wrap.scss */ .cmb2-wrap input[type="text"].cmb2-oembed { width: 100%; } /* line 20, sass/partials/_main_wrap.scss */ .cmb2-wrap textarea { width: 500px; padding: 8px; } /* line 24, sass/partials/_main_wrap.scss */ .cmb2-wrap textarea.cmb2-textarea-code { font-family: "Courier 10 Pitch", Courier, monospace; line-height: 16px; } /* line 32, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-text-small, .cmb2-wrap input.cmb2-timepicker { width: 100px; } /* line 38, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-text-money { width: 90px; } /* line 43, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-text-medium { width: 230px; } /* line 48, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-upload-file { width: 65%; } /* line 52, sass/partials/_main_wrap.scss */ .cmb2-wrap input.ed_button { padding: 2px 4px; } /* line 57, sass/partials/_main_wrap.scss */ .cmb2-wrap input:not([type="hidden"]) + input, .cmb2-wrap input:not([type="hidden"]) + .button-secondary, .cmb2-wrap input:not([type="hidden"]) + select { margin-left: 20px; } /* line 65, sass/partials/_main_wrap.scss */ .cmb2-wrap ul { margin: 0; } /* line 69, sass/partials/_main_wrap.scss */ .cmb2-wrap li { font-size: 14px; line-height: 16px; margin: 1px 0 5px 0; } /* line 80, sass/partials/_main_wrap.scss */ .cmb2-wrap select { font-size: 14px; margin-top: 3px; } /* line 85, sass/partials/_main_wrap.scss */ .cmb2-wrap input:focus, .cmb2-wrap textarea:focus { background: #fffff8; } /* line 90, sass/partials/_main_wrap.scss */ .cmb2-wrap input[type="radio"] { margin: 0 5px 0 0; padding: 0; } /* line 95, sass/partials/_main_wrap.scss */ .cmb2-wrap input[type="checkbox"] { margin: 0 5px 0 0; padding: 0; } /* line 100, sass/partials/_main_wrap.scss */ .cmb2-wrap button, .cmb2-wrap .button-secondary { white-space: nowrap; } /* line 105, sass/partials/_main_wrap.scss */ .cmb2-wrap .mceLayout { border: 1px solid #e9e9e9 !important; } /* line 109, sass/partials/_main_wrap.scss */ .cmb2-wrap .mceIframeContainer { background: #ffffff; } /* line 113, sass/partials/_main_wrap.scss */ .cmb2-wrap .meta_mce { width: 97%; } /* line 116, sass/partials/_main_wrap.scss */ .cmb2-wrap .meta_mce textarea { width: 100%; } /* line 122, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-multicheck-toggle { margin-top: -1em; } /* line 127, sass/partials/_main_wrap.scss */ .cmb2-wrap .wp-picker-clear.button, .cmb2-wrap .wp-picker-default.button { margin-left: 6px; padding: 2px 8px; } /* line 133, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-row { margin: 0; } /* line 136, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-row:after { content: ''; clear: both; display: block; width: 100%; } /* line 143, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-row.cmb-repeat .cmb2-metabox-description { padding-top: 0; padding-bottom: 1em; } /* line 154, sass/partials/_main_wrap.scss */ body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type="radio"]::before { margin: .1875rem; } @media screen and (max-width: 782px) { /* line 154, sass/partials/_main_wrap.scss */ body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type="radio"]::before { margin: .4375rem; } } /* line 162, sass/partials/_main_wrap.scss */ .cmb2-metabox { clear: both; margin: 0; } /* line 168, sass/partials/_main_wrap.scss */ .cmb2-metabox > .cmb-row:first-of-type > .cmb-td, .cmb2-metabox > .cmb-row:first-of-type > .cmb-th, .cmb2-metabox .cmb-field-list > .cmb-row:first-of-type > .cmb-td, .cmb2-metabox .cmb-field-list > .cmb-row:first-of-type > .cmb-th { border: 0; } /* line 175, sass/partials/_main_wrap.scss */ .cmb-add-row { margin: 1.8em 0 0; } /* line 179, sass/partials/_main_wrap.scss */ .cmb-nested .cmb-td, .cmb-repeatable-group .cmb-th, .cmb-repeatable-group:first-of-type { border: 0; } /* line 185, sass/partials/_main_wrap.scss */ .cmb-row:last-of-type, .cmb2-wrap .cmb-row:last-of-type, .cmb-repeatable-group:last-of-type { border-bottom: 0; } /* line 191, sass/partials/_main_wrap.scss */ .cmb-repeatable-grouping { border: 1px solid #e9e9e9; padding: 0 1em; } /* line 195, sass/partials/_main_wrap.scss */ .cmb-repeatable-grouping.cmb-row { margin: 0 0 0.8em; } /* line 203, sass/partials/_main_wrap.scss */ .cmb-th { color: #222222; float: left; font-weight: 600; padding: 20px 10px 20px 0; vertical-align: top; width: 200px; } @media (max-width: 450px) { /* line 203, sass/partials/_main_wrap.scss */ .cmb-th { font-size: 1.2em; display: block; float: none; padding-bottom: 1em; text-align: left; width: 100%; } /* line 27, sass/partials/_mixins.scss */ .cmb-th label { display: block; margin-top: 0; margin-bottom: 0.5em; } } /* line 216, sass/partials/_main_wrap.scss */ .cmb-td { line-height: 1.3; max-width: 100%; padding: 15px 10px; vertical-align: middle; } /* line 225, sass/partials/_main_wrap.scss */ .cmb-type-title .cmb-td { padding: 0; } /* line 230, sass/partials/_main_wrap.scss */ .cmb-th label { display: block; padding: 5px 0; } /* line 235, sass/partials/_main_wrap.scss */ .cmb-th + .cmb-td { float: left; } /* line 239, sass/partials/_main_wrap.scss */ .cmb-td .cmb-td { padding-bottom: 1em; } /* line 243, sass/partials/_main_wrap.scss */ .cmb-remove-row { text-align: right; } /* line 247, sass/partials/_main_wrap.scss */ .empty-row.hidden { display: none; } /* line 252, sass/partials/_main_wrap.scss */ .cmb-repeat-table { background-color: #fafafa; border: 1px solid #e1e1e1; } /* line 256, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row { position: relative; counter-increment: el; margin: 0; padding: 10px 10px 10px 50px; border-bottom: none !important; } /* line 264, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row + .cmb-repeat-row { border-top: solid 1px #e9e9e9; } /* line 268, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row.ui-sortable-helper { outline: dashed 2px #e9e9e9 !important; } /* line 272, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row:before { content: counter(el); display: block; top: 0; left: 0; position: absolute; width: 35px; height: 100%; line-height: 35px; cursor: move; color: #757575; text-align: center; border-right: solid 1px #e9e9e9; } /* line 289, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row .cmb-td { margin: 0; padding: 0; } /* line 296, sass/partials/_main_wrap.scss */ .cmb-repeat-table + .cmb-add-row { margin: 0; } /* line 299, sass/partials/_main_wrap.scss */ .cmb-repeat-table + .cmb-add-row:before { content: ''; width: 1px; height: 1.6em; display: block; margin-left: 17px; background-color: gainsboro; } /* line 309, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-remove-row { top: 7px; right: 7px; position: absolute; width: auto; margin-left: 0; padding: 0 !important; display: none; } /* line 320, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-remove-row > .cmb-remove-row-button { font-size: 20px; text-indent: -1000px; overflow: hidden; position: relative; height: auto; line-height: 1; padding: 0 10px 0; } /* line 331, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-remove-row > .cmb-remove-row-button:before { content: ""; font-family: 'Dashicons'; speak: none; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; margin: 0; text-indent: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; text-align: center; line-height: 1.3; } /* line 338, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-repeat-row:hover .cmb-remove-row { display: block; } /* line 346, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-th { padding: 5px; } /* line 350, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-title { background-color: #e9e9e9; padding: 8px 12px 8px 2.2em; margin: 0 -1em; min-height: 1.5em; font-size: 14px; line-height: 1.4; } /* line 358, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-title h4 { border: 0; margin: 0; font-size: 1.2em; font-weight: 500; padding: 0.5em 0.75em; } /* line 366, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-title .cmb-th { display: block; width: 100%; } /* line 372, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-description .cmb-th { font-size: 1.2em; display: block; float: none; padding-bottom: 1em; text-align: left; width: 100%; } /* line 27, sass/partials/_mixins.scss */ .cmb-repeatable-group .cmb-group-description .cmb-th label { display: block; margin-top: 0; margin-bottom: 0.5em; } /* line 376, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-shift-rows { margin-right: 1em; } /* line 379, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-up-alt2 { margin-top: .15em; } /* line 383, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-down-alt2 { margin-top: .2em; } /* line 388, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb2-upload-button { float: right; } /* line 394, sass/partials/_main_wrap.scss */ p.cmb2-metabox-description { color: #666; letter-spacing: 0.01em; margin: 0; padding-top: .5em; } /* line 401, sass/partials/_main_wrap.scss */ span.cmb2-metabox-description { color: #666; letter-spacing: 0.01em; } /* line 406, sass/partials/_main_wrap.scss */ .cmb2-metabox-title { margin: 0 0 5px 0; padding: 5px 0 0 0; font-size: 14px; } /* line 412, sass/partials/_main_wrap.scss */ .cmb-inline ul { padding: 4px 0 0 0; } /* line 416, sass/partials/_main_wrap.scss */ .cmb-inline li { display: inline-block; padding-right: 18px; } /* line 421, sass/partials/_main_wrap.scss */ .cmb-type-textarea-code pre { margin: 0; } /* line 427, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status { clear: none; display: inline-block; vertical-align: middle; margin-right: 10px; width: auto; } /* line 434, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status img { max-width: 350px; height: auto; } /* line 440, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status img, .cmb2-media-status .embed-status { background: #eee; border: 5px solid #ffffff; outline: 1px solid #e9e9e9; box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(0, 0, 0, 0.05); background-image: linear-gradient(45deg, #d0d0d0 25%, transparent 25%, transparent 75%, #d0d0d0 75%, #d0d0d0), linear-gradient(45deg, #d0d0d0 25%, transparent 25%, transparent 75%, #d0d0d0 75%, #d0d0d0); background-position: 0 0, 10px 10px; background-size: 20px 20px; border-radius: 2px; -moz-border-radius: 2px; margin: 15px 0 0 0; } /* line 454, sass/partials/_main_wrap.scss */ .cmb2-media-status .embed-status { float: left; max-width: 800px; } /* line 459, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status, .cmb2-media-status .embed-status { position: relative; } /* line 462, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status .cmb2-remove-file-button, .cmb2-media-status .embed-status .cmb2-remove-file-button { background: url(../images/ico-delete.png); height: 16px; left: -5px; position: absolute; text-indent: -9999px; top: -5px; width: 16px; } /* line 476, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status .cmb2-remove-file-button { top: 10px; } /* line 481, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status img, .cmb2-media-status .file-status > span { cursor: pointer; } /* line 486, sass/partials/_main_wrap.scss */ .cmb2-media-status.cmb-attach-list .img-status img, .cmb2-media-status.cmb-attach-list .file-status > span { cursor: move; } /* line 493, sass/partials/_main_wrap.scss */ .cmb-type-file-list .cmb2-media-status .img-status { clear: none; vertical-align: middle; width: auto; margin-right: 10px; margin-bottom: 10px; margin-top: 0; } /* line 502, sass/partials/_main_wrap.scss */ .cmb-attach-list li { clear: both; display: inline-block; width: 100%; margin-top: 5px; margin-bottom: 10px; } /* line 508, sass/partials/_main_wrap.scss */ .cmb-attach-list li img { float: left; margin-right: 10px; } /* line 514, sass/partials/_main_wrap.scss */ .cmb2-remove-wrapper { margin: 0; } /* line 518, sass/partials/_main_wrap.scss */ .child-cmb2 .cmb-th { text-align: left; } /* line 522, sass/partials/_main_wrap.scss */ .cmb2-indented-hierarchy { padding-left: 1.5em; } @media (max-width: 450px) { /* line 527, sass/partials/_main_wrap.scss */ .cmb-th, .cmb-td, .cmb-th + .cmb-td { display: block; float: none; width: 100%; } } /*-------------------------------------------------------------- * Post Metaboxes --------------------------------------------------------------*/ /* line 5, sass/partials/_post_metaboxes.scss */ #poststuff .cmb-group-title { margin-left: -1em; margin-right: -1em; min-height: 1.5em; } /* line 11, sass/partials/_post_metaboxes.scss */ #poststuff .repeatable .cmb-group-title { padding-left: 2.2em; } /* line 17, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb2-wrap, .cmb-type-group .cmb2-wrap { margin: 0; } /* line 20, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb2-wrap > .cmb-field-list > .cmb-row, .cmb-type-group .cmb2-wrap > .cmb-field-list > .cmb-row { padding: 1.8em 0; } /* line 26, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb2-wrap input[type=text].cmb2-oembed, .cmb-type-group .cmb2-wrap input[type=text].cmb2-oembed { width: 100%; } /* line 32, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row, .cmb-type-group .cmb-row { padding: 0 0 1.8em; margin: 0 0 0.8em; } /* line 36, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row .cmbhandle, .cmb-type-group .cmb-row .cmbhandle { right: -1em; position: relative; color: #222222; } /* line 43, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-repeatable-grouping, .cmb-type-group .cmb-repeatable-grouping { padding: 0 1em; max-width: 100%; min-width: 1px !important; } /* line 49, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-repeatable-group > .cmb-row, .cmb-type-group .cmb-repeatable-group > .cmb-row { padding-bottom: 0; } /* line 53, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-th, .cmb-type-group .cmb-th { width: 18%; padding: 0 2% 0 0; } /* line 59, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-td, .cmb-type-group .cmb-td { margin-bottom: 0; padding: 0; line-height: 1.3; } /* line 65, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-th + .cmb-td, .cmb-type-group .cmb-th + .cmb-td { width: 80%; float: right; } /* line 70, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row:not(:last-of-type), .cmb2-postbox .cmb-repeatable-group:not(:last-of-type), .cmb-type-group .cmb-row:not(:last-of-type), .cmb-type-group .cmb-repeatable-group:not(:last-of-type) { border-bottom: 1px solid #e9e9e9; } @media (max-width: 450px) { /* line 70, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row:not(:last-of-type), .cmb2-postbox .cmb-repeatable-group:not(:last-of-type), .cmb-type-group .cmb-row:not(:last-of-type), .cmb-type-group .cmb-repeatable-group:not(:last-of-type) { border-bottom: 0; } } /* line 79, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-repeat-group-field, .cmb2-postbox .cmb-remove-field-row, .cmb-type-group .cmb-repeat-group-field, .cmb-type-group .cmb-remove-field-row { padding-top: 1.8em; } /* line 85, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .button-secondary .dashicons, .cmb-type-group .button-secondary .dashicons { line-height: 1.3; } /* line 89, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .button-secondary.move-up .dashicons, .cmb2-postbox .button-secondary.move-down .dashicons, .cmb-type-group .button-secondary.move-up .dashicons, .cmb-type-group .button-secondary.move-down .dashicons { line-height: 1.1; } /* line 94, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .button-secondary.cmb-add-group-row .dashicons, .cmb-type-group .button-secondary.cmb-add-group-row .dashicons { line-height: 1.5; } /*-------------------------------------------------------------- * Context Metaboxes --------------------------------------------------------------*/ /* Metabox collapse arrow indicators */ /* line 8, sass/partials/_context_metaboxes.scss */ .js .cmb2-postbox.context-box .handlediv { text-align: center; } /* line 13, sass/partials/_context_metaboxes.scss */ .js .cmb2-postbox.context-box .toggle-indicator:before { content: "\f142"; display: inline-block; font: normal 20px/1 dashicons; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-decoration: none !important; } /* line 26, sass/partials/_context_metaboxes.scss */ .js .cmb2-postbox.context-box.closed .toggle-indicator:before { content: "\f140"; } /* line 34, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box { margin-bottom: 10px; } /* line 38, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-before_permalink-box { margin-top: 10px; } /* line 42, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-after_title-box { margin-top: 10px; } /* line 46, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-after_editor-box { margin-top: 20px; margin-bottom: 0; } /* line 51, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-form_top-box { margin-top: 10px; } /* line 55, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-form_top-box .hndle { font-size: 14px; padding: 8px 12px; margin: 0; line-height: 1.4; } /* line 63, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box .hndle { cursor: auto; } /* line 68, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap { margin-top: 10px; } /* line 72, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap.cmb2-context-wrap-form_top { margin-right: 300px; width: auto; } /* line 79, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap.cmb2-context-wrap-no-title .cmb2-metabox { padding: 10px; } /* line 84, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-th { padding: 0 2% 0 0; width: 18%; } /* line 89, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-td { width: 80%; padding: 0; } /* line 94, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-row { margin-bottom: 10px; } /* line 97, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-row:last-of-type { margin-bottom: 0; } /* one column on the post write/edit screen */ @media only screen and (max-width: 850px) { /* line 107, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap.cmb2-context-wrap-form_top { margin-right: 0; } } /*-------------------------------------------------------------- * Options page --------------------------------------------------------------*/ /* line 5, sass/partials/_options-page.scss */ .cmb2-options-page { max-width: 1200px; } /* line 8, sass/partials/_options-page.scss */ .cmb2-options-page.wrap > h2 { margin-bottom: 1em; } /* line 12, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row { padding: 1em; margin-top: -1px; background: #ffffff; border: 1px solid #e9e9e9; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05); } /* line 19, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row > .cmb-th { padding: 0; font-weight: initial; } /* line 24, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row > .cmb-th + .cmb-td { float: none; padding: 0 0 0 1em; margin-left: 200px; } @media (max-width: 450px) { /* line 24, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row > .cmb-th + .cmb-td { padding: 0; margin-left: 0; } } /* line 37, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-wrap .cmb-type-title { margin-top: 1em; padding: 0.6em 1em; background-color: #fafafa; } /* line 42, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-title { font-size: 12px; margin-top: 0; margin-bottom: 0; text-transform: uppercase; } /* line 49, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-description { padding-top: 0.25em; } /* line 55, sass/partials/_options-page.scss */ .cmb2-options-page .cmb-repeatable-group .cmb-group-description .cmb-th { padding: 0 0 0.8em 0; } /* line 59, sass/partials/_options-page.scss */ .cmb2-options-page .cmb-repeatable-group .cmb-group-name { font-size: 16px; margin-top: 0; margin-bottom: 0; } /* line 65, sass/partials/_options-page.scss */ .cmb2-options-page .cmb-repeatable-group .cmb-th > .cmb2-metabox-description { font-weight: 400; padding-bottom: 0 !important; } /*-------------------------------------------------------------- * New-Term Page --------------------------------------------------------------*/ /* line 6, sass/partials/_new_term.scss */ #addtag .cmb-th { float: none; width: auto; padding: 20px 0 0; } /* line 12, sass/partials/_new_term.scss */ #addtag .cmb-td { padding: 0; } /* line 16, sass/partials/_new_term.scss */ #addtag .cmb-th + .cmb-td { float: none; } /* line 20, sass/partials/_new_term.scss */ #addtag select { max-width: 100%; } /* line 24, sass/partials/_new_term.scss */ #addtag .cmb2-metabox { padding-bottom: 20px; } /* line 28, sass/partials/_new_term.scss */ #addtag .cmb-row li label { display: inline; } /*-------------------------------------------------------------- * Misc. --------------------------------------------------------------*/ /* line 5, sass/partials/_misc.scss */ #poststuff .cmb-repeatable-group h2 { margin: 0; } /* line 12, sass/partials/_misc.scss */ .edit-tags-php .cmb2-metabox-title, .profile-php .cmb2-metabox-title, .user-edit-php .cmb2-metabox-title { font-size: 1.4em; } /* line 18, sass/partials/_misc.scss */ .cmb2-postbox .cmb-spinner, .cmb2-no-box-wrap .cmb-spinner { float: left; display: none; } /* line 24, sass/partials/_misc.scss */ .cmb-spinner { display: none; } /* line 26, sass/partials/_misc.scss */ .cmb-spinner.is-active { display: block; } /*-------------------------------------------------------------- * Sidebar Placement Adjustments --------------------------------------------------------------*/ /* line 10, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap > .cmb-field-list > .cmb-row, #side-sortables .cmb2-wrap > .cmb-field-list > .cmb-row { padding: 1.4em 0; } /* line 16, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input[type=text]:not(.wp-color-picker), #side-sortables .cmb2-wrap input[type=text]:not(.wp-color-picker) { width: 100%; } /* line 20, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input + input:not(.wp-picker-clear), .inner-sidebar .cmb2-wrap input + select, #side-sortables .cmb2-wrap input + input:not(.wp-picker-clear), #side-sortables .cmb2-wrap input + select { margin-left: 0; margin-top: 1em; display: block; } /* line 26, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input.cmb2-text-money, #side-sortables .cmb2-wrap input.cmb2-text-money { max-width: 70%; } /* line 28, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input.cmb2-text-money + .cmb2-metabox-description, #side-sortables .cmb2-wrap input.cmb2-text-money + .cmb2-metabox-description { display: block; } /* line 34, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap label, #side-sortables .cmb2-wrap label { display: block; font-weight: 700; padding: 0 0 5px; } /* line 42, sass/partials/_sidebar_placements.scss */ .inner-sidebar textarea, #side-sortables textarea { max-width: 99%; } /* line 46, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-repeatable-group, #side-sortables .cmb-repeatable-group { border-bottom: 1px solid #e9e9e9; } /* line 50, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-type-group > .cmb-td > .cmb-repeatable-group, #side-sortables .cmb-type-group > .cmb-td > .cmb-repeatable-group { border-bottom: 0; margin-bottom: -1.4em; } /* line 55, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-th, .inner-sidebar .cmb-td:not(.cmb-remove-row), .inner-sidebar .cmb-th + .cmb-td, #side-sortables .cmb-th, #side-sortables .cmb-td:not(.cmb-remove-row), #side-sortables .cmb-th + .cmb-td { width: 100%; display: block; float: none; } /* line 63, sass/partials/_sidebar_placements.scss */ .inner-sidebar .closed .inside, #side-sortables .closed .inside { display: none; } /* line 67, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-th, #side-sortables .cmb-th { display: block; float: none; padding-bottom: 1em; text-align: left; width: 100%; padding-left: 0; padding-right: 0; } /* line 27, sass/partials/_mixins.scss */ .inner-sidebar .cmb-th label, #side-sortables .cmb-th label { display: block; margin-top: 0; margin-bottom: 0.5em; } /* line 14, sass/partials/_mixins.scss */ .inner-sidebar .cmb-th label, #side-sortables .cmb-th label { font-size: 14px; line-height: 1.4em; } /* line 74, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-group-description .cmb-th, #side-sortables .cmb-group-description .cmb-th { padding-top: 0; } /* line 77, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-group-description .cmb2-metabox-description, #side-sortables .cmb-group-description .cmb2-metabox-description { padding: 0; } /* line 84, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-group-title .cmb-th, #side-sortables .cmb-group-title .cmb-th { padding: 0; } /* line 90, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-repeatable-grouping + .cmb-repeatable-grouping, #side-sortables .cmb-repeatable-grouping + .cmb-repeatable-grouping { margin-top: 1em; } /* line 99, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-media-status .img-status img, .inner-sidebar .cmb2-media-status .embed-status img, #side-sortables .cmb2-media-status .img-status img, #side-sortables .cmb2-media-status .embed-status img { max-width: 90%; height: auto; } /* line 107, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-list label, #side-sortables .cmb2-list label { display: inline; font-weight: normal; } /* line 112, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-metabox-description, #side-sortables .cmb2-metabox-description { display: block; padding: 7px 0 0; } /* line 119, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-type-checkbox .cmb-td label, .inner-sidebar .cmb-type-checkbox .cmb2-metabox-description, #side-sortables .cmb-type-checkbox .cmb-td label, #side-sortables .cmb-type-checkbox .cmb2-metabox-description { font-weight: normal; display: inline; } /* line 126, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-row .cmb2-metabox-description, #side-sortables .cmb-row .cmb2-metabox-description { padding-bottom: 1.8em; } /* line 130, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-metabox-title, #side-sortables .cmb2-metabox-title { font-size: 1.2em; font-style: italic; } /* line 135, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-remove-row, #side-sortables .cmb-remove-row { clear: both; padding-top: 12px; padding-bottom: 0; } /* line 141, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-upload-button, #side-sortables .cmb2-upload-button { clear: both; margin-top: 12px; } /*-------------------------------------------------------------- * Collapsible UI --------------------------------------------------------------*/ /* line 6, sass/partials/_collapsible_ui.scss */ .cmb2-metabox .cmbhandle { color: #757575; float: right; width: 27px; height: 30px; cursor: pointer; right: -1em; position: relative; } /* line 14, sass/partials/_collapsible_ui.scss */ .cmb2-metabox .cmbhandle:before { content: '\f142'; right: 12px; font: normal 20px/1 'dashicons'; speak: none; display: inline-block; padding: 8px 10px; top: 0; position: relative; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-decoration: none !important; } /* line 31, sass/partials/_collapsible_ui.scss */ .cmb2-metabox .postbox.closed .cmbhandle:before { content: '\f140'; } /* line 37, sass/partials/_collapsible_ui.scss */ .cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row { -webkit-appearance: none !important; background: none !important; border: none !important; position: absolute; left: 0; top: .5em; line-height: 1em; padding: 2px 6px 3px; opacity: .5; } /* line 47, sass/partials/_collapsible_ui.scss */ .cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]) { cursor: pointer; color: #a00; opacity: 1; } /* line 51, sass/partials/_collapsible_ui.scss */ .cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]):hover { color: #f00; } /* * jQuery UI CSS Framework 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Theming/API * * WordPress Styles adopted from "jQuery UI Datepicker CSS for WordPress" * https://github.com/stuttter/wp-datepicker-styling * */ /* line 15, sass/partials/_jquery_ui.scss */ * html .cmb2-element.ui-helper-clearfix { height: 1%; } /* line 24, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker, .cmb2-element .ui-datepicker { padding: 0; margin: 0; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; background-color: #fff; border: 1px solid #dfdfdf; border-top: none; -webkit-box-shadow: 0 3px 6px rgba(0, 0, 0, 0.075); box-shadow: 0 3px 6px rgba(0, 0, 0, 0.075); min-width: 17em; width: auto; /* Default Color Scheme */ } /* line 38, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker *, .cmb2-element .ui-datepicker * { padding: 0; font-family: "Open Sans", sans-serif; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } /* line 46, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker table, .cmb2-element .ui-datepicker table { font-size: 13px; margin: 0; border: none; border-collapse: collapse; } /* line 53, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-widget-header, .cmb2-element.ui-datepicker .ui-datepicker-header, .cmb2-element .ui-datepicker .ui-widget-header, .cmb2-element .ui-datepicker .ui-datepicker-header { background-image: none; border: none; color: #fff; font-weight: normal; } /* line 61, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover, .cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover { background: transparent; border-color: transparent; cursor: pointer; } /* line 67, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-title, .cmb2-element .ui-datepicker .ui-datepicker-title { margin: 0; padding: 10px 0; color: #fff; font-size: 14px; line-height: 14px; text-align: center; } /* line 75, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-title select, .cmb2-element .ui-datepicker .ui-datepicker-title select { margin-top: -8px; margin-bottom: -8px; } /* line 81, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev, .cmb2-element.ui-datepicker .ui-datepicker-next, .cmb2-element .ui-datepicker .ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-datepicker-next { position: relative; top: 0; height: 34px; width: 34px; } /* line 89, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-prev, .cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-next, .cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-next { border: none; } /* line 94, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev, .cmb2-element.ui-datepicker .ui-datepicker-prev-hover, .cmb2-element .ui-datepicker .ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-datepicker-prev-hover { left: 0; } /* line 99, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next, .cmb2-element.ui-datepicker .ui-datepicker-next-hover, .cmb2-element .ui-datepicker .ui-datepicker-next, .cmb2-element .ui-datepicker .ui-datepicker-next-hover { right: 0; } /* line 104, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next span, .cmb2-element.ui-datepicker .ui-datepicker-prev span, .cmb2-element .ui-datepicker .ui-datepicker-next span, .cmb2-element .ui-datepicker .ui-datepicker-prev span { display: none; } /* line 109, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-datepicker-prev { float: left; } /* line 113, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next, .cmb2-element .ui-datepicker .ui-datepicker-next { float: right; } /* line 117, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev:before, .cmb2-element.ui-datepicker .ui-datepicker-next:before, .cmb2-element .ui-datepicker .ui-datepicker-prev:before, .cmb2-element .ui-datepicker .ui-datepicker-next:before { font: normal 20px/34px 'dashicons'; padding-left: 7px; color: #fff; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; width: 34px; height: 34px; } /* line 129, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev:before, .cmb2-element .ui-datepicker .ui-datepicker-prev:before { content: '\f341'; } /* line 133, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next:before, .cmb2-element .ui-datepicker .ui-datepicker-next:before { content: '\f345'; } /* line 137, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev-hover:before, .cmb2-element.ui-datepicker .ui-datepicker-next-hover:before, .cmb2-element .ui-datepicker .ui-datepicker-prev-hover:before, .cmb2-element .ui-datepicker .ui-datepicker-next-hover:before { opacity: 0.7; } /* line 142, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker select.ui-datepicker-month, .cmb2-element.ui-datepicker select.ui-datepicker-year, .cmb2-element .ui-datepicker select.ui-datepicker-month, .cmb2-element .ui-datepicker select.ui-datepicker-year { width: 33%; background: transparent; border-color: transparent; box-shadow: none; color: #fff; } /* line 149, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker select.ui-datepicker-month option, .cmb2-element.ui-datepicker select.ui-datepicker-year option, .cmb2-element .ui-datepicker select.ui-datepicker-month option, .cmb2-element .ui-datepicker select.ui-datepicker-year option { color: #333; } /* line 154, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker thead, .cmb2-element .ui-datepicker thead { color: #fff; font-weight: 600; } /* line 157, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker thead th, .cmb2-element .ui-datepicker thead th { font-weight: normal; } /* line 162, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker th, .cmb2-element .ui-datepicker th { padding: 10px; } /* line 166, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td, .cmb2-element .ui-datepicker td { padding: 0; border: 1px solid #f4f4f4; } /* line 171, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-other-month, .cmb2-element .ui-datepicker td.ui-datepicker-other-month { border: transparent; } /* line 175, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-week-end, .cmb2-element .ui-datepicker td.ui-datepicker-week-end { background-color: #f4f4f4; border: 1px solid #f4f4f4; } /* line 178, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today, .cmb2-element .ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today { -webkit-box-shadow: inset 0px 0px 1px 0px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset 0px 0px 1px 0px rgba(0, 0, 0, 0.1); box-shadow: inset 0px 0px 1px 0px rgba(0, 0, 0, 0.1); } /* line 185, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-today, .cmb2-element .ui-datepicker td.ui-datepicker-today { background-color: #f0f0c0; } /* line 189, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-current-day, .cmb2-element .ui-datepicker td.ui-datepicker-current-day { background: #bbdd88; } /* line 193, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td .ui-state-default, .cmb2-element .ui-datepicker td .ui-state-default { background: transparent; border: none; text-align: center; text-decoration: none; width: auto; display: block; padding: 5px 10px; font-weight: normal; color: #444; } /* line 205, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-state-disabled .ui-state-default, .cmb2-element .ui-datepicker td.ui-state-disabled .ui-state-default { opacity: 0.5; } /* line 210, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-widget-header, .cmb2-element.ui-datepicker .ui-datepicker-header, .cmb2-element .ui-datepicker .ui-widget-header, .cmb2-element .ui-datepicker .ui-datepicker-header { background: #00a0d2; } /* line 215, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker thead, .cmb2-element .ui-datepicker thead { background: #32373c; } /* line 219, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td .ui-state-hover, .cmb2-element.ui-datepicker td .ui-state-active, .cmb2-element .ui-datepicker td .ui-state-hover, .cmb2-element .ui-datepicker td .ui-state-active { background: #0073aa; color: #fff; } /* line 224, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div, .cmb2-element .ui-datepicker .ui-timepicker-div { font-size: 14px; } /* line 226, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl, .cmb2-element .ui-datepicker .ui-timepicker-div dl { text-align: left; padding: 0 .6em; } /* line 229, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl dt, .cmb2-element .ui-datepicker .ui-timepicker-div dl dt { float: left; clear: left; padding: 0 0 0 5px; } /* line 234, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl dd, .cmb2-element .ui-datepicker .ui-timepicker-div dl dd { margin: 0 10px 10px 40%; } /* line 236, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl dd select, .cmb2-element .ui-datepicker .ui-timepicker-div dl dd select { width: 100%; } /* line 242, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane, .cmb2-element .ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane { padding: .6em; text-align: left; } /* line 246, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-primary, .cmb2-element.ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-secondary, .cmb2-element .ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-primary, .cmb2-element .ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-secondary { padding: 0 10px 1px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; margin: 0 .6em .4em .4em; } /* line 260, sass/partials/_jquery_ui.scss */ .admin-color-fresh .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-fresh .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-fresh .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-fresh .cmb2-element .ui-datepicker .ui-datepicker-header { background: #00a0d2; } /* line 265, sass/partials/_jquery_ui.scss */ .admin-color-fresh .cmb2-element.ui-datepicker thead, .admin-color-fresh .cmb2-element .ui-datepicker thead { background: #32373c; } /* line 269, sass/partials/_jquery_ui.scss */ .admin-color-fresh .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-fresh .cmb2-element .ui-datepicker td .ui-state-hover { background: #0073aa; color: #fff; } /* line 277, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-blue .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-blue .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-blue .cmb2-element .ui-datepicker .ui-datepicker-header { background: #52accc; } /* line 282, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker thead, .admin-color-blue .cmb2-element .ui-datepicker thead { background: #4796b3; } /* line 291, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-blue .cmb2-element.ui-datepicker td .ui-state-active, .admin-color-blue .cmb2-element .ui-datepicker td .ui-state-hover, .admin-color-blue .cmb2-element .ui-datepicker td .ui-state-active { background: #096484; color: #fff; } /* line 296, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker td.ui-datepicker-today, .admin-color-blue .cmb2-element .ui-datepicker td.ui-datepicker-today { background: #eee; } /* line 305, sass/partials/_jquery_ui.scss */ .admin-color-coffee .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-coffee .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-coffee .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-coffee .cmb2-element .ui-datepicker .ui-datepicker-header { background: #59524c; } /* line 310, sass/partials/_jquery_ui.scss */ .admin-color-coffee .cmb2-element.ui-datepicker thead, .admin-color-coffee .cmb2-element .ui-datepicker thead { background: #46403c; } /* line 314, sass/partials/_jquery_ui.scss */ .admin-color-coffee .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-coffee .cmb2-element .ui-datepicker td .ui-state-hover { background: #c7a589; color: #fff; } /* line 322, sass/partials/_jquery_ui.scss */ .admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-datepicker-header { background: #523f6d; } /* line 327, sass/partials/_jquery_ui.scss */ .admin-color-ectoplasm .cmb2-element.ui-datepicker thead, .admin-color-ectoplasm .cmb2-element .ui-datepicker thead { background: #413256; } /* line 331, sass/partials/_jquery_ui.scss */ .admin-color-ectoplasm .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-ectoplasm .cmb2-element .ui-datepicker td .ui-state-hover { background: #a3b745; color: #fff; } /* line 339, sass/partials/_jquery_ui.scss */ .admin-color-midnight .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-midnight .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-midnight .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-midnight .cmb2-element .ui-datepicker .ui-datepicker-header { background: #363b3f; } /* line 344, sass/partials/_jquery_ui.scss */ .admin-color-midnight .cmb2-element.ui-datepicker thead, .admin-color-midnight .cmb2-element .ui-datepicker thead { background: #26292c; } /* line 348, sass/partials/_jquery_ui.scss */ .admin-color-midnight .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-midnight .cmb2-element .ui-datepicker td .ui-state-hover { background: #e14d43; color: #fff; } /* line 356, sass/partials/_jquery_ui.scss */ .admin-color-ocean .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-ocean .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-ocean .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-ocean .cmb2-element .ui-datepicker .ui-datepicker-header { background: #738e96; } /* line 361, sass/partials/_jquery_ui.scss */ .admin-color-ocean .cmb2-element.ui-datepicker thead, .admin-color-ocean .cmb2-element .ui-datepicker thead { background: #627c83; } /* line 365, sass/partials/_jquery_ui.scss */ .admin-color-ocean .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-ocean .cmb2-element .ui-datepicker td .ui-state-hover { background: #9ebaa0; color: #fff; } /* line 373, sass/partials/_jquery_ui.scss */ .admin-color-sunrise .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover, .admin-color-sunrise .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header, .admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover { background: #cf4944; } /* line 379, sass/partials/_jquery_ui.scss */ .admin-color-sunrise .cmb2-element.ui-datepicker th, .admin-color-sunrise .cmb2-element .ui-datepicker th { border-color: #be3631; background: #be3631; } /* line 384, sass/partials/_jquery_ui.scss */ .admin-color-sunrise .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-sunrise .cmb2-element .ui-datepicker td .ui-state-hover { background: #dd823b; color: #fff; } /* line 392, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-light .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-header { background: #e5e5e5; } /* line 397, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-month, .admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-year, .admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-month, .admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-year { color: #555; } /* line 402, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker thead, .admin-color-light .cmb2-element .ui-datepicker thead { background: #888; } /* line 406, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-title, .admin-color-light .cmb2-element.ui-datepicker td .ui-state-default, .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-prev:before, .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-next:before, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-title, .admin-color-light .cmb2-element .ui-datepicker td .ui-state-default, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-prev:before, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-next:before { color: #555; } /* line 414, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-light .cmb2-element.ui-datepicker td .ui-state-active, .admin-color-light .cmb2-element .ui-datepicker td .ui-state-hover, .admin-color-light .cmb2-element .ui-datepicker td .ui-state-active { background: #ccc; } /* line 418, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker td.ui-datepicker-today, .admin-color-light .cmb2-element .ui-datepicker td.ui-datepicker-today { background: #eee; } /* line 426, sass/partials/_jquery_ui.scss */ .admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-datepicker-header { background: #56b274; } /* line 431, sass/partials/_jquery_ui.scss */ .admin-color-bbp-evergreen .cmb2-element.ui-datepicker thead, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker thead { background: #36533f; } /* line 435, sass/partials/_jquery_ui.scss */ .admin-color-bbp-evergreen .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker td .ui-state-hover { background: #446950; color: #fff; } /* line 443, sass/partials/_jquery_ui.scss */ .admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-datepicker-header { background: #4ca26a; } /* line 448, sass/partials/_jquery_ui.scss */ .admin-color-bbp-mint .cmb2-element.ui-datepicker thead, .admin-color-bbp-mint .cmb2-element .ui-datepicker thead { background: #4f6d59; } /* line 452, sass/partials/_jquery_ui.scss */ .admin-color-bbp-mint .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-bbp-mint .cmb2-element .ui-datepicker td .ui-state-hover { background: #5fb37c; color: #fff; } /*-------------------------------------------------------------- * Character counter --------------------------------------------------------------*/ /* line 5, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap { margin: .5em 0 1em; } /* line 8, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap input[type="text"] { font-size: 12px; width: 25px; } /* line 14, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap.cmb2-max-exceeded input[type="text"] { border-color: #a00 !important; } /* line 17, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap.cmb2-max-exceeded .cmb2-char-max-msg { display: inline-block; } /* line 23, sass/partials/_char_counter.scss */ .cmb2-char-max-msg { color: #a00; display: none; font-weight: 600; margin-left: 1em; } /*# sourceMappingURL=cmb2.css.map */ cmb2/cmb2/css/cmb2-rtl.css 0000644 00000144216 15151523432 0011147 0 ustar 00 /*! * CMB2 - v2.11.0 - 2024-04-02 * https://cmb2.io * Copyright (c) 2024 * Licensed GPLv2+ */ @charset "UTF-8"; /*-------------------------------------------------------------- * Main Wrap --------------------------------------------------------------*/ /* line 5, sass/partials/_main_wrap.scss */ .cmb2-wrap { margin: 0; } /* line 8, sass/partials/_main_wrap.scss */ .cmb2-wrap input, .cmb2-wrap textarea { max-width: 100%; } /* line 15, sass/partials/_main_wrap.scss */ .cmb2-wrap input[type="text"].cmb2-oembed { width: 100%; } /* line 20, sass/partials/_main_wrap.scss */ .cmb2-wrap textarea { width: 500px; padding: 8px; } /* line 24, sass/partials/_main_wrap.scss */ .cmb2-wrap textarea.cmb2-textarea-code { font-family: "Courier 10 Pitch", Courier, monospace; line-height: 16px; } /* line 32, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-text-small, .cmb2-wrap input.cmb2-timepicker { width: 100px; } /* line 38, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-text-money { width: 90px; } /* line 43, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-text-medium { width: 230px; } /* line 48, sass/partials/_main_wrap.scss */ .cmb2-wrap input.cmb2-upload-file { width: 65%; } /* line 52, sass/partials/_main_wrap.scss */ .cmb2-wrap input.ed_button { padding: 2px 4px; } /* line 57, sass/partials/_main_wrap.scss */ .cmb2-wrap input:not([type="hidden"]) + input, .cmb2-wrap input:not([type="hidden"]) + .button-secondary, .cmb2-wrap input:not([type="hidden"]) + select { margin-right: 20px; } /* line 65, sass/partials/_main_wrap.scss */ .cmb2-wrap ul { margin: 0; } /* line 69, sass/partials/_main_wrap.scss */ .cmb2-wrap li { font-size: 14px; line-height: 16px; margin: 1px 0 5px 0; } /* line 80, sass/partials/_main_wrap.scss */ .cmb2-wrap select { font-size: 14px; margin-top: 3px; } /* line 85, sass/partials/_main_wrap.scss */ .cmb2-wrap input:focus, .cmb2-wrap textarea:focus { background: #fffff8; } /* line 90, sass/partials/_main_wrap.scss */ .cmb2-wrap input[type="radio"] { margin: 0 0 0 5px; padding: 0; } /* line 95, sass/partials/_main_wrap.scss */ .cmb2-wrap input[type="checkbox"] { margin: 0 0 0 5px; padding: 0; } /* line 100, sass/partials/_main_wrap.scss */ .cmb2-wrap button, .cmb2-wrap .button-secondary { white-space: nowrap; } /* line 105, sass/partials/_main_wrap.scss */ .cmb2-wrap .mceLayout { border: 1px solid #e9e9e9 !important; } /* line 109, sass/partials/_main_wrap.scss */ .cmb2-wrap .mceIframeContainer { background: #ffffff; } /* line 113, sass/partials/_main_wrap.scss */ .cmb2-wrap .meta_mce { width: 97%; } /* line 116, sass/partials/_main_wrap.scss */ .cmb2-wrap .meta_mce textarea { width: 100%; } /* line 122, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-multicheck-toggle { margin-top: -1em; } /* line 127, sass/partials/_main_wrap.scss */ .cmb2-wrap .wp-picker-clear.button, .cmb2-wrap .wp-picker-default.button { margin-right: 6px; padding: 2px 8px; } /* line 133, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-row { margin: 0; } /* line 136, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-row:after { content: ''; clear: both; display: block; width: 100%; } /* line 143, sass/partials/_main_wrap.scss */ .cmb2-wrap .cmb-row.cmb-repeat .cmb2-metabox-description { padding-top: 0; padding-bottom: 1em; } /* line 154, sass/partials/_main_wrap.scss */ body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type="radio"]::before { margin: .1875rem; } @media screen and (max-width: 782px) { /* line 154, sass/partials/_main_wrap.scss */ body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type="radio"]::before { margin: .4375rem; } } /* line 162, sass/partials/_main_wrap.scss */ .cmb2-metabox { clear: both; margin: 0; } /* line 168, sass/partials/_main_wrap.scss */ .cmb2-metabox > .cmb-row:first-of-type > .cmb-td, .cmb2-metabox > .cmb-row:first-of-type > .cmb-th, .cmb2-metabox .cmb-field-list > .cmb-row:first-of-type > .cmb-td, .cmb2-metabox .cmb-field-list > .cmb-row:first-of-type > .cmb-th { border: 0; } /* line 175, sass/partials/_main_wrap.scss */ .cmb-add-row { margin: 1.8em 0 0; } /* line 179, sass/partials/_main_wrap.scss */ .cmb-nested .cmb-td, .cmb-repeatable-group .cmb-th, .cmb-repeatable-group:first-of-type { border: 0; } /* line 185, sass/partials/_main_wrap.scss */ .cmb-row:last-of-type, .cmb2-wrap .cmb-row:last-of-type, .cmb-repeatable-group:last-of-type { border-bottom: 0; } /* line 191, sass/partials/_main_wrap.scss */ .cmb-repeatable-grouping { border: 1px solid #e9e9e9; padding: 0 1em; } /* line 195, sass/partials/_main_wrap.scss */ .cmb-repeatable-grouping.cmb-row { margin: 0 0 0.8em; } /* line 203, sass/partials/_main_wrap.scss */ .cmb-th { color: #222222; float: right; font-weight: 600; padding: 20px 0 20px 10px; vertical-align: top; width: 200px; } @media (max-width: 450px) { /* line 203, sass/partials/_main_wrap.scss */ .cmb-th { font-size: 1.2em; display: block; float: none; padding-bottom: 1em; text-align: right; width: 100%; } /* line 27, sass/partials/_mixins.scss */ .cmb-th label { display: block; margin-top: 0; margin-bottom: 0.5em; } } /* line 216, sass/partials/_main_wrap.scss */ .cmb-td { line-height: 1.3; max-width: 100%; padding: 15px 10px; vertical-align: middle; } /* line 225, sass/partials/_main_wrap.scss */ .cmb-type-title .cmb-td { padding: 0; } /* line 230, sass/partials/_main_wrap.scss */ .cmb-th label { display: block; padding: 5px 0; } /* line 235, sass/partials/_main_wrap.scss */ .cmb-th + .cmb-td { float: right; } /* line 239, sass/partials/_main_wrap.scss */ .cmb-td .cmb-td { padding-bottom: 1em; } /* line 243, sass/partials/_main_wrap.scss */ .cmb-remove-row { text-align: left; } /* line 247, sass/partials/_main_wrap.scss */ .empty-row.hidden { display: none; } /* line 252, sass/partials/_main_wrap.scss */ .cmb-repeat-table { background-color: #fafafa; border: 1px solid #e1e1e1; } /* line 256, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row { position: relative; counter-increment: el; margin: 0; padding: 10px 50px 10px 10px; border-bottom: none !important; } /* line 264, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row + .cmb-repeat-row { border-top: solid 1px #e9e9e9; } /* line 268, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row.ui-sortable-helper { outline: dashed 2px #e9e9e9 !important; } /* line 272, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row:before { content: counter(el); display: block; top: 0; right: 0; position: absolute; width: 35px; height: 100%; line-height: 35px; cursor: move; color: #757575; text-align: center; border-left: solid 1px #e9e9e9; } /* line 289, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-row.cmb-repeat-row .cmb-td { margin: 0; padding: 0; } /* line 296, sass/partials/_main_wrap.scss */ .cmb-repeat-table + .cmb-add-row { margin: 0; } /* line 299, sass/partials/_main_wrap.scss */ .cmb-repeat-table + .cmb-add-row:before { content: ''; width: 1px; height: 1.6em; display: block; margin-right: 17px; background-color: gainsboro; } /* line 309, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-remove-row { top: 7px; left: 7px; position: absolute; width: auto; margin-right: 0; padding: 0 !important; display: none; } /* line 320, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-remove-row > .cmb-remove-row-button { font-size: 20px; text-indent: -1000px; overflow: hidden; position: relative; height: auto; line-height: 1; padding: 0 10px 0; } /* line 331, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-remove-row > .cmb-remove-row-button:before { content: ""; font-family: 'Dashicons'; speak: none; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; margin: 0; text-indent: 0; position: absolute; top: 0; right: 0; width: 100%; height: 100%; text-align: center; line-height: 1.3; } /* line 338, sass/partials/_main_wrap.scss */ .cmb-repeat-table .cmb-repeat-row:hover .cmb-remove-row { display: block; } /* line 346, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-th { padding: 5px; } /* line 350, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-title { background-color: #e9e9e9; padding: 8px 2.2em 8px 12px; margin: 0 -1em; min-height: 1.5em; font-size: 14px; line-height: 1.4; } /* line 358, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-title h4 { border: 0; margin: 0; font-size: 1.2em; font-weight: 500; padding: 0.5em 0.75em; } /* line 366, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-title .cmb-th { display: block; width: 100%; } /* line 372, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-group-description .cmb-th { font-size: 1.2em; display: block; float: none; padding-bottom: 1em; text-align: right; width: 100%; } /* line 27, sass/partials/_mixins.scss */ .cmb-repeatable-group .cmb-group-description .cmb-th label { display: block; margin-top: 0; margin-bottom: 0.5em; } /* line 376, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-shift-rows { margin-left: 1em; } /* line 379, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-up-alt2 { margin-top: .15em; } /* line 383, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-down-alt2 { margin-top: .2em; } /* line 388, sass/partials/_main_wrap.scss */ .cmb-repeatable-group .cmb2-upload-button { float: left; } /* line 394, sass/partials/_main_wrap.scss */ p.cmb2-metabox-description { color: #666; letter-spacing: 0.01em; margin: 0; padding-top: .5em; } /* line 401, sass/partials/_main_wrap.scss */ span.cmb2-metabox-description { color: #666; letter-spacing: 0.01em; } /* line 406, sass/partials/_main_wrap.scss */ .cmb2-metabox-title { margin: 0 0 5px 0; padding: 5px 0 0 0; font-size: 14px; } /* line 412, sass/partials/_main_wrap.scss */ .cmb-inline ul { padding: 4px 0 0 0; } /* line 416, sass/partials/_main_wrap.scss */ .cmb-inline li { display: inline-block; padding-left: 18px; } /* line 421, sass/partials/_main_wrap.scss */ .cmb-type-textarea-code pre { margin: 0; } /* line 427, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status { clear: none; display: inline-block; vertical-align: middle; margin-left: 10px; width: auto; } /* line 434, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status img { max-width: 350px; height: auto; } /* line 440, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status img, .cmb2-media-status .embed-status { background: #eee; border: 5px solid #ffffff; outline: 1px solid #e9e9e9; box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.3), inset 0 0 0 1px rgba(0, 0, 0, 0.05); background-image: linear-gradient(45deg, #d0d0d0 25%, transparent 25%, transparent 75%, #d0d0d0 75%, #d0d0d0), linear-gradient(45deg, #d0d0d0 25%, transparent 25%, transparent 75%, #d0d0d0 75%, #d0d0d0); background-position: 0 0, 10px 10px; background-size: 20px 20px; border-radius: 2px; -moz-border-radius: 2px; margin: 15px 0 0 0; } /* line 454, sass/partials/_main_wrap.scss */ .cmb2-media-status .embed-status { float: right; max-width: 800px; } /* line 459, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status, .cmb2-media-status .embed-status { position: relative; } /* line 462, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status .cmb2-remove-file-button, .cmb2-media-status .embed-status .cmb2-remove-file-button { background: url(../images/ico-delete.png); height: 16px; right: -5px; position: absolute; text-indent: -9999px; top: -5px; width: 16px; } /* line 476, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status .cmb2-remove-file-button { top: 10px; } /* line 481, sass/partials/_main_wrap.scss */ .cmb2-media-status .img-status img, .cmb2-media-status .file-status > span { cursor: pointer; } /* line 486, sass/partials/_main_wrap.scss */ .cmb2-media-status.cmb-attach-list .img-status img, .cmb2-media-status.cmb-attach-list .file-status > span { cursor: move; } /* line 493, sass/partials/_main_wrap.scss */ .cmb-type-file-list .cmb2-media-status .img-status { clear: none; vertical-align: middle; width: auto; margin-left: 10px; margin-bottom: 10px; margin-top: 0; } /* line 502, sass/partials/_main_wrap.scss */ .cmb-attach-list li { clear: both; display: inline-block; width: 100%; margin-top: 5px; margin-bottom: 10px; } /* line 508, sass/partials/_main_wrap.scss */ .cmb-attach-list li img { float: right; margin-left: 10px; } /* line 514, sass/partials/_main_wrap.scss */ .cmb2-remove-wrapper { margin: 0; } /* line 518, sass/partials/_main_wrap.scss */ .child-cmb2 .cmb-th { text-align: right; } /* line 522, sass/partials/_main_wrap.scss */ .cmb2-indented-hierarchy { padding-right: 1.5em; } @media (max-width: 450px) { /* line 527, sass/partials/_main_wrap.scss */ .cmb-th, .cmb-td, .cmb-th + .cmb-td { display: block; float: none; width: 100%; } } /*-------------------------------------------------------------- * Post Metaboxes --------------------------------------------------------------*/ /* line 5, sass/partials/_post_metaboxes.scss */ #poststuff .cmb-group-title { margin-right: -1em; margin-left: -1em; min-height: 1.5em; } /* line 11, sass/partials/_post_metaboxes.scss */ #poststuff .repeatable .cmb-group-title { padding-right: 2.2em; } /* line 17, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb2-wrap, .cmb-type-group .cmb2-wrap { margin: 0; } /* line 20, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb2-wrap > .cmb-field-list > .cmb-row, .cmb-type-group .cmb2-wrap > .cmb-field-list > .cmb-row { padding: 1.8em 0; } /* line 26, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb2-wrap input[type=text].cmb2-oembed, .cmb-type-group .cmb2-wrap input[type=text].cmb2-oembed { width: 100%; } /* line 32, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row, .cmb-type-group .cmb-row { padding: 0 0 1.8em; margin: 0 0 0.8em; } /* line 36, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row .cmbhandle, .cmb-type-group .cmb-row .cmbhandle { left: -1em; position: relative; color: #222222; } /* line 43, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-repeatable-grouping, .cmb-type-group .cmb-repeatable-grouping { padding: 0 1em; max-width: 100%; min-width: 1px !important; } /* line 49, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-repeatable-group > .cmb-row, .cmb-type-group .cmb-repeatable-group > .cmb-row { padding-bottom: 0; } /* line 53, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-th, .cmb-type-group .cmb-th { width: 18%; padding: 0 0 0 2%; } /* line 59, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-td, .cmb-type-group .cmb-td { margin-bottom: 0; padding: 0; line-height: 1.3; } /* line 65, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-th + .cmb-td, .cmb-type-group .cmb-th + .cmb-td { width: 80%; float: left; } /* line 70, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row:not(:last-of-type), .cmb2-postbox .cmb-repeatable-group:not(:last-of-type), .cmb-type-group .cmb-row:not(:last-of-type), .cmb-type-group .cmb-repeatable-group:not(:last-of-type) { border-bottom: 1px solid #e9e9e9; } @media (max-width: 450px) { /* line 70, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-row:not(:last-of-type), .cmb2-postbox .cmb-repeatable-group:not(:last-of-type), .cmb-type-group .cmb-row:not(:last-of-type), .cmb-type-group .cmb-repeatable-group:not(:last-of-type) { border-bottom: 0; } } /* line 79, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .cmb-repeat-group-field, .cmb2-postbox .cmb-remove-field-row, .cmb-type-group .cmb-repeat-group-field, .cmb-type-group .cmb-remove-field-row { padding-top: 1.8em; } /* line 85, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .button-secondary .dashicons, .cmb-type-group .button-secondary .dashicons { line-height: 1.3; } /* line 89, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .button-secondary.move-up .dashicons, .cmb2-postbox .button-secondary.move-down .dashicons, .cmb-type-group .button-secondary.move-up .dashicons, .cmb-type-group .button-secondary.move-down .dashicons { line-height: 1.1; } /* line 94, sass/partials/_post_metaboxes.scss */ .cmb2-postbox .button-secondary.cmb-add-group-row .dashicons, .cmb-type-group .button-secondary.cmb-add-group-row .dashicons { line-height: 1.5; } /*-------------------------------------------------------------- * Context Metaboxes --------------------------------------------------------------*/ /* Metabox collapse arrow indicators */ /* line 8, sass/partials/_context_metaboxes.scss */ .js .cmb2-postbox.context-box .handlediv { text-align: center; } /* line 13, sass/partials/_context_metaboxes.scss */ .js .cmb2-postbox.context-box .toggle-indicator:before { content: "\f142"; display: inline-block; font: normal 20px/1 dashicons; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-decoration: none !important; } /* line 26, sass/partials/_context_metaboxes.scss */ .js .cmb2-postbox.context-box.closed .toggle-indicator:before { content: "\f140"; } /* line 34, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box { margin-bottom: 10px; } /* line 38, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-before_permalink-box { margin-top: 10px; } /* line 42, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-after_title-box { margin-top: 10px; } /* line 46, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-after_editor-box { margin-top: 20px; margin-bottom: 0; } /* line 51, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-form_top-box { margin-top: 10px; } /* line 55, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box.context-form_top-box .hndle { font-size: 14px; padding: 8px 12px; margin: 0; line-height: 1.4; } /* line 63, sass/partials/_context_metaboxes.scss */ .cmb2-postbox.context-box .hndle { cursor: auto; } /* line 68, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap { margin-top: 10px; } /* line 72, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap.cmb2-context-wrap-form_top { margin-left: 300px; width: auto; } /* line 79, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap.cmb2-context-wrap-no-title .cmb2-metabox { padding: 10px; } /* line 84, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-th { padding: 0 0 0 2%; width: 18%; } /* line 89, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-td { width: 80%; padding: 0; } /* line 94, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-row { margin-bottom: 10px; } /* line 97, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap .cmb-row:last-of-type { margin-bottom: 0; } /* one column on the post write/edit screen */ @media only screen and (max-width: 850px) { /* line 107, sass/partials/_context_metaboxes.scss */ .cmb2-context-wrap.cmb2-context-wrap-form_top { margin-left: 0; } } /*-------------------------------------------------------------- * Options page --------------------------------------------------------------*/ /* line 5, sass/partials/_options-page.scss */ .cmb2-options-page { max-width: 1200px; } /* line 8, sass/partials/_options-page.scss */ .cmb2-options-page.wrap > h2 { margin-bottom: 1em; } /* line 12, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row { padding: 1em; margin-top: -1px; background: #ffffff; border: 1px solid #e9e9e9; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05); } /* line 19, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row > .cmb-th { padding: 0; font-weight: initial; } /* line 24, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row > .cmb-th + .cmb-td { float: none; padding: 0 1em 0 0; margin-right: 200px; } @media (max-width: 450px) { /* line 24, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-metabox > .cmb-row > .cmb-th + .cmb-td { padding: 0; margin-right: 0; } } /* line 37, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-wrap .cmb-type-title { margin-top: 1em; padding: 0.6em 1em; background-color: #fafafa; } /* line 42, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-title { font-size: 12px; margin-top: 0; margin-bottom: 0; text-transform: uppercase; } /* line 49, sass/partials/_options-page.scss */ .cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-description { padding-top: 0.25em; } /* line 55, sass/partials/_options-page.scss */ .cmb2-options-page .cmb-repeatable-group .cmb-group-description .cmb-th { padding: 0 0 0.8em 0; } /* line 59, sass/partials/_options-page.scss */ .cmb2-options-page .cmb-repeatable-group .cmb-group-name { font-size: 16px; margin-top: 0; margin-bottom: 0; } /* line 65, sass/partials/_options-page.scss */ .cmb2-options-page .cmb-repeatable-group .cmb-th > .cmb2-metabox-description { font-weight: 400; padding-bottom: 0 !important; } /*-------------------------------------------------------------- * New-Term Page --------------------------------------------------------------*/ /* line 6, sass/partials/_new_term.scss */ #addtag .cmb-th { float: none; width: auto; padding: 20px 0 0; } /* line 12, sass/partials/_new_term.scss */ #addtag .cmb-td { padding: 0; } /* line 16, sass/partials/_new_term.scss */ #addtag .cmb-th + .cmb-td { float: none; } /* line 20, sass/partials/_new_term.scss */ #addtag select { max-width: 100%; } /* line 24, sass/partials/_new_term.scss */ #addtag .cmb2-metabox { padding-bottom: 20px; } /* line 28, sass/partials/_new_term.scss */ #addtag .cmb-row li label { display: inline; } /*-------------------------------------------------------------- * Misc. --------------------------------------------------------------*/ /* line 5, sass/partials/_misc.scss */ #poststuff .cmb-repeatable-group h2 { margin: 0; } /* line 12, sass/partials/_misc.scss */ .edit-tags-php .cmb2-metabox-title, .profile-php .cmb2-metabox-title, .user-edit-php .cmb2-metabox-title { font-size: 1.4em; } /* line 18, sass/partials/_misc.scss */ .cmb2-postbox .cmb-spinner, .cmb2-no-box-wrap .cmb-spinner { float: right; display: none; } /* line 24, sass/partials/_misc.scss */ .cmb-spinner { display: none; } /* line 26, sass/partials/_misc.scss */ .cmb-spinner.is-active { display: block; } /*-------------------------------------------------------------- * Sidebar Placement Adjustments --------------------------------------------------------------*/ /* line 10, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap > .cmb-field-list > .cmb-row, #side-sortables .cmb2-wrap > .cmb-field-list > .cmb-row { padding: 1.4em 0; } /* line 16, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input[type=text]:not(.wp-color-picker), #side-sortables .cmb2-wrap input[type=text]:not(.wp-color-picker) { width: 100%; } /* line 20, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input + input:not(.wp-picker-clear), .inner-sidebar .cmb2-wrap input + select, #side-sortables .cmb2-wrap input + input:not(.wp-picker-clear), #side-sortables .cmb2-wrap input + select { margin-right: 0; margin-top: 1em; display: block; } /* line 26, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input.cmb2-text-money, #side-sortables .cmb2-wrap input.cmb2-text-money { max-width: 70%; } /* line 28, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap input.cmb2-text-money + .cmb2-metabox-description, #side-sortables .cmb2-wrap input.cmb2-text-money + .cmb2-metabox-description { display: block; } /* line 34, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-wrap label, #side-sortables .cmb2-wrap label { display: block; font-weight: 700; padding: 0 0 5px; } /* line 42, sass/partials/_sidebar_placements.scss */ .inner-sidebar textarea, #side-sortables textarea { max-width: 99%; } /* line 46, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-repeatable-group, #side-sortables .cmb-repeatable-group { border-bottom: 1px solid #e9e9e9; } /* line 50, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-type-group > .cmb-td > .cmb-repeatable-group, #side-sortables .cmb-type-group > .cmb-td > .cmb-repeatable-group { border-bottom: 0; margin-bottom: -1.4em; } /* line 55, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-th, .inner-sidebar .cmb-td:not(.cmb-remove-row), .inner-sidebar .cmb-th + .cmb-td, #side-sortables .cmb-th, #side-sortables .cmb-td:not(.cmb-remove-row), #side-sortables .cmb-th + .cmb-td { width: 100%; display: block; float: none; } /* line 63, sass/partials/_sidebar_placements.scss */ .inner-sidebar .closed .inside, #side-sortables .closed .inside { display: none; } /* line 67, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-th, #side-sortables .cmb-th { display: block; float: none; padding-bottom: 1em; text-align: right; width: 100%; padding-right: 0; padding-left: 0; } /* line 27, sass/partials/_mixins.scss */ .inner-sidebar .cmb-th label, #side-sortables .cmb-th label { display: block; margin-top: 0; margin-bottom: 0.5em; } /* line 14, sass/partials/_mixins.scss */ .inner-sidebar .cmb-th label, #side-sortables .cmb-th label { font-size: 14px; line-height: 1.4em; } /* line 74, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-group-description .cmb-th, #side-sortables .cmb-group-description .cmb-th { padding-top: 0; } /* line 77, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-group-description .cmb2-metabox-description, #side-sortables .cmb-group-description .cmb2-metabox-description { padding: 0; } /* line 84, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-group-title .cmb-th, #side-sortables .cmb-group-title .cmb-th { padding: 0; } /* line 90, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-repeatable-grouping + .cmb-repeatable-grouping, #side-sortables .cmb-repeatable-grouping + .cmb-repeatable-grouping { margin-top: 1em; } /* line 99, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-media-status .img-status img, .inner-sidebar .cmb2-media-status .embed-status img, #side-sortables .cmb2-media-status .img-status img, #side-sortables .cmb2-media-status .embed-status img { max-width: 90%; height: auto; } /* line 107, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-list label, #side-sortables .cmb2-list label { display: inline; font-weight: normal; } /* line 112, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-metabox-description, #side-sortables .cmb2-metabox-description { display: block; padding: 7px 0 0; } /* line 119, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-type-checkbox .cmb-td label, .inner-sidebar .cmb-type-checkbox .cmb2-metabox-description, #side-sortables .cmb-type-checkbox .cmb-td label, #side-sortables .cmb-type-checkbox .cmb2-metabox-description { font-weight: normal; display: inline; } /* line 126, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-row .cmb2-metabox-description, #side-sortables .cmb-row .cmb2-metabox-description { padding-bottom: 1.8em; } /* line 130, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-metabox-title, #side-sortables .cmb2-metabox-title { font-size: 1.2em; font-style: italic; } /* line 135, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb-remove-row, #side-sortables .cmb-remove-row { clear: both; padding-top: 12px; padding-bottom: 0; } /* line 141, sass/partials/_sidebar_placements.scss */ .inner-sidebar .cmb2-upload-button, #side-sortables .cmb2-upload-button { clear: both; margin-top: 12px; } /*-------------------------------------------------------------- * Collapsible UI --------------------------------------------------------------*/ /* line 6, sass/partials/_collapsible_ui.scss */ .cmb2-metabox .cmbhandle { color: #757575; float: left; width: 27px; height: 30px; cursor: pointer; left: -1em; position: relative; } /* line 14, sass/partials/_collapsible_ui.scss */ .cmb2-metabox .cmbhandle:before { content: '\f142'; left: 12px; font: normal 20px/1 'dashicons'; speak: none; display: inline-block; padding: 8px 10px; top: 0; position: relative; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-decoration: none !important; } /* line 31, sass/partials/_collapsible_ui.scss */ .cmb2-metabox .postbox.closed .cmbhandle:before { content: '\f140'; } /* line 37, sass/partials/_collapsible_ui.scss */ .cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row { -webkit-appearance: none !important; background: none !important; border: none !important; position: absolute; right: 0; top: .5em; line-height: 1em; padding: 2px 6px 3px; opacity: .5; } /* line 47, sass/partials/_collapsible_ui.scss */ .cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]) { cursor: pointer; color: #a00; opacity: 1; } /* line 51, sass/partials/_collapsible_ui.scss */ .cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]):hover { color: #f00; } /* * jQuery UI CSS Framework 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Theming/API * * WordPress Styles adopted from "jQuery UI Datepicker CSS for WordPress" * https://github.com/stuttter/wp-datepicker-styling * */ /* line 15, sass/partials/_jquery_ui.scss */ * html .cmb2-element.ui-helper-clearfix { height: 1%; } /* line 24, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker, .cmb2-element .ui-datepicker { padding: 0; margin: 0; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; background-color: #fff; border: 1px solid #dfdfdf; border-top: none; -webkit-box-shadow: 0 3px 6px rgba(0, 0, 0, 0.075); box-shadow: 0 3px 6px rgba(0, 0, 0, 0.075); min-width: 17em; width: auto; /* Default Color Scheme */ } /* line 38, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker *, .cmb2-element .ui-datepicker * { padding: 0; font-family: "Open Sans", sans-serif; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } /* line 46, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker table, .cmb2-element .ui-datepicker table { font-size: 13px; margin: 0; border: none; border-collapse: collapse; } /* line 53, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-widget-header, .cmb2-element.ui-datepicker .ui-datepicker-header, .cmb2-element .ui-datepicker .ui-widget-header, .cmb2-element .ui-datepicker .ui-datepicker-header { background-image: none; border: none; color: #fff; font-weight: normal; } /* line 61, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover, .cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover { background: transparent; border-color: transparent; cursor: pointer; } /* line 67, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-title, .cmb2-element .ui-datepicker .ui-datepicker-title { margin: 0; padding: 10px 0; color: #fff; font-size: 14px; line-height: 14px; text-align: center; } /* line 75, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-title select, .cmb2-element .ui-datepicker .ui-datepicker-title select { margin-top: -8px; margin-bottom: -8px; } /* line 81, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev, .cmb2-element.ui-datepicker .ui-datepicker-next, .cmb2-element .ui-datepicker .ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-datepicker-next { position: relative; top: 0; height: 34px; width: 34px; } /* line 89, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-prev, .cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-next, .cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-next { border: none; } /* line 94, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev, .cmb2-element.ui-datepicker .ui-datepicker-prev-hover, .cmb2-element .ui-datepicker .ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-datepicker-prev-hover { right: 0; } /* line 99, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next, .cmb2-element.ui-datepicker .ui-datepicker-next-hover, .cmb2-element .ui-datepicker .ui-datepicker-next, .cmb2-element .ui-datepicker .ui-datepicker-next-hover { left: 0; } /* line 104, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next span, .cmb2-element.ui-datepicker .ui-datepicker-prev span, .cmb2-element .ui-datepicker .ui-datepicker-next span, .cmb2-element .ui-datepicker .ui-datepicker-prev span { display: none; } /* line 109, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev, .cmb2-element .ui-datepicker .ui-datepicker-prev { float: right; } /* line 113, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next, .cmb2-element .ui-datepicker .ui-datepicker-next { float: left; } /* line 117, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev:before, .cmb2-element.ui-datepicker .ui-datepicker-next:before, .cmb2-element .ui-datepicker .ui-datepicker-prev:before, .cmb2-element .ui-datepicker .ui-datepicker-next:before { font: normal 20px/34px 'dashicons'; padding-right: 7px; color: #fff; speak: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; width: 34px; height: 34px; } /* line 129, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev:before, .cmb2-element .ui-datepicker .ui-datepicker-prev:before { content: '\f341'; } /* line 133, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-next:before, .cmb2-element .ui-datepicker .ui-datepicker-next:before { content: '\f345'; } /* line 137, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-datepicker-prev-hover:before, .cmb2-element.ui-datepicker .ui-datepicker-next-hover:before, .cmb2-element .ui-datepicker .ui-datepicker-prev-hover:before, .cmb2-element .ui-datepicker .ui-datepicker-next-hover:before { opacity: 0.7; } /* line 142, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker select.ui-datepicker-month, .cmb2-element.ui-datepicker select.ui-datepicker-year, .cmb2-element .ui-datepicker select.ui-datepicker-month, .cmb2-element .ui-datepicker select.ui-datepicker-year { width: 33%; background: transparent; border-color: transparent; box-shadow: none; color: #fff; } /* line 149, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker select.ui-datepicker-month option, .cmb2-element.ui-datepicker select.ui-datepicker-year option, .cmb2-element .ui-datepicker select.ui-datepicker-month option, .cmb2-element .ui-datepicker select.ui-datepicker-year option { color: #333; } /* line 154, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker thead, .cmb2-element .ui-datepicker thead { color: #fff; font-weight: 600; } /* line 157, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker thead th, .cmb2-element .ui-datepicker thead th { font-weight: normal; } /* line 162, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker th, .cmb2-element .ui-datepicker th { padding: 10px; } /* line 166, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td, .cmb2-element .ui-datepicker td { padding: 0; border: 1px solid #f4f4f4; } /* line 171, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-other-month, .cmb2-element .ui-datepicker td.ui-datepicker-other-month { border: transparent; } /* line 175, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-week-end, .cmb2-element .ui-datepicker td.ui-datepicker-week-end { background-color: #f4f4f4; border: 1px solid #f4f4f4; } /* line 178, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today, .cmb2-element .ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today { -webkit-box-shadow: inset 0px 0px 1px 0px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset 0px 0px 1px 0px rgba(0, 0, 0, 0.1); box-shadow: inset 0px 0px 1px 0px rgba(0, 0, 0, 0.1); } /* line 185, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-today, .cmb2-element .ui-datepicker td.ui-datepicker-today { background-color: #f0f0c0; } /* line 189, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-datepicker-current-day, .cmb2-element .ui-datepicker td.ui-datepicker-current-day { background: #bbdd88; } /* line 193, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td .ui-state-default, .cmb2-element .ui-datepicker td .ui-state-default { background: transparent; border: none; text-align: center; text-decoration: none; width: auto; display: block; padding: 5px 10px; font-weight: normal; color: #444; } /* line 205, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td.ui-state-disabled .ui-state-default, .cmb2-element .ui-datepicker td.ui-state-disabled .ui-state-default { opacity: 0.5; } /* line 210, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-widget-header, .cmb2-element.ui-datepicker .ui-datepicker-header, .cmb2-element .ui-datepicker .ui-widget-header, .cmb2-element .ui-datepicker .ui-datepicker-header { background: #00a0d2; } /* line 215, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker thead, .cmb2-element .ui-datepicker thead { background: #32373c; } /* line 219, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker td .ui-state-hover, .cmb2-element.ui-datepicker td .ui-state-active, .cmb2-element .ui-datepicker td .ui-state-hover, .cmb2-element .ui-datepicker td .ui-state-active { background: #0073aa; color: #fff; } /* line 224, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div, .cmb2-element .ui-datepicker .ui-timepicker-div { font-size: 14px; } /* line 226, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl, .cmb2-element .ui-datepicker .ui-timepicker-div dl { text-align: right; padding: 0 .6em; } /* line 229, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl dt, .cmb2-element .ui-datepicker .ui-timepicker-div dl dt { float: right; clear: right; padding: 0 5px 0 0; } /* line 234, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl dd, .cmb2-element .ui-datepicker .ui-timepicker-div dl dd { margin: 0 40% 10px 10px; } /* line 236, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div dl dd select, .cmb2-element .ui-datepicker .ui-timepicker-div dl dd select { width: 100%; } /* line 242, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane, .cmb2-element .ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane { padding: .6em; text-align: right; } /* line 246, sass/partials/_jquery_ui.scss */ .cmb2-element.ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-primary, .cmb2-element.ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-secondary, .cmb2-element .ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-primary, .cmb2-element .ui-datepicker .ui-timepicker-div + .ui-datepicker-buttonpane .button-secondary { padding: 0 10px 1px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; margin: 0 .4em .4em .6em; } /* line 260, sass/partials/_jquery_ui.scss */ .admin-color-fresh .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-fresh .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-fresh .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-fresh .cmb2-element .ui-datepicker .ui-datepicker-header { background: #00a0d2; } /* line 265, sass/partials/_jquery_ui.scss */ .admin-color-fresh .cmb2-element.ui-datepicker thead, .admin-color-fresh .cmb2-element .ui-datepicker thead { background: #32373c; } /* line 269, sass/partials/_jquery_ui.scss */ .admin-color-fresh .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-fresh .cmb2-element .ui-datepicker td .ui-state-hover { background: #0073aa; color: #fff; } /* line 277, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-blue .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-blue .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-blue .cmb2-element .ui-datepicker .ui-datepicker-header { background: #52accc; } /* line 282, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker thead, .admin-color-blue .cmb2-element .ui-datepicker thead { background: #4796b3; } /* line 291, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-blue .cmb2-element.ui-datepicker td .ui-state-active, .admin-color-blue .cmb2-element .ui-datepicker td .ui-state-hover, .admin-color-blue .cmb2-element .ui-datepicker td .ui-state-active { background: #096484; color: #fff; } /* line 296, sass/partials/_jquery_ui.scss */ .admin-color-blue .cmb2-element.ui-datepicker td.ui-datepicker-today, .admin-color-blue .cmb2-element .ui-datepicker td.ui-datepicker-today { background: #eee; } /* line 305, sass/partials/_jquery_ui.scss */ .admin-color-coffee .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-coffee .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-coffee .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-coffee .cmb2-element .ui-datepicker .ui-datepicker-header { background: #59524c; } /* line 310, sass/partials/_jquery_ui.scss */ .admin-color-coffee .cmb2-element.ui-datepicker thead, .admin-color-coffee .cmb2-element .ui-datepicker thead { background: #46403c; } /* line 314, sass/partials/_jquery_ui.scss */ .admin-color-coffee .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-coffee .cmb2-element .ui-datepicker td .ui-state-hover { background: #c7a589; color: #fff; } /* line 322, sass/partials/_jquery_ui.scss */ .admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-datepicker-header { background: #523f6d; } /* line 327, sass/partials/_jquery_ui.scss */ .admin-color-ectoplasm .cmb2-element.ui-datepicker thead, .admin-color-ectoplasm .cmb2-element .ui-datepicker thead { background: #413256; } /* line 331, sass/partials/_jquery_ui.scss */ .admin-color-ectoplasm .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-ectoplasm .cmb2-element .ui-datepicker td .ui-state-hover { background: #a3b745; color: #fff; } /* line 339, sass/partials/_jquery_ui.scss */ .admin-color-midnight .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-midnight .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-midnight .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-midnight .cmb2-element .ui-datepicker .ui-datepicker-header { background: #363b3f; } /* line 344, sass/partials/_jquery_ui.scss */ .admin-color-midnight .cmb2-element.ui-datepicker thead, .admin-color-midnight .cmb2-element .ui-datepicker thead { background: #26292c; } /* line 348, sass/partials/_jquery_ui.scss */ .admin-color-midnight .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-midnight .cmb2-element .ui-datepicker td .ui-state-hover { background: #e14d43; color: #fff; } /* line 356, sass/partials/_jquery_ui.scss */ .admin-color-ocean .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-ocean .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-ocean .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-ocean .cmb2-element .ui-datepicker .ui-datepicker-header { background: #738e96; } /* line 361, sass/partials/_jquery_ui.scss */ .admin-color-ocean .cmb2-element.ui-datepicker thead, .admin-color-ocean .cmb2-element .ui-datepicker thead { background: #627c83; } /* line 365, sass/partials/_jquery_ui.scss */ .admin-color-ocean .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-ocean .cmb2-element .ui-datepicker td .ui-state-hover { background: #9ebaa0; color: #fff; } /* line 373, sass/partials/_jquery_ui.scss */ .admin-color-sunrise .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover, .admin-color-sunrise .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header, .admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover { background: #cf4944; } /* line 379, sass/partials/_jquery_ui.scss */ .admin-color-sunrise .cmb2-element.ui-datepicker th, .admin-color-sunrise .cmb2-element .ui-datepicker th { border-color: #be3631; background: #be3631; } /* line 384, sass/partials/_jquery_ui.scss */ .admin-color-sunrise .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-sunrise .cmb2-element .ui-datepicker td .ui-state-hover { background: #dd823b; color: #fff; } /* line 392, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-light .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-header { background: #e5e5e5; } /* line 397, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-month, .admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-year, .admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-month, .admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-year { color: #555; } /* line 402, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker thead, .admin-color-light .cmb2-element .ui-datepicker thead { background: #888; } /* line 406, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-title, .admin-color-light .cmb2-element.ui-datepicker td .ui-state-default, .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-prev:before, .admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-next:before, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-title, .admin-color-light .cmb2-element .ui-datepicker td .ui-state-default, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-prev:before, .admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-next:before { color: #555; } /* line 414, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-light .cmb2-element.ui-datepicker td .ui-state-active, .admin-color-light .cmb2-element .ui-datepicker td .ui-state-hover, .admin-color-light .cmb2-element .ui-datepicker td .ui-state-active { background: #ccc; } /* line 418, sass/partials/_jquery_ui.scss */ .admin-color-light .cmb2-element.ui-datepicker td.ui-datepicker-today, .admin-color-light .cmb2-element .ui-datepicker td.ui-datepicker-today { background: #eee; } /* line 426, sass/partials/_jquery_ui.scss */ .admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-datepicker-header { background: #56b274; } /* line 431, sass/partials/_jquery_ui.scss */ .admin-color-bbp-evergreen .cmb2-element.ui-datepicker thead, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker thead { background: #36533f; } /* line 435, sass/partials/_jquery_ui.scss */ .admin-color-bbp-evergreen .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-bbp-evergreen .cmb2-element .ui-datepicker td .ui-state-hover { background: #446950; color: #fff; } /* line 443, sass/partials/_jquery_ui.scss */ .admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-widget-header, .admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-datepicker-header, .admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-widget-header, .admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-datepicker-header { background: #4ca26a; } /* line 448, sass/partials/_jquery_ui.scss */ .admin-color-bbp-mint .cmb2-element.ui-datepicker thead, .admin-color-bbp-mint .cmb2-element .ui-datepicker thead { background: #4f6d59; } /* line 452, sass/partials/_jquery_ui.scss */ .admin-color-bbp-mint .cmb2-element.ui-datepicker td .ui-state-hover, .admin-color-bbp-mint .cmb2-element .ui-datepicker td .ui-state-hover { background: #5fb37c; color: #fff; } /*-------------------------------------------------------------- * Character counter --------------------------------------------------------------*/ /* line 5, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap { margin: .5em 0 1em; } /* line 8, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap input[type="text"] { font-size: 12px; width: 25px; } /* line 14, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap.cmb2-max-exceeded input[type="text"] { border-color: #a00 !important; } /* line 17, sass/partials/_char_counter.scss */ .cmb2-char-counter-wrap.cmb2-max-exceeded .cmb2-char-max-msg { display: inline-block; } /* line 23, sass/partials/_char_counter.scss */ .cmb2-char-max-msg { color: #a00; display: none; font-weight: 600; margin-right: 1em; } /*# sourceMappingURL=cmb2.css.map */ cmb2/cmb2/css/cmb2-rtl.min.css 0000644 00000100265 15151523432 0011725 0 ustar 00 @charset "UTF-8";.cmb2-wrap{margin:0}.cmb2-wrap input,.cmb2-wrap textarea{max-width:100%}.cmb2-wrap input[type=text].cmb2-oembed{width:100%}.cmb2-wrap textarea{width:500px;padding:8px}.cmb2-wrap textarea.cmb2-textarea-code{font-family:"Courier 10 Pitch",Courier,monospace;line-height:16px}.cmb2-wrap input.cmb2-text-small,.cmb2-wrap input.cmb2-timepicker{width:100px}.cmb2-wrap input.cmb2-text-money{width:90px}.cmb2-wrap input.cmb2-text-medium{width:230px}.cmb2-wrap input.cmb2-upload-file{width:65%}.cmb2-wrap input.ed_button{padding:2px 4px}.cmb2-wrap input:not([type=hidden])+.button-secondary,.cmb2-wrap input:not([type=hidden])+input,.cmb2-wrap input:not([type=hidden])+select{margin-right:20px}.cmb2-wrap ul{margin:0}.cmb2-wrap li{font-size:14px;line-height:16px;margin:1px 0 5px 0}.cmb2-wrap select{font-size:14px;margin-top:3px}.cmb2-wrap input:focus,.cmb2-wrap textarea:focus{background:#fffff8}.cmb2-wrap input[type=radio]{margin:0 0 0 5px;padding:0}.cmb2-wrap input[type=checkbox]{margin:0 0 0 5px;padding:0}.cmb2-wrap .button-secondary,.cmb2-wrap button{white-space:nowrap}.cmb2-wrap .mceLayout{border:1px solid #e9e9e9!important}.cmb2-wrap .mceIframeContainer{background:#fff}.cmb2-wrap .meta_mce{width:97%}.cmb2-wrap .meta_mce textarea{width:100%}.cmb2-wrap .cmb-multicheck-toggle{margin-top:-1em}.cmb2-wrap .wp-picker-clear.button,.cmb2-wrap .wp-picker-default.button{margin-right:6px;padding:2px 8px}.cmb2-wrap .cmb-row{margin:0}.cmb2-wrap .cmb-row:after{content:'';clear:both;display:block;width:100%}.cmb2-wrap .cmb-row.cmb-repeat .cmb2-metabox-description{padding-top:0;padding-bottom:1em}body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type=radio]::before{margin:.1875rem}@media screen and (max-width:782px){body.block-editor-page.branch-5-3 .cmb2-wrap .cmb-row .cmb2-radio-list input[type=radio]::before{margin:.4375rem}}.cmb2-metabox{clear:both;margin:0}.cmb2-metabox .cmb-field-list>.cmb-row:first-of-type>.cmb-td,.cmb2-metabox .cmb-field-list>.cmb-row:first-of-type>.cmb-th,.cmb2-metabox>.cmb-row:first-of-type>.cmb-td,.cmb2-metabox>.cmb-row:first-of-type>.cmb-th{border:0}.cmb-add-row{margin:1.8em 0 0}.cmb-nested .cmb-td,.cmb-repeatable-group .cmb-th,.cmb-repeatable-group:first-of-type{border:0}.cmb-repeatable-group:last-of-type,.cmb-row:last-of-type,.cmb2-wrap .cmb-row:last-of-type{border-bottom:0}.cmb-repeatable-grouping{border:1px solid #e9e9e9;padding:0 1em}.cmb-repeatable-grouping.cmb-row{margin:0 0 .8em}.cmb-th{color:#222;float:right;font-weight:600;padding:20px 0 20px 10px;vertical-align:top;width:200px}@media (max-width:450px){.cmb-th{font-size:1.2em;display:block;float:none;padding-bottom:1em;text-align:right;width:100%}.cmb-th label{display:block;margin-top:0;margin-bottom:.5em}}.cmb-td{line-height:1.3;max-width:100%;padding:15px 10px;vertical-align:middle}.cmb-type-title .cmb-td{padding:0}.cmb-th label{display:block;padding:5px 0}.cmb-th+.cmb-td{float:right}.cmb-td .cmb-td{padding-bottom:1em}.cmb-remove-row{text-align:left}.empty-row.hidden{display:none}.cmb-repeat-table{background-color:#fafafa;border:1px solid #e1e1e1}.cmb-repeat-table .cmb-row.cmb-repeat-row{position:relative;counter-increment:el;margin:0;padding:10px 50px 10px 10px;border-bottom:none!important}.cmb-repeat-table .cmb-row.cmb-repeat-row+.cmb-repeat-row{border-top:solid 1px #e9e9e9}.cmb-repeat-table .cmb-row.cmb-repeat-row.ui-sortable-helper{outline:dashed 2px #e9e9e9!important}.cmb-repeat-table .cmb-row.cmb-repeat-row:before{content:counter(el);display:block;top:0;right:0;position:absolute;width:35px;height:100%;line-height:35px;cursor:move;color:#757575;text-align:center;border-left:solid 1px #e9e9e9}.cmb-repeat-table .cmb-row.cmb-repeat-row .cmb-td{margin:0;padding:0}.cmb-repeat-table+.cmb-add-row{margin:0}.cmb-repeat-table+.cmb-add-row:before{content:'';width:1px;height:1.6em;display:block;margin-right:17px;background-color:#dcdcdc}.cmb-repeat-table .cmb-remove-row{top:7px;left:7px;position:absolute;width:auto;margin-right:0;padding:0!important;display:none}.cmb-repeat-table .cmb-remove-row>.cmb-remove-row-button{font-size:20px;text-indent:-1000px;overflow:hidden;position:relative;height:auto;line-height:1;padding:0 10px 0}.cmb-repeat-table .cmb-remove-row>.cmb-remove-row-button:before{content:"";font-family:Dashicons;speak:none;font-weight:400;font-variant:normal;text-transform:none;line-height:1;-webkit-font-smoothing:antialiased;margin:0;text-indent:0;position:absolute;top:0;right:0;width:100%;height:100%;text-align:center;line-height:1.3}.cmb-repeat-table .cmb-repeat-row:hover .cmb-remove-row{display:block}.cmb-repeatable-group .cmb-th{padding:5px}.cmb-repeatable-group .cmb-group-title{background-color:#e9e9e9;padding:8px 2.2em 8px 12px;margin:0 -1em;min-height:1.5em;font-size:14px;line-height:1.4}.cmb-repeatable-group .cmb-group-title h4{border:0;margin:0;font-size:1.2em;font-weight:500;padding:.5em .75em}.cmb-repeatable-group .cmb-group-title .cmb-th{display:block;width:100%}.cmb-repeatable-group .cmb-group-description .cmb-th{font-size:1.2em;display:block;float:none;padding-bottom:1em;text-align:right;width:100%}.cmb-repeatable-group .cmb-group-description .cmb-th label{display:block;margin-top:0;margin-bottom:.5em}.cmb-repeatable-group .cmb-shift-rows{margin-left:1em}.cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-up-alt2{margin-top:.15em}.cmb-repeatable-group .cmb-shift-rows .dashicons-arrow-down-alt2{margin-top:.2em}.cmb-repeatable-group .cmb2-upload-button{float:left}p.cmb2-metabox-description{color:#666;letter-spacing:.01em;margin:0;padding-top:.5em}span.cmb2-metabox-description{color:#666;letter-spacing:.01em}.cmb2-metabox-title{margin:0 0 5px 0;padding:5px 0 0 0;font-size:14px}.cmb-inline ul{padding:4px 0 0 0}.cmb-inline li{display:inline-block;padding-left:18px}.cmb-type-textarea-code pre{margin:0}.cmb2-media-status .img-status{clear:none;display:inline-block;vertical-align:middle;margin-left:10px;width:auto}.cmb2-media-status .img-status img{max-width:350px;height:auto}.cmb2-media-status .embed-status,.cmb2-media-status .img-status img{background:#eee;border:5px solid #fff;outline:1px solid #e9e9e9;box-shadow:inset 0 0 15px rgba(0,0,0,.3),inset 0 0 0 1px rgba(0,0,0,.05);background-image:linear-gradient(45deg,#d0d0d0 25%,transparent 25%,transparent 75%,#d0d0d0 75%,#d0d0d0),linear-gradient(45deg,#d0d0d0 25%,transparent 25%,transparent 75%,#d0d0d0 75%,#d0d0d0);background-position:0 0,10px 10px;background-size:20px 20px;border-radius:2px;-moz-border-radius:2px;margin:15px 0 0 0}.cmb2-media-status .embed-status{float:right;max-width:800px}.cmb2-media-status .embed-status,.cmb2-media-status .img-status{position:relative}.cmb2-media-status .embed-status .cmb2-remove-file-button,.cmb2-media-status .img-status .cmb2-remove-file-button{background:url(../images/ico-delete.png);height:16px;right:-5px;position:absolute;text-indent:-9999px;top:-5px;width:16px}.cmb2-media-status .img-status .cmb2-remove-file-button{top:10px}.cmb2-media-status .file-status>span,.cmb2-media-status .img-status img{cursor:pointer}.cmb2-media-status.cmb-attach-list .file-status>span,.cmb2-media-status.cmb-attach-list .img-status img{cursor:move}.cmb-type-file-list .cmb2-media-status .img-status{clear:none;vertical-align:middle;width:auto;margin-left:10px;margin-bottom:10px;margin-top:0}.cmb-attach-list li{clear:both;display:inline-block;width:100%;margin-top:5px;margin-bottom:10px}.cmb-attach-list li img{float:right;margin-left:10px}.cmb2-remove-wrapper{margin:0}.child-cmb2 .cmb-th{text-align:right}.cmb2-indented-hierarchy{padding-right:1.5em}@media (max-width:450px){.cmb-td,.cmb-th,.cmb-th+.cmb-td{display:block;float:none;width:100%}}#poststuff .cmb-group-title{margin-right:-1em;margin-left:-1em;min-height:1.5em}#poststuff .repeatable .cmb-group-title{padding-right:2.2em}.cmb-type-group .cmb2-wrap,.cmb2-postbox .cmb2-wrap{margin:0}.cmb-type-group .cmb2-wrap>.cmb-field-list>.cmb-row,.cmb2-postbox .cmb2-wrap>.cmb-field-list>.cmb-row{padding:1.8em 0}.cmb-type-group .cmb2-wrap input[type=text].cmb2-oembed,.cmb2-postbox .cmb2-wrap input[type=text].cmb2-oembed{width:100%}.cmb-type-group .cmb-row,.cmb2-postbox .cmb-row{padding:0 0 1.8em;margin:0 0 .8em}.cmb-type-group .cmb-row .cmbhandle,.cmb2-postbox .cmb-row .cmbhandle{left:-1em;position:relative;color:#222}.cmb-type-group .cmb-repeatable-grouping,.cmb2-postbox .cmb-repeatable-grouping{padding:0 1em;max-width:100%;min-width:1px!important}.cmb-type-group .cmb-repeatable-group>.cmb-row,.cmb2-postbox .cmb-repeatable-group>.cmb-row{padding-bottom:0}.cmb-type-group .cmb-th,.cmb2-postbox .cmb-th{width:18%;padding:0 0 0 2%}.cmb-type-group .cmb-td,.cmb2-postbox .cmb-td{margin-bottom:0;padding:0;line-height:1.3}.cmb-type-group .cmb-th+.cmb-td,.cmb2-postbox .cmb-th+.cmb-td{width:80%;float:left}.cmb-type-group .cmb-repeatable-group:not(:last-of-type),.cmb-type-group .cmb-row:not(:last-of-type),.cmb2-postbox .cmb-repeatable-group:not(:last-of-type),.cmb2-postbox .cmb-row:not(:last-of-type){border-bottom:1px solid #e9e9e9}@media (max-width:450px){.cmb-type-group .cmb-repeatable-group:not(:last-of-type),.cmb-type-group .cmb-row:not(:last-of-type),.cmb2-postbox .cmb-repeatable-group:not(:last-of-type),.cmb2-postbox .cmb-row:not(:last-of-type){border-bottom:0}}.cmb-type-group .cmb-remove-field-row,.cmb-type-group .cmb-repeat-group-field,.cmb2-postbox .cmb-remove-field-row,.cmb2-postbox .cmb-repeat-group-field{padding-top:1.8em}.cmb-type-group .button-secondary .dashicons,.cmb2-postbox .button-secondary .dashicons{line-height:1.3}.cmb-type-group .button-secondary.move-down .dashicons,.cmb-type-group .button-secondary.move-up .dashicons,.cmb2-postbox .button-secondary.move-down .dashicons,.cmb2-postbox .button-secondary.move-up .dashicons{line-height:1.1}.cmb-type-group .button-secondary.cmb-add-group-row .dashicons,.cmb2-postbox .button-secondary.cmb-add-group-row .dashicons{line-height:1.5}.js .cmb2-postbox.context-box .handlediv{text-align:center}.js .cmb2-postbox.context-box .toggle-indicator:before{content:"\f142";display:inline-block;font:normal 20px/1 dashicons;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-decoration:none!important}.js .cmb2-postbox.context-box.closed .toggle-indicator:before{content:"\f140"}.cmb2-postbox.context-box{margin-bottom:10px}.cmb2-postbox.context-box.context-before_permalink-box{margin-top:10px}.cmb2-postbox.context-box.context-after_title-box{margin-top:10px}.cmb2-postbox.context-box.context-after_editor-box{margin-top:20px;margin-bottom:0}.cmb2-postbox.context-box.context-form_top-box{margin-top:10px}.cmb2-postbox.context-box.context-form_top-box .hndle{font-size:14px;padding:8px 12px;margin:0;line-height:1.4}.cmb2-postbox.context-box .hndle{cursor:auto}.cmb2-context-wrap{margin-top:10px}.cmb2-context-wrap.cmb2-context-wrap-form_top{margin-left:300px;width:auto}.cmb2-context-wrap.cmb2-context-wrap-no-title .cmb2-metabox{padding:10px}.cmb2-context-wrap .cmb-th{padding:0 0 0 2%;width:18%}.cmb2-context-wrap .cmb-td{width:80%;padding:0}.cmb2-context-wrap .cmb-row{margin-bottom:10px}.cmb2-context-wrap .cmb-row:last-of-type{margin-bottom:0}@media only screen and (max-width:850px){.cmb2-context-wrap.cmb2-context-wrap-form_top{margin-left:0}}.cmb2-options-page{max-width:1200px}.cmb2-options-page.wrap>h2{margin-bottom:1em}.cmb2-options-page .cmb2-metabox>.cmb-row{padding:1em;margin-top:-1px;background:#fff;border:1px solid #e9e9e9;box-shadow:0 1px 1px rgba(0,0,0,.05)}.cmb2-options-page .cmb2-metabox>.cmb-row>.cmb-th{padding:0;font-weight:initial}.cmb2-options-page .cmb2-metabox>.cmb-row>.cmb-th+.cmb-td{float:none;padding:0 1em 0 0;margin-right:200px}@media (max-width:450px){.cmb2-options-page .cmb2-metabox>.cmb-row>.cmb-th+.cmb-td{padding:0;margin-right:0}}.cmb2-options-page .cmb2-wrap .cmb-type-title{margin-top:1em;padding:.6em 1em;background-color:#fafafa}.cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-title{font-size:12px;margin-top:0;margin-bottom:0;text-transform:uppercase}.cmb2-options-page .cmb2-wrap .cmb-type-title .cmb2-metabox-description{padding-top:.25em}.cmb2-options-page .cmb-repeatable-group .cmb-group-description .cmb-th{padding:0 0 .8em 0}.cmb2-options-page .cmb-repeatable-group .cmb-group-name{font-size:16px;margin-top:0;margin-bottom:0}.cmb2-options-page .cmb-repeatable-group .cmb-th>.cmb2-metabox-description{font-weight:400;padding-bottom:0!important}#addtag .cmb-th{float:none;width:auto;padding:20px 0 0}#addtag .cmb-td{padding:0}#addtag .cmb-th+.cmb-td{float:none}#addtag select{max-width:100%}#addtag .cmb2-metabox{padding-bottom:20px}#addtag .cmb-row li label{display:inline}#poststuff .cmb-repeatable-group h2{margin:0}.edit-tags-php .cmb2-metabox-title,.profile-php .cmb2-metabox-title,.user-edit-php .cmb2-metabox-title{font-size:1.4em}.cmb2-no-box-wrap .cmb-spinner,.cmb2-postbox .cmb-spinner{float:right;display:none}.cmb-spinner{display:none}.cmb-spinner.is-active{display:block}#side-sortables .cmb2-wrap>.cmb-field-list>.cmb-row,.inner-sidebar .cmb2-wrap>.cmb-field-list>.cmb-row{padding:1.4em 0}#side-sortables .cmb2-wrap input[type=text]:not(.wp-color-picker),.inner-sidebar .cmb2-wrap input[type=text]:not(.wp-color-picker){width:100%}#side-sortables .cmb2-wrap input+input:not(.wp-picker-clear),#side-sortables .cmb2-wrap input+select,.inner-sidebar .cmb2-wrap input+input:not(.wp-picker-clear),.inner-sidebar .cmb2-wrap input+select{margin-right:0;margin-top:1em;display:block}#side-sortables .cmb2-wrap input.cmb2-text-money,.inner-sidebar .cmb2-wrap input.cmb2-text-money{max-width:70%}#side-sortables .cmb2-wrap input.cmb2-text-money+.cmb2-metabox-description,.inner-sidebar .cmb2-wrap input.cmb2-text-money+.cmb2-metabox-description{display:block}#side-sortables .cmb2-wrap label,.inner-sidebar .cmb2-wrap label{display:block;font-weight:700;padding:0 0 5px}#side-sortables textarea,.inner-sidebar textarea{max-width:99%}#side-sortables .cmb-repeatable-group,.inner-sidebar .cmb-repeatable-group{border-bottom:1px solid #e9e9e9}#side-sortables .cmb-type-group>.cmb-td>.cmb-repeatable-group,.inner-sidebar .cmb-type-group>.cmb-td>.cmb-repeatable-group{border-bottom:0;margin-bottom:-1.4em}#side-sortables .cmb-td:not(.cmb-remove-row),#side-sortables .cmb-th,#side-sortables .cmb-th+.cmb-td,.inner-sidebar .cmb-td:not(.cmb-remove-row),.inner-sidebar .cmb-th,.inner-sidebar .cmb-th+.cmb-td{width:100%;display:block;float:none}#side-sortables .closed .inside,.inner-sidebar .closed .inside{display:none}#side-sortables .cmb-th,.inner-sidebar .cmb-th{display:block;float:none;padding-bottom:1em;text-align:right;width:100%;padding-right:0;padding-left:0}#side-sortables .cmb-th label,.inner-sidebar .cmb-th label{display:block;margin-top:0;margin-bottom:.5em}#side-sortables .cmb-th label,.inner-sidebar .cmb-th label{font-size:14px;line-height:1.4em}#side-sortables .cmb-group-description .cmb-th,.inner-sidebar .cmb-group-description .cmb-th{padding-top:0}#side-sortables .cmb-group-description .cmb2-metabox-description,.inner-sidebar .cmb-group-description .cmb2-metabox-description{padding:0}#side-sortables .cmb-group-title .cmb-th,.inner-sidebar .cmb-group-title .cmb-th{padding:0}#side-sortables .cmb-repeatable-grouping+.cmb-repeatable-grouping,.inner-sidebar .cmb-repeatable-grouping+.cmb-repeatable-grouping{margin-top:1em}#side-sortables .cmb2-media-status .embed-status img,#side-sortables .cmb2-media-status .img-status img,.inner-sidebar .cmb2-media-status .embed-status img,.inner-sidebar .cmb2-media-status .img-status img{max-width:90%;height:auto}#side-sortables .cmb2-list label,.inner-sidebar .cmb2-list label{display:inline;font-weight:400}#side-sortables .cmb2-metabox-description,.inner-sidebar .cmb2-metabox-description{display:block;padding:7px 0 0}#side-sortables .cmb-type-checkbox .cmb-td label,#side-sortables .cmb-type-checkbox .cmb2-metabox-description,.inner-sidebar .cmb-type-checkbox .cmb-td label,.inner-sidebar .cmb-type-checkbox .cmb2-metabox-description{font-weight:400;display:inline}#side-sortables .cmb-row .cmb2-metabox-description,.inner-sidebar .cmb-row .cmb2-metabox-description{padding-bottom:1.8em}#side-sortables .cmb2-metabox-title,.inner-sidebar .cmb2-metabox-title{font-size:1.2em;font-style:italic}#side-sortables .cmb-remove-row,.inner-sidebar .cmb-remove-row{clear:both;padding-top:12px;padding-bottom:0}#side-sortables .cmb2-upload-button,.inner-sidebar .cmb2-upload-button{clear:both;margin-top:12px}.cmb2-metabox .cmbhandle{color:#757575;float:left;width:27px;height:30px;cursor:pointer;left:-1em;position:relative}.cmb2-metabox .cmbhandle:before{content:'\f142';left:12px;font:normal 20px/1 dashicons;speak:none;display:inline-block;padding:8px 10px;top:0;position:relative;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-decoration:none!important}.cmb2-metabox .postbox.closed .cmbhandle:before{content:'\f140'}.cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row{-webkit-appearance:none!important;background:0 0!important;border:none!important;position:absolute;right:0;top:.5em;line-height:1em;padding:2px 6px 3px;opacity:.5}.cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]){cursor:pointer;color:#a00;opacity:1}.cmb2-metabox button.dashicons-before.dashicons-no-alt.cmb-remove-group-row:not([disabled]):hover{color:red}* html .cmb2-element.ui-helper-clearfix{height:1%}.cmb2-element .ui-datepicker,.cmb2-element.ui-datepicker{padding:0;margin:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;background-color:#fff;border:1px solid #dfdfdf;border-top:none;-webkit-box-shadow:0 3px 6px rgba(0,0,0,.075);box-shadow:0 3px 6px rgba(0,0,0,.075);min-width:17em;width:auto}.cmb2-element .ui-datepicker *,.cmb2-element.ui-datepicker *{padding:0;font-family:"Open Sans",sans-serif;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.cmb2-element .ui-datepicker table,.cmb2-element.ui-datepicker table{font-size:13px;margin:0;border:none;border-collapse:collapse}.cmb2-element .ui-datepicker .ui-datepicker-header,.cmb2-element .ui-datepicker .ui-widget-header,.cmb2-element.ui-datepicker .ui-datepicker-header,.cmb2-element.ui-datepicker .ui-widget-header{background-image:none;border:none;color:#fff;font-weight:400}.cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover,.cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover{background:0 0;border-color:transparent;cursor:pointer}.cmb2-element .ui-datepicker .ui-datepicker-title,.cmb2-element.ui-datepicker .ui-datepicker-title{margin:0;padding:10px 0;color:#fff;font-size:14px;line-height:14px;text-align:center}.cmb2-element .ui-datepicker .ui-datepicker-title select,.cmb2-element.ui-datepicker .ui-datepicker-title select{margin-top:-8px;margin-bottom:-8px}.cmb2-element .ui-datepicker .ui-datepicker-next,.cmb2-element .ui-datepicker .ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-datepicker-next,.cmb2-element.ui-datepicker .ui-datepicker-prev{position:relative;top:0;height:34px;width:34px}.cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-next,.cmb2-element .ui-datepicker .ui-state-hover.ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-next,.cmb2-element.ui-datepicker .ui-state-hover.ui-datepicker-prev{border:none}.cmb2-element .ui-datepicker .ui-datepicker-prev,.cmb2-element .ui-datepicker .ui-datepicker-prev-hover,.cmb2-element.ui-datepicker .ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-datepicker-prev-hover{right:0}.cmb2-element .ui-datepicker .ui-datepicker-next,.cmb2-element .ui-datepicker .ui-datepicker-next-hover,.cmb2-element.ui-datepicker .ui-datepicker-next,.cmb2-element.ui-datepicker .ui-datepicker-next-hover{left:0}.cmb2-element .ui-datepicker .ui-datepicker-next span,.cmb2-element .ui-datepicker .ui-datepicker-prev span,.cmb2-element.ui-datepicker .ui-datepicker-next span,.cmb2-element.ui-datepicker .ui-datepicker-prev span{display:none}.cmb2-element .ui-datepicker .ui-datepicker-prev,.cmb2-element.ui-datepicker .ui-datepicker-prev{float:right}.cmb2-element .ui-datepicker .ui-datepicker-next,.cmb2-element.ui-datepicker .ui-datepicker-next{float:left}.cmb2-element .ui-datepicker .ui-datepicker-next:before,.cmb2-element .ui-datepicker .ui-datepicker-prev:before,.cmb2-element.ui-datepicker .ui-datepicker-next:before,.cmb2-element.ui-datepicker .ui-datepicker-prev:before{font:normal 20px/34px dashicons;padding-right:7px;color:#fff;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;width:34px;height:34px}.cmb2-element .ui-datepicker .ui-datepicker-prev:before,.cmb2-element.ui-datepicker .ui-datepicker-prev:before{content:'\f341'}.cmb2-element .ui-datepicker .ui-datepicker-next:before,.cmb2-element.ui-datepicker .ui-datepicker-next:before{content:'\f345'}.cmb2-element .ui-datepicker .ui-datepicker-next-hover:before,.cmb2-element .ui-datepicker .ui-datepicker-prev-hover:before,.cmb2-element.ui-datepicker .ui-datepicker-next-hover:before,.cmb2-element.ui-datepicker .ui-datepicker-prev-hover:before{opacity:.7}.cmb2-element .ui-datepicker select.ui-datepicker-month,.cmb2-element .ui-datepicker select.ui-datepicker-year,.cmb2-element.ui-datepicker select.ui-datepicker-month,.cmb2-element.ui-datepicker select.ui-datepicker-year{width:33%;background:0 0;border-color:transparent;box-shadow:none;color:#fff}.cmb2-element .ui-datepicker select.ui-datepicker-month option,.cmb2-element .ui-datepicker select.ui-datepicker-year option,.cmb2-element.ui-datepicker select.ui-datepicker-month option,.cmb2-element.ui-datepicker select.ui-datepicker-year option{color:#333}.cmb2-element .ui-datepicker thead,.cmb2-element.ui-datepicker thead{color:#fff;font-weight:600}.cmb2-element .ui-datepicker thead th,.cmb2-element.ui-datepicker thead th{font-weight:400}.cmb2-element .ui-datepicker th,.cmb2-element.ui-datepicker th{padding:10px}.cmb2-element .ui-datepicker td,.cmb2-element.ui-datepicker td{padding:0;border:1px solid #f4f4f4}.cmb2-element .ui-datepicker td.ui-datepicker-other-month,.cmb2-element.ui-datepicker td.ui-datepicker-other-month{border:transparent}.cmb2-element .ui-datepicker td.ui-datepicker-week-end,.cmb2-element.ui-datepicker td.ui-datepicker-week-end{background-color:#f4f4f4;border:1px solid #f4f4f4}.cmb2-element .ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today,.cmb2-element.ui-datepicker td.ui-datepicker-week-end.ui-datepicker-today{-webkit-box-shadow:inset 0 0 1px 0 rgba(0,0,0,.1);-moz-box-shadow:inset 0 0 1px 0 rgba(0,0,0,.1);box-shadow:inset 0 0 1px 0 rgba(0,0,0,.1)}.cmb2-element .ui-datepicker td.ui-datepicker-today,.cmb2-element.ui-datepicker td.ui-datepicker-today{background-color:#f0f0c0}.cmb2-element .ui-datepicker td.ui-datepicker-current-day,.cmb2-element.ui-datepicker td.ui-datepicker-current-day{background:#bd8}.cmb2-element .ui-datepicker td .ui-state-default,.cmb2-element.ui-datepicker td .ui-state-default{background:0 0;border:none;text-align:center;text-decoration:none;width:auto;display:block;padding:5px 10px;font-weight:400;color:#444}.cmb2-element .ui-datepicker td.ui-state-disabled .ui-state-default,.cmb2-element.ui-datepicker td.ui-state-disabled .ui-state-default{opacity:.5}.cmb2-element .ui-datepicker .ui-datepicker-header,.cmb2-element .ui-datepicker .ui-widget-header,.cmb2-element.ui-datepicker .ui-datepicker-header,.cmb2-element.ui-datepicker .ui-widget-header{background:#00a0d2}.cmb2-element .ui-datepicker thead,.cmb2-element.ui-datepicker thead{background:#32373c}.cmb2-element .ui-datepicker td .ui-state-active,.cmb2-element .ui-datepicker td .ui-state-hover,.cmb2-element.ui-datepicker td .ui-state-active,.cmb2-element.ui-datepicker td .ui-state-hover{background:#0073aa;color:#fff}.cmb2-element .ui-datepicker .ui-timepicker-div,.cmb2-element.ui-datepicker .ui-timepicker-div{font-size:14px}.cmb2-element .ui-datepicker .ui-timepicker-div dl,.cmb2-element.ui-datepicker .ui-timepicker-div dl{text-align:right;padding:0 .6em}.cmb2-element .ui-datepicker .ui-timepicker-div dl dt,.cmb2-element.ui-datepicker .ui-timepicker-div dl dt{float:right;clear:right;padding:0 5px 0 0}.cmb2-element .ui-datepicker .ui-timepicker-div dl dd,.cmb2-element.ui-datepicker .ui-timepicker-div dl dd{margin:0 40% 10px 10px}.cmb2-element .ui-datepicker .ui-timepicker-div dl dd select,.cmb2-element.ui-datepicker .ui-timepicker-div dl dd select{width:100%}.cmb2-element .ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane,.cmb2-element.ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane{padding:.6em;text-align:right}.cmb2-element .ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-primary,.cmb2-element .ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-secondary,.cmb2-element.ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-primary,.cmb2-element.ui-datepicker .ui-timepicker-div+.ui-datepicker-buttonpane .button-secondary{padding:0 10px 1px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;margin:0 .4em .4em .6em}.admin-color-fresh .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-fresh .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-fresh .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-fresh .cmb2-element.ui-datepicker .ui-widget-header{background:#00a0d2}.admin-color-fresh .cmb2-element .ui-datepicker thead,.admin-color-fresh .cmb2-element.ui-datepicker thead{background:#32373c}.admin-color-fresh .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-fresh .cmb2-element.ui-datepicker td .ui-state-hover{background:#0073aa;color:#fff}.admin-color-blue .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-blue .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-blue .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-blue .cmb2-element.ui-datepicker .ui-widget-header{background:#52accc}.admin-color-blue .cmb2-element .ui-datepicker thead,.admin-color-blue .cmb2-element.ui-datepicker thead{background:#4796b3}.admin-color-blue .cmb2-element .ui-datepicker td .ui-state-active,.admin-color-blue .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-blue .cmb2-element.ui-datepicker td .ui-state-active,.admin-color-blue .cmb2-element.ui-datepicker td .ui-state-hover{background:#096484;color:#fff}.admin-color-blue .cmb2-element .ui-datepicker td.ui-datepicker-today,.admin-color-blue .cmb2-element.ui-datepicker td.ui-datepicker-today{background:#eee}.admin-color-coffee .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-coffee .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-coffee .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-coffee .cmb2-element.ui-datepicker .ui-widget-header{background:#59524c}.admin-color-coffee .cmb2-element .ui-datepicker thead,.admin-color-coffee .cmb2-element.ui-datepicker thead{background:#46403c}.admin-color-coffee .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-coffee .cmb2-element.ui-datepicker td .ui-state-hover{background:#c7a589;color:#fff}.admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-ectoplasm .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-ectoplasm .cmb2-element.ui-datepicker .ui-widget-header{background:#523f6d}.admin-color-ectoplasm .cmb2-element .ui-datepicker thead,.admin-color-ectoplasm .cmb2-element.ui-datepicker thead{background:#413256}.admin-color-ectoplasm .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-ectoplasm .cmb2-element.ui-datepicker td .ui-state-hover{background:#a3b745;color:#fff}.admin-color-midnight .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-midnight .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-midnight .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-midnight .cmb2-element.ui-datepicker .ui-widget-header{background:#363b3f}.admin-color-midnight .cmb2-element .ui-datepicker thead,.admin-color-midnight .cmb2-element.ui-datepicker thead{background:#26292c}.admin-color-midnight .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-midnight .cmb2-element.ui-datepicker td .ui-state-hover{background:#e14d43;color:#fff}.admin-color-ocean .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-ocean .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-ocean .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-ocean .cmb2-element.ui-datepicker .ui-widget-header{background:#738e96}.admin-color-ocean .cmb2-element .ui-datepicker thead,.admin-color-ocean .cmb2-element.ui-datepicker thead{background:#627c83}.admin-color-ocean .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-ocean .cmb2-element.ui-datepicker td .ui-state-hover{background:#9ebaa0;color:#fff}.admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-sunrise .cmb2-element .ui-datepicker .ui-datepicker-header .ui-state-hover,.admin-color-sunrise .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-sunrise .cmb2-element.ui-datepicker .ui-datepicker-header .ui-state-hover,.admin-color-sunrise .cmb2-element.ui-datepicker .ui-widget-header{background:#cf4944}.admin-color-sunrise .cmb2-element .ui-datepicker th,.admin-color-sunrise .cmb2-element.ui-datepicker th{border-color:#be3631;background:#be3631}.admin-color-sunrise .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-sunrise .cmb2-element.ui-datepicker td .ui-state-hover{background:#dd823b;color:#fff}.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-light .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-light .cmb2-element.ui-datepicker .ui-widget-header{background:#e5e5e5}.admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-month,.admin-color-light .cmb2-element .ui-datepicker select.ui-datepicker-year,.admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-month,.admin-color-light .cmb2-element.ui-datepicker select.ui-datepicker-year{color:#555}.admin-color-light .cmb2-element .ui-datepicker thead,.admin-color-light .cmb2-element.ui-datepicker thead{background:#888}.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-next:before,.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-prev:before,.admin-color-light .cmb2-element .ui-datepicker .ui-datepicker-title,.admin-color-light .cmb2-element .ui-datepicker td .ui-state-default,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-next:before,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-prev:before,.admin-color-light .cmb2-element.ui-datepicker .ui-datepicker-title,.admin-color-light .cmb2-element.ui-datepicker td .ui-state-default{color:#555}.admin-color-light .cmb2-element .ui-datepicker td .ui-state-active,.admin-color-light .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-light .cmb2-element.ui-datepicker td .ui-state-active,.admin-color-light .cmb2-element.ui-datepicker td .ui-state-hover{background:#ccc}.admin-color-light .cmb2-element .ui-datepicker td.ui-datepicker-today,.admin-color-light .cmb2-element.ui-datepicker td.ui-datepicker-today{background:#eee}.admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-bbp-evergreen .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker .ui-widget-header{background:#56b274}.admin-color-bbp-evergreen .cmb2-element .ui-datepicker thead,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker thead{background:#36533f}.admin-color-bbp-evergreen .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-bbp-evergreen .cmb2-element.ui-datepicker td .ui-state-hover{background:#446950;color:#fff}.admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-datepicker-header,.admin-color-bbp-mint .cmb2-element .ui-datepicker .ui-widget-header,.admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-datepicker-header,.admin-color-bbp-mint .cmb2-element.ui-datepicker .ui-widget-header{background:#4ca26a}.admin-color-bbp-mint .cmb2-element .ui-datepicker thead,.admin-color-bbp-mint .cmb2-element.ui-datepicker thead{background:#4f6d59}.admin-color-bbp-mint .cmb2-element .ui-datepicker td .ui-state-hover,.admin-color-bbp-mint .cmb2-element.ui-datepicker td .ui-state-hover{background:#5fb37c;color:#fff}.cmb2-char-counter-wrap{margin:.5em 0 1em}.cmb2-char-counter-wrap input[type=text]{font-size:12px;width:25px}.cmb2-char-counter-wrap.cmb2-max-exceeded input[type=text]{border-color:#a00!important}.cmb2-char-counter-wrap.cmb2-max-exceeded .cmb2-char-max-msg{display:inline-block}.cmb2-char-max-msg{color:#a00;display:none;font-weight:600;margin-right:1em} cmb2/cmb2/css/index.php 0000644 00000000033 15151523432 0010617 0 ustar 00 <?php // Silence is golden cmb2/cmb2/init.php 0000644 00000012471 15151523432 0007674 0 ustar 00 <?php /** * The initation loader for CMB2, and the main plugin file. * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * Plugin Name: CMB2 * Plugin URI: https://github.com/CMB2/CMB2 * Description: CMB2 will create metaboxes and forms with custom fields that will blow your mind. * Author: CMB2 team * Author URI: https://cmb2.io * Contributors: Justin Sternberg (@jtsternberg / dsgnwrks.pro) * WebDevStudios (@webdevstudios / webdevstudios.com) * Human Made (@humanmadeltd / hmn.md) * Jared Atchison (@jaredatch / jaredatchison.com) * Bill Erickson (@billerickson / billerickson.net) * Andrew Norcross (@norcross / andrewnorcross.com) * * Version: 2.11.0 * * Text Domain: cmb2 * Domain Path: languages * * * Released under the GPL license * http://www.opensource.org/licenses/gpl-license.php * * This is an add-on for WordPress * https://wordpress.org/ * * ********************************************************************** * 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 2 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 not edit the code below * (or any code in the included files) * or things might explode! * *********************************************************************** */ if ( ! class_exists( 'CMB2_Bootstrap_2110', false ) ) { /** * Handles checking for and loading the newest version of CMB2 * * @since 2.0.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Bootstrap_2110 { /** * Current version number * * @var string * @since 1.0.0 */ const VERSION = '2.11.0'; /** * Current version hook priority. * Will decrement with each release * * @var int * @since 2.0.0 */ const PRIORITY = 9957; /** * Single instance of the CMB2_Bootstrap_2110 object * * @var CMB2_Bootstrap_2110 */ public static $single_instance = null; /** * Creates/returns the single instance CMB2_Bootstrap_2110 object * * @since 2.0.0 * @return CMB2_Bootstrap_2110 Single instance object */ public static function initiate() { if ( null === self::$single_instance ) { self::$single_instance = new self(); } return self::$single_instance; } /** * Starts the version checking process. * Creates CMB2_LOADED definition for early detection by other scripts * * Hooks CMB2 inclusion to the init hook on a high priority which decrements * (increasing the priority) with each version release. * * @since 2.0.0 */ private function __construct() { /** * A constant you can use to check if CMB2 is loaded * for your plugins/themes with CMB2 dependency */ if ( ! defined( 'CMB2_LOADED' ) ) { define( 'CMB2_LOADED', self::PRIORITY ); } if ( ! function_exists( 'add_action' ) ) { // We are running outside of the context of WordPress. return; } add_action( 'init', array( $this, 'include_cmb' ), self::PRIORITY ); } /** * A final check if CMB2 exists before kicking off our CMB2 loading. * CMB2_VERSION and CMB2_DIR constants are set at this point. * * @since 2.0.0 */ public function include_cmb() { if ( class_exists( 'CMB2', false ) ) { return; } if ( ! defined( 'CMB2_VERSION' ) ) { define( 'CMB2_VERSION', self::VERSION ); } if ( ! defined( 'CMB2_DIR' ) ) { define( 'CMB2_DIR', trailingslashit( dirname( __FILE__ ) ) ); } $this->l10ni18n(); // Include helper functions. require_once CMB2_DIR . 'includes/CMB2_Base.php'; require_once CMB2_DIR . 'includes/CMB2.php'; require_once CMB2_DIR . 'includes/helper-functions.php'; // Now kick off the class autoloader. spl_autoload_register( 'cmb2_autoload_classes' ); // Kick the whole thing off. require_once( cmb2_dir( 'bootstrap.php' ) ); cmb2_bootstrap(); } /** * Registers CMB2 text domain path * * @since 2.0.0 */ public function l10ni18n() { $loaded = load_plugin_textdomain( 'cmb2', false, '/languages/' ); if ( ! $loaded ) { $loaded = load_muplugin_textdomain( 'cmb2', '/languages/' ); } if ( ! $loaded ) { $loaded = load_theme_textdomain( 'cmb2', get_stylesheet_directory() . '/languages/' ); } if ( ! $loaded ) { $locale = apply_filters( 'plugin_locale', function_exists( 'determine_locale' ) ? determine_locale() : get_locale(), 'cmb2' ); $mofile = dirname( __FILE__ ) . '/languages/cmb2-' . $locale . '.mo'; load_textdomain( 'cmb2', $mofile ); } } } // Make it so... CMB2_Bootstrap_2110::initiate(); }// End if(). cmb2/cmb2/includes/shim/WP_REST_Controller.php 0000644 00000036736 15151523432 0015077 0 ustar 00 <?php abstract class WP_REST_Controller { /** * The namespace of this controller's route. * * @var string */ protected $namespace; /** * The base of this controller's route. * * @var string */ protected $rest_base; /** * Register the routes for the objects of the controller. */ public function register_routes() { /* translators: %s: register_routes() */ _doing_it_wrong( 'WP_REST_Controller::register_routes', sprintf( __( "Method '%s' must be overridden." ), __METHOD__ ), '4.7' ); } /** * Check if a given request has access to get items. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function get_items_permissions_check( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Get a collection of items. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_items( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Check if a given request has access to get a specific item. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function get_item_permissions_check( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Get one item from the collection. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Check if a given request has access to create items. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function create_item_permissions_check( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Create one item from the collection. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function create_item( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Check if a given request has access to update a specific item. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function update_item_permissions_check( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Update one item from the collection. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function update_item( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Check if a given request has access to delete a specific item. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function delete_item_permissions_check( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Delete one item from the collection. * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function delete_item( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Prepare the item for create or update operation. * * @param WP_REST_Request $request Request object. * @return WP_Error|object $prepared_item */ protected function prepare_item_for_database( $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Prepare the item for the REST response. * * @param mixed $item WordPress representation of the item. * @param WP_REST_Request $request Request object. * @return WP_REST_Response $response */ public function prepare_item_for_response( $item, $request ) { return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405, ) ); } /** * Prepare a response for inserting into a collection. * * @param WP_REST_Response $response Response object. * @return array Response data, ready for insertion into collection data. */ public function prepare_response_for_collection( $response ) { if ( ! ( $response instanceof WP_REST_Response ) ) { return $response; } $data = (array) $response->get_data(); $server = rest_get_server(); if ( method_exists( $server, 'get_compact_response_links' ) ) { $links = call_user_func( array( $server, 'get_compact_response_links' ), $response ); } else { $links = call_user_func( array( $server, 'get_response_links' ), $response ); } if ( ! empty( $links ) ) { $data['_links'] = $links; } return $data; } /** * Filter a response based on the context defined in the schema. * * @param array $data * @param string $context * @return array */ public function filter_response_by_context( $data, $context ) { $schema = $this->get_item_schema(); foreach ( $data as $key => $value ) { if ( empty( $schema['properties'][ $key ] ) || empty( $schema['properties'][ $key ]['context'] ) ) { continue; } if ( ! in_array( $context, $schema['properties'][ $key ]['context'] ) ) { unset( $data[ $key ] ); continue; } if ( 'object' === $schema['properties'][ $key ]['type'] && ! empty( $schema['properties'][ $key ]['properties'] ) ) { foreach ( $schema['properties'][ $key ]['properties'] as $attribute => $details ) { if ( empty( $details['context'] ) ) { continue; } if ( ! in_array( $context, $details['context'] ) ) { if ( isset( $data[ $key ][ $attribute ] ) ) { unset( $data[ $key ][ $attribute ] ); } } } } } return $data; } /** * Get the item's schema, conforming to JSON Schema. * * @return array */ public function get_item_schema() { return $this->add_additional_fields_schema( array() ); } /** * Get the item's schema for display / public consumption purposes. * * @return array */ public function get_public_item_schema() { $schema = $this->get_item_schema(); foreach ( $schema['properties'] as &$property ) { if ( isset( $property['arg_options'] ) ) { unset( $property['arg_options'] ); } } return $schema; } /** * Get the query params for collections. * * @return array */ public function get_collection_params() { return array( 'context' => $this->get_context_param(), 'page' => array( 'description' => __( 'Current page of the collection.' ), 'type' => 'integer', 'default' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', 'minimum' => 1, ), 'per_page' => array( 'description' => __( 'Maximum number of items to be returned in result set.' ), 'type' => 'integer', 'default' => 10, 'minimum' => 1, 'maximum' => 100, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), 'search' => array( 'description' => __( 'Limit results to those matching a string.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => 'rest_validate_request_arg', ), ); } /** * Get the magical context param. * * Ensures consistent description between endpoints, and populates enum from schema. * * @param array $args * @return array */ public function get_context_param( $args = array() ) { $param_details = array( 'description' => __( 'Scope under which the request is made; determines fields present in response.' ), 'type' => 'string', 'sanitize_callback' => 'sanitize_key', 'validate_callback' => 'rest_validate_request_arg', ); $schema = $this->get_item_schema(); if ( empty( $schema['properties'] ) ) { return array_merge( $param_details, $args ); } $contexts = array(); foreach ( $schema['properties'] as $attributes ) { if ( ! empty( $attributes['context'] ) ) { $contexts = array_merge( $contexts, $attributes['context'] ); } } if ( ! empty( $contexts ) ) { $param_details['enum'] = array_unique( $contexts ); rsort( $param_details['enum'] ); } return array_merge( $param_details, $args ); } /** * Add the values from additional fields to a data object. * * @param array $object * @param WP_REST_Request $request * @return array modified object with additional fields. */ protected function add_additional_fields_to_object( $object, $request ) { $additional_fields = $this->get_additional_fields(); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['get_callback'] ) { continue; } $object[ $field_name ] = call_user_func( $field_options['get_callback'], $object, $field_name, $request, $this->get_object_type() ); } return $object; } /** * Update the values of additional fields added to a data object. * * @param array $object * @param WP_REST_Request $request */ protected function update_additional_fields_for_object( $object, $request ) { $additional_fields = $this->get_additional_fields(); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['update_callback'] ) { continue; } // Don't run the update callbacks if the data wasn't passed in the request. if ( ! isset( $request[ $field_name ] ) ) { continue; } call_user_func( $field_options['update_callback'], $request[ $field_name ], $object, $field_name, $request, $this->get_object_type() ); } } /** * Add the schema from additional fields to an schema array. * * The type of object is inferred from the passed schema. * * @param array $schema Schema array. */ protected function add_additional_fields_schema( $schema ) { if ( empty( $schema['title'] ) ) { return $schema; } /** * Can't use $this->get_object_type otherwise we cause an inf loop. */ $object_type = $schema['title']; $additional_fields = $this->get_additional_fields( $object_type ); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['schema'] ) { continue; } $schema['properties'][ $field_name ] = $field_options['schema']; } return $schema; } /** * Get all the registered additional fields for a given object-type. * * @param string $object_type * @return array */ protected function get_additional_fields( $object_type = null ) { if ( ! $object_type ) { $object_type = $this->get_object_type(); } if ( ! $object_type ) { return array(); } global $wp_rest_additional_fields; if ( ! $wp_rest_additional_fields || ! isset( $wp_rest_additional_fields[ $object_type ] ) ) { return array(); } return $wp_rest_additional_fields[ $object_type ]; } /** * Get the object type this controller is responsible for managing. * * @return string */ protected function get_object_type() { $schema = $this->get_item_schema(); if ( ! $schema || ! isset( $schema['title'] ) ) { return null; } return $schema['title']; } /** * Get an array of endpoint arguments from the item schema for the controller. * * @param string $method HTTP method of the request. The arguments * for `CREATABLE` requests are checked for required * values and may fall-back to a given default, this * is not done on `EDITABLE` requests. Default is * WP_REST_Server::CREATABLE. * @return array $endpoint_args */ public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) { $schema = $this->get_item_schema(); $schema_properties = ! empty( $schema['properties'] ) ? $schema['properties'] : array(); $endpoint_args = array(); foreach ( $schema_properties as $field_id => $params ) { // Arguments specified as `readonly` are not allowed to be set. if ( ! empty( $params['readonly'] ) ) { continue; } $endpoint_args[ $field_id ] = array( 'validate_callback' => 'rest_validate_request_arg', 'sanitize_callback' => 'rest_sanitize_request_arg', ); if ( isset( $params['description'] ) ) { $endpoint_args[ $field_id ]['description'] = $params['description']; } if ( WP_REST_Server::CREATABLE === $method && isset( $params['default'] ) ) { $endpoint_args[ $field_id ]['default'] = $params['default']; } if ( WP_REST_Server::CREATABLE === $method && ! empty( $params['required'] ) ) { $endpoint_args[ $field_id ]['required'] = true; } foreach ( array( 'type', 'format', 'enum' ) as $schema_prop ) { if ( isset( $params[ $schema_prop ] ) ) { $endpoint_args[ $field_id ][ $schema_prop ] = $params[ $schema_prop ]; } } // Merge in any options provided by the schema property. if ( isset( $params['arg_options'] ) ) { // Only use required / default from arg_options on CREATABLE endpoints. if ( WP_REST_Server::CREATABLE !== $method ) { $params['arg_options'] = array_diff_key( $params['arg_options'], array( 'required' => '', 'default' => '', ) ); } $endpoint_args[ $field_id ] = array_merge( $endpoint_args[ $field_id ], $params['arg_options'] ); } }// End foreach(). return $endpoint_args; } /** * Retrieves post data given a post ID or post object. * * This is a subset of the functionality of the `get_post()` function, with * the additional functionality of having `the_post` action done on the * resultant post object. This is done so that plugins may manipulate the * post that is used in the REST API. * * @see get_post() * @global WP_Query $wp_query * * @param int|WP_Post $post Post ID or post object. Defaults to global $post. * @return WP_Post|null A `WP_Post` object when successful. */ public function get_post( $post ) { $post_obj = get_post( $post ); /** * Filter the post. * * Allows plugins to filter the post object as returned by `\WP_REST_Controller::get_post()`. * * @param WP_Post|null $post_obj The post object as returned by `get_post()`. * @param int|WP_Post $post The original value used to obtain the post object. */ $post = apply_filters( 'rest_the_post', $post_obj, $post ); return $post; } } cmb2/cmb2/includes/CMB2_Field_Display.php 0000644 00000030522 15151523432 0014007 0 ustar 00 <?php /** * CMB2 field display base. * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Field_Display { /** * A CMB field object * * @var CMB2_Field object * @since 2.2.2 */ public $field; /** * The CMB field object's value. * * @var mixed * @since 2.2.2 */ public $value; /** * Get the corresponding display class for the field type. * * @since 2.2.2 * @param CMB2_Field $field Requested field type. * @return CMB2_Field_Display */ public static function get( CMB2_Field $field ) { $fieldtype = $field->type(); $display_class_name = $field->args( 'display_class' ); if ( empty( $display_class_name ) ) { switch ( $fieldtype ) { case 'text_url': $display_class_name = 'CMB2_Display_Text_Url'; break; case 'text_money': $display_class_name = 'CMB2_Display_Text_Money'; break; case 'colorpicker': $display_class_name = 'CMB2_Display_Colorpicker'; break; case 'checkbox': $display_class_name = 'CMB2_Display_Checkbox'; break; case 'wysiwyg': case 'textarea_small': $display_class_name = 'CMB2_Display_Textarea'; break; case 'textarea_code': $display_class_name = 'CMB2_Display_Textarea_Code'; break; case 'text_time': $display_class_name = 'CMB2_Display_Text_Time'; break; case 'text_date': case 'text_date_timestamp': case 'text_datetime_timestamp': $display_class_name = 'CMB2_Display_Text_Date'; break; case 'text_datetime_timestamp_timezone': $display_class_name = 'CMB2_Display_Text_Date_Timezone'; break; case 'select': case 'radio': case 'radio_inline': $display_class_name = 'CMB2_Display_Select'; break; case 'multicheck': case 'multicheck_inline': $display_class_name = 'CMB2_Display_Multicheck'; break; case 'taxonomy_radio': case 'taxonomy_radio_inline': case 'taxonomy_select': case 'taxonomy_select_hierarchical': case 'taxonomy_radio_hierarchical': $display_class_name = 'CMB2_Display_Taxonomy_Radio'; break; case 'taxonomy_multicheck': case 'taxonomy_multicheck_inline': case 'taxonomy_multicheck_hierarchical': $display_class_name = 'CMB2_Display_Taxonomy_Multicheck'; break; case 'file': $display_class_name = 'CMB2_Display_File'; break; case 'file_list': $display_class_name = 'CMB2_Display_File_List'; break; case 'oembed': $display_class_name = 'CMB2_Display_oEmbed'; break; default: $display_class_name = __CLASS__; break; }// End switch. } if ( has_action( "cmb2_display_class_{$fieldtype}" ) ) { /** * Filters the custom field display class used for displaying the field. Class is required to extend CMB2_Type_Base. * * The dynamic portion of the hook name, $fieldtype, refers to the (custom) field type. * * @since 2.2.4 * * @param string $display_class_name The custom field display class to use. * @param object $field The `CMB2_Field` object. */ $display_class_name = apply_filters( "cmb2_display_class_{$fieldtype}", $display_class_name, $field ); } return new $display_class_name( $field ); } /** * Setup our class vars * * @since 2.2.2 * @param CMB2_Field $field A CMB2 field object. */ public function __construct( CMB2_Field $field ) { $this->field = $field; $this->value = $this->field->value; } /** * Catchall method if field's 'display_cb' is NOT defined, or field type does * not have a corresponding display method * * @since 2.2.2 */ public function display() { // If repeatable. if ( $this->field->args( 'repeatable' ) ) { // And has a repeatable value. if ( is_array( $this->field->value ) ) { // Then loop and output. echo '<ul class="cmb2-' . esc_attr( sanitize_html_class( str_replace( '_', '-', $this->field->type() ) ) ) . '">'; foreach ( $this->field->value as $val ) { $this->value = $val; echo '<li>', $this->_display(), '</li>'; ; } echo '</ul>'; } } else { $this->_display(); } } /** * Default fallback display method. * * @since 2.2.2 */ protected function _display() { print_r( $this->value ); } } class CMB2_Display_Text_Url extends CMB2_Field_Display { /** * Display url value. * * @since 2.2.2 */ protected function _display() { echo make_clickable( esc_url( $this->value ) ); } } class CMB2_Display_Text_Money extends CMB2_Field_Display { /** * Display text_money value. * * @since 2.2.2 */ protected function _display() { $this->value = $this->value ? $this->value : '0'; echo ( ! $this->field->get_param_callback_result( 'before_field' ) ? '$' : ' ' ), $this->value; } } class CMB2_Display_Colorpicker extends CMB2_Field_Display { /** * Display color picker value. * * @since 2.2.2 */ protected function _display() { echo '<span class="cmb2-colorpicker-swatch"><span style="background-color:', esc_attr( $this->value ), '"></span> ', esc_html( $this->value ), '</span>'; } } class CMB2_Display_Checkbox extends CMB2_Field_Display { /** * Display multicheck value. * * @since 2.2.2 */ protected function _display() { echo $this->value === 'on' ? 'on' : 'off'; } } class CMB2_Display_Select extends CMB2_Field_Display { /** * Display select value. * * @since 2.2.2 */ protected function _display() { $options = $this->field->options(); $fallback = $this->field->args( 'show_option_none' ); if ( ! $fallback && isset( $options[''] ) ) { $fallback = $options['']; } if ( ! $this->value && $fallback ) { echo $fallback; } elseif ( isset( $options[ $this->value ] ) ) { echo $options[ $this->value ]; } else { echo esc_attr( $this->value ); } } } class CMB2_Display_Multicheck extends CMB2_Field_Display { /** * Display multicheck value. * * @since 2.2.2 */ protected function _display() { if ( empty( $this->value ) || ! is_array( $this->value ) ) { return; } $options = $this->field->options(); $output = array(); foreach ( $this->value as $val ) { if ( isset( $options[ $val ] ) ) { $output[] = $options[ $val ]; } else { $output[] = esc_attr( $val ); } } echo implode( ', ', $output ); } } class CMB2_Display_Textarea extends CMB2_Field_Display { /** * Display textarea value. * * @since 2.2.2 */ protected function _display() { echo wpautop( wp_kses_post( $this->value ) ); } } class CMB2_Display_Textarea_Code extends CMB2_Field_Display { /** * Display textarea_code value. * * @since 2.2.2 */ protected function _display() { echo '<xmp class="cmb2-code">' . print_r( $this->value, true ) . '</xmp>'; } } class CMB2_Display_Text_Time extends CMB2_Field_Display { /** * Display text_time value. * * @since 2.2.2 */ protected function _display() { echo $this->field->get_timestamp_format( 'time_format', $this->value ); } } class CMB2_Display_Text_Date extends CMB2_Field_Display { /** * Display text_date value. * * @since 2.2.2 */ protected function _display() { echo $this->field->get_timestamp_format( 'date_format', $this->value ); } } class CMB2_Display_Text_Date_Timezone extends CMB2_Field_Display { /** * Display text_datetime_timestamp_timezone value. * * @since 2.2.2 */ protected function _display() { if ( empty( $this->value ) ) { return; } $datetime = CMB2_Utils::get_datetime_from_value( $this->value ); if ( ! $datetime || ! $datetime instanceof DateTime ) { return; } $date = $datetime->format( stripslashes( $this->field->args( 'date_format' ) ) ); $time = $datetime->format( stripslashes( $this->field->args( 'time_format' ) ) ); $timezone = $datetime->getTimezone()->getName(); echo $date; if ( $time ) { echo ' ' . $time; } if ( $timezone ) { echo ', ' . $timezone; } } } class CMB2_Display_Taxonomy_Radio extends CMB2_Field_Display { /** * Display single taxonomy value. * * @since 2.2.2 */ protected function _display() { $taxonomy = $this->field->args( 'taxonomy' ); $types = new CMB2_Types( $this->field ); $type = $types->get_new_render_type( $this->field->type(), 'CMB2_Type_Taxonomy_Radio' ); $terms = $type->get_object_terms(); $term = false; if ( is_wp_error( $terms ) || empty( $terms ) && ( $default = $this->field->get_default() ) ) { $term = get_term_by( 'slug', $default, $taxonomy ); } elseif ( ! empty( $terms ) ) { $term = $terms[ key( $terms ) ]; } if ( $term ) { $link = get_edit_term_link( $term->term_id, $taxonomy ); echo '<a href="', esc_url( $link ), '">', esc_html( $term->name ), '</a>'; } } } class CMB2_Display_Taxonomy_Multicheck extends CMB2_Field_Display { /** * Display taxonomy values. * * @since 2.2.2 */ protected function _display() { $taxonomy = $this->field->args( 'taxonomy' ); $types = new CMB2_Types( $this->field ); $type = $types->get_new_render_type( $this->field->type(), 'CMB2_Type_Taxonomy_Multicheck' ); $terms = $type->get_object_terms(); if ( is_wp_error( $terms ) || empty( $terms ) && ( $default = $this->field->get_default() ) ) { $terms = array(); if ( is_array( $default ) ) { foreach ( $default as $slug ) { $terms[] = get_term_by( 'slug', $slug, $taxonomy ); } } else { $terms[] = get_term_by( 'slug', $default, $taxonomy ); } } if ( is_array( $terms ) ) { $links = array(); foreach ( $terms as $term ) { $link = get_edit_term_link( $term->term_id, $taxonomy ); $links[] = '<a href="' . esc_url( $link ) . '">' . esc_html( $term->name ) . '</a>'; } // Then loop and output. echo '<div class="cmb2-taxonomy-terms-', esc_attr( sanitize_html_class( $taxonomy ) ), '">'; echo implode( ', ', $links ); echo '</div>'; } } } class CMB2_Display_File extends CMB2_Field_Display { /** * Display file value. * * @since 2.2.2 */ protected function _display() { if ( empty( $this->value ) ) { return; } $this->value = esc_url_raw( $this->value ); $types = new CMB2_Types( $this->field ); $type = $types->get_new_render_type( $this->field->type(), 'CMB2_Type_File_Base' ); $id = $this->field->get_field_clone( array( 'id' => $this->field->_id( '', false ) . '_id', ) )->escaped_value( 'absint' ); $this->file_output( $this->value, $id, $type ); } protected function file_output( $url_value, $id, CMB2_Type_File_Base $field_type ) { // If there is no ID saved yet, try to get it from the url. if ( $url_value && ! $id ) { $id = CMB2_Utils::image_id_from_url( esc_url_raw( $url_value ) ); } if ( $field_type->is_valid_img_ext( $url_value ) ) { $img_size = $this->field->args( 'preview_size' ); if ( $id ) { $image = wp_get_attachment_image( $id, $img_size, null, array( 'class' => 'cmb-image-display', ) ); } else { $size = is_array( $img_size ) ? $img_size[0] : 200; $image = '<img class="cmb-image-display" style="max-width: ' . absint( $size ) . 'px; width: 100%; height: auto;" src="' . esc_url( $url_value ) . '" alt="" />'; } echo $image; } else { printf( '<div class="file-status"><span>%1$s <strong><a href="%2$s">%3$s</a></strong></span></div>', esc_html( $field_type->_text( 'file_text', __( 'File:', 'cmb2' ) ) ), esc_url( $url_value ), esc_html( CMB2_Utils::get_file_name_from_path( $url_value ) ) ); } } } class CMB2_Display_File_List extends CMB2_Display_File { /** * Display file_list value. * * @since 2.2.2 */ protected function _display() { if ( empty( $this->value ) || ! is_array( $this->value ) ) { return; } $types = new CMB2_Types( $this->field ); $type = $types->get_new_render_type( $this->field->type(), 'CMB2_Type_File_Base' ); echo '<ul class="cmb2-display-file-list">'; foreach ( $this->value as $id => $fullurl ) { echo '<li>', $this->file_output( esc_url_raw( $fullurl ), $id, $type ), '</li>'; } echo '</ul>'; } } class CMB2_Display_oEmbed extends CMB2_Field_Display { /** * Display oembed value. * * @since 2.2.2 */ protected function _display() { if ( ! $this->value ) { return; } cmb2_do_oembed( array( 'url' => $this->value, 'object_id' => $this->field->object_id, 'object_type' => $this->field->object_type, 'oembed_args' => array( 'width' => '300', ), 'field_id' => $this->field->id(), ) ); } } cmb2/cmb2/includes/CMB2_JS.php 0000644 00000020200 15151523432 0011603 0 ustar 00 <?php /** * Handles the dependencies and enqueueing of the CMB2 JS scripts * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_JS { /** * The CMB2 JS handle * * @var string * @since 2.0.7 */ protected static $handle = 'cmb2-scripts'; /** * The CMB2 JS variable name * * @var string * @since 2.0.7 */ protected static $js_variable = 'cmb2_l10'; /** * Array of CMB2 JS dependencies * * @var array * @since 2.0.7 */ protected static $dependencies = array( 'jquery' => 'jquery', ); /** * Array of CMB2 fields model data for JS. * * @var array * @since 2.4.0 */ protected static $fields = array(); /** * Add a dependency to the array of CMB2 JS dependencies * * @since 2.0.7 * @param array|string $dependencies Array (or string) of dependencies to add. */ public static function add_dependencies( $dependencies ) { foreach ( (array) $dependencies as $dependency ) { self::$dependencies[ $dependency ] = $dependency; } } /** * Add field model data to the array for JS. * * @since 2.4.0 * * @param CMB2_Field $field Field object. */ public static function add_field_data( CMB2_Field $field ) { $hash = $field->hash_id(); if ( ! isset( self::$fields[ $hash ] ) ) { self::$fields[ $hash ] = $field->js_data(); } } /** * Enqueue the CMB2 JS * * @since 2.0.7 */ public static function enqueue() { // Filter required script dependencies. $dependencies = self::$dependencies = apply_filters( 'cmb2_script_dependencies', self::$dependencies ); // Only use minified files if SCRIPT_DEBUG is off. $debug = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG; $min = $debug ? '' : '.min'; // if colorpicker. if ( isset( $dependencies['wp-color-picker'] ) ) { if ( ! is_admin() ) { self::colorpicker_frontend(); } // Enqueue colorpicker if ( ! wp_script_is( 'wp-color-picker', 'enqueued' ) ) { wp_enqueue_script( 'wp-color-picker' ); } if ( isset( $dependencies['wp-color-picker-alpha'] ) ) { self::register_colorpicker_alpha(); } } // if file/file_list. if ( isset( $dependencies['media-editor'] ) ) { wp_enqueue_media(); CMB2_Type_File_Base::output_js_underscore_templates(); } // if timepicker. if ( isset( $dependencies['jquery-ui-datetimepicker'] ) ) { self::register_datetimepicker(); } // if cmb2-wysiwyg. $enqueue_wysiwyg = isset( $dependencies['cmb2-wysiwyg'] ) && $debug; unset( $dependencies['cmb2-wysiwyg'] ); // if cmb2-char-counter. $enqueue_char_counter = isset( $dependencies['cmb2-char-counter'] ) && $debug; unset( $dependencies['cmb2-char-counter'] ); // Enqueue cmb JS. wp_enqueue_script( self::$handle, CMB2_Utils::url( "js/cmb2{$min}.js" ), array_values( $dependencies ), CMB2_VERSION, true ); // if SCRIPT_DEBUG, we need to enqueue separately. if ( $enqueue_wysiwyg ) { wp_enqueue_script( 'cmb2-wysiwyg', CMB2_Utils::url( 'js/cmb2-wysiwyg.js' ), array( 'jquery', 'wp-util' ), CMB2_VERSION ); } if ( $enqueue_char_counter ) { wp_enqueue_script( 'cmb2-char-counter', CMB2_Utils::url( 'js/cmb2-char-counter.js' ), array( 'jquery', 'wp-util' ), CMB2_VERSION ); } self::localize( $debug ); do_action( 'cmb2_footer_enqueue' ); } /** * Register or enqueue the wp-color-picker-alpha script. * * @since 2.2.7 * * @param boolean $enqueue Whether or not to enqueue. * * @return void */ public static function register_colorpicker_alpha( $enqueue = false ) { // Only use minified files if SCRIPT_DEBUG is off. $min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; $func = $enqueue ? 'wp_enqueue_script' : 'wp_register_script'; $func( 'wp-color-picker-alpha', CMB2_Utils::url( "js/wp-color-picker-alpha{$min}.js" ), array( 'wp-color-picker' ), '2.1.3' ); } /** * Register or enqueue the jquery-ui-datetimepicker script. * * @since 2.2.7 * * @param boolean $enqueue Whether or not to enqueue. * * @return void */ public static function register_datetimepicker( $enqueue = false ) { $func = $enqueue ? 'wp_enqueue_script' : 'wp_register_script'; $func( 'jquery-ui-datetimepicker', CMB2_Utils::url( 'js/jquery-ui-timepicker-addon.min.js' ), array( 'jquery-ui-slider' ), '1.5.0' ); } /** * We need to register colorpicker on the front-end * * @since 2.0.7 */ protected static function colorpicker_frontend() { wp_register_script( 'iris', admin_url( 'js/iris.min.js' ), array( 'jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch' ), CMB2_VERSION ); wp_register_script( 'wp-color-picker', admin_url( 'js/color-picker.min.js' ), array( 'iris' ), CMB2_VERSION ); wp_localize_script( 'wp-color-picker', 'wpColorPickerL10n', array( 'clear' => esc_html__( 'Clear', 'cmb2' ), 'defaultString' => esc_html__( 'Default', 'cmb2' ), 'pick' => esc_html__( 'Select Color', 'cmb2' ), 'current' => esc_html__( 'Current Color', 'cmb2' ), ) ); } /** * Localize the php variables for CMB2 JS * * @since 2.0.7 * * @param mixed $debug Whether or not we are debugging. */ protected static function localize( $debug ) { static $localized = false; if ( $localized ) { return; } $localized = true; $l10n = array( 'fields' => self::$fields, 'ajax_nonce' => wp_create_nonce( 'ajax_nonce' ), 'ajaxurl' => admin_url( '/admin-ajax.php' ), 'script_debug' => $debug, 'up_arrow_class' => 'dashicons dashicons-arrow-up-alt2', 'down_arrow_class' => 'dashicons dashicons-arrow-down-alt2', 'user_can_richedit' => user_can_richedit(), 'defaults' => array( 'code_editor' => false, 'color_picker' => false, 'date_picker' => array( 'changeMonth' => true, 'changeYear' => true, 'dateFormat' => _x( 'mm/dd/yy', 'Valid formatDate string for jquery-ui datepicker', 'cmb2' ), 'dayNames' => explode( ',', esc_html__( 'Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday', 'cmb2' ) ), 'dayNamesMin' => explode( ',', esc_html__( 'Su, Mo, Tu, We, Th, Fr, Sa', 'cmb2' ) ), 'dayNamesShort' => explode( ',', esc_html__( 'Sun, Mon, Tue, Wed, Thu, Fri, Sat', 'cmb2' ) ), 'monthNames' => explode( ',', esc_html__( 'January, February, March, April, May, June, July, August, September, October, November, December', 'cmb2' ) ), 'monthNamesShort' => explode( ',', esc_html__( 'Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec', 'cmb2' ) ), 'nextText' => esc_html__( 'Next', 'cmb2' ), 'prevText' => esc_html__( 'Prev', 'cmb2' ), 'currentText' => esc_html__( 'Today', 'cmb2' ), 'closeText' => esc_html__( 'Done', 'cmb2' ), 'clearText' => esc_html__( 'Clear', 'cmb2' ), ), 'time_picker' => array( 'timeOnlyTitle' => esc_html__( 'Choose Time', 'cmb2' ), 'timeText' => esc_html__( 'Time', 'cmb2' ), 'hourText' => esc_html__( 'Hour', 'cmb2' ), 'minuteText' => esc_html__( 'Minute', 'cmb2' ), 'secondText' => esc_html__( 'Second', 'cmb2' ), 'currentText' => esc_html__( 'Now', 'cmb2' ), 'closeText' => esc_html__( 'Done', 'cmb2' ), 'timeFormat' => _x( 'hh:mm TT', 'Valid formatting string, as per http://trentrichardson.com/examples/timepicker/', 'cmb2' ), 'controlType' => 'select', 'stepMinute' => 5, ), ), 'strings' => array( 'upload_file' => esc_html__( 'Use this file', 'cmb2' ), 'upload_files' => esc_html__( 'Use these files', 'cmb2' ), 'remove_image' => esc_html__( 'Remove Image', 'cmb2' ), 'remove_file' => esc_html__( 'Remove', 'cmb2' ), 'file' => esc_html__( 'File:', 'cmb2' ), 'download' => esc_html__( 'Download', 'cmb2' ), 'check_toggle' => esc_html__( 'Select / Deselect All', 'cmb2' ), ), ); if ( isset( self::$dependencies['code-editor'] ) && function_exists( 'wp_enqueue_code_editor' ) ) { $l10n['defaults']['code_editor'] = wp_enqueue_code_editor( array( 'type' => 'text/html', ) ); } wp_localize_script( self::$handle, self::$js_variable, apply_filters( 'cmb2_localized_data', $l10n ) ); } } cmb2/cmb2/includes/types/CMB2_Type_File_List.php 0000644 00000004426 15151523432 0015322 0 ustar 00 <?php /** * CMB file_list field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_File_List extends CMB2_Type_File_Base { public function render( $args = array() ) { $field = $this->field; $meta_value = $field->escaped_value(); $name = $this->_name(); $img_size = $field->args( 'preview_size' ); $query_args = $field->args( 'query_args' ); $output = ''; // get an array of image size meta data, fallback to 'thumbnail' $img_size_data = parent::get_image_size_data( $img_size, 'thumbnail' ); $output .= parent::render( array( 'type' => 'hidden', 'class' => 'cmb2-upload-file cmb2-upload-list', 'size' => 45, 'desc' => '', 'value' => '', 'data-previewsize' => sprintf( '[%d,%d]', $img_size_data['width'], $img_size_data['height'] ), 'data-sizename' => $img_size_data['name'], 'data-queryargs' => ! empty( $query_args ) ? json_encode( $query_args ) : '', 'js_dependencies' => 'media-editor', ) ); $output .= parent::render( array( 'type' => 'button', 'class' => 'cmb2-upload-button button-secondary cmb2-upload-list', 'value' => esc_attr( $this->_text( 'add_upload_files_text', esc_html__( 'Add or Upload Files', 'cmb2' ) ) ), 'name' => false, 'id' => false, ) ); $output .= '<ul id="' . $this->_id( '-status', false ) . '" class="cmb2-media-status cmb-attach-list">'; if ( $meta_value && is_array( $meta_value ) ) { foreach ( $meta_value as $id => $fullurl ) { $id_input = parent::render( array( 'type' => 'hidden', 'value' => $fullurl, 'name' => $name . '[' . $id . ']', 'id' => 'filelist-' . $id, 'data-id' => $id, 'desc' => '', 'class' => false, ) ); if ( $this->is_valid_img_ext( $fullurl ) ) { $output .= $this->img_status_output( array( 'image' => wp_get_attachment_image( $id, $img_size ), 'tag' => 'li', 'id_input' => $id_input, ) ); } else { $output .= $this->file_status_output( array( 'value' => $fullurl, 'tag' => 'li', 'id_input' => $id_input, ) ); } } } $output .= '</ul>'; return $this->rendered( $output ); } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Radio.php 0000644 00000004222 15151523432 0016376 0 ustar 00 <?php /** * CMB taxonomy_radio field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Taxonomy_Radio extends CMB2_Type_Taxonomy_Base { protected $counter = 0; public function render() { return $this->rendered( $this->types->radio( array( 'options' => $this->get_term_options(), ), 'taxonomy_radio' ) ); } protected function get_term_options() { $all_terms = $this->get_terms(); if ( ! $all_terms || is_wp_error( $all_terms ) ) { return $this->no_terms_result( $all_terms ); } $saved_term = $this->get_object_term_or_default(); $option_none = $this->field->args( 'show_option_none' ); $options = ''; if ( ! empty( $option_none ) ) { $field_id = $this->_id( '', false ); /** * Default (option-none) taxonomy-radio value. * * @since 1.3.0 * * @param string $option_none_value Default (option-none) taxonomy-radio value. */ $option_none_value = apply_filters( 'cmb2_taxonomy_radio_default_value', '' ); /** * Default (option-none) taxonomy-radio value. * * The dynamic portion of the hook name, $field_id, refers to the field id attribute. * * @since 1.3.0 * * @param string $option_none_value Default (option-none) taxonomy-radio value. */ $option_none_value = apply_filters( "cmb2_taxonomy_radio_{$field_id}_default_value", $option_none_value ); $options .= $this->list_term_input( (object) array( 'slug' => $option_none_value, 'name' => $option_none, ), $saved_term ); } $options .= $this->loop_terms( $all_terms, $saved_term ); return $options; } protected function loop_terms( $all_terms, $saved_term ) { $options = ''; foreach ( $all_terms as $term ) { $options .= $this->list_term_input( $term, $saved_term ); } return $options; } protected function list_term_input( $term, $saved_term ) { $args = array( 'value' => $term->slug, 'label' => $term->name, ); if ( $saved_term == $term->slug ) { $args['checked'] = 'checked'; } return $this->list_input( $args, ++$this->counter ); } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Radio_Hierarchical.php 0000644 00000001512 15151523432 0021033 0 ustar 00 <?php /** * CMB taxonomy_radio_hierarchical field type * * @since 2.2.5 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Taxonomy_Radio_Hierarchical extends CMB2_Type_Taxonomy_Radio { /** * Parent term ID when looping hierarchical terms. * * @var integer */ protected $parent = 0; public function render() { return $this->rendered( $this->types->radio( array( 'options' => $this->get_term_options(), ), 'taxonomy_radio_hierarchical' ) ); } protected function list_term_input( $term, $saved_term ) { $options = parent::list_term_input( $term, $saved_term ); $children = $this->build_children( $term, $saved_term ); if ( ! empty( $children ) ) { $options .= $children; } return $options; } } cmb2/cmb2/includes/types/CMB2_Type_Text_Datetime_Timestamp.php 0000644 00000004526 15151523432 0020234 0 ustar 00 <?php /** * CMB text_datetime_timestamp field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Text_Datetime_Timestamp extends CMB2_Type_Picker_Base { public function render( $args = array() ) { $field = $this->field; $value = $field->escaped_value(); if ( empty( $value ) ) { $value = $field->get_default(); } $args = wp_parse_args( $this->args, array( 'value' => $value, 'desc' => $this->_desc(), 'datepicker' => array(), 'timepicker' => array(), ) ); if ( empty( $args['value'] ) ) { $args['value'] = $value; // This will be used if there is a select_timezone set for this field $tz_offset = $field->field_timezone_offset(); if ( ! empty( $tz_offset ) ) { $args['value'] -= $tz_offset; } } $has_good_value = ! empty( $args['value'] ) && ! is_array( $args['value'] ); $date_input = parent::render( $this->date_args( $args, $has_good_value ) ); $time_input = parent::render( $this->time_args( $args, $has_good_value ) ); return $this->rendered( $date_input . "\n" . $time_input ); } public function date_args( $args, $has_good_value ) { $date_args = wp_parse_args( $args['datepicker'], array( 'class' => 'cmb2-text-small cmb2-datepicker', 'name' => $this->_name( '[date]' ), 'id' => $this->_id( '_date' ), 'value' => $has_good_value ? $this->field->get_timestamp_format( 'date_format', $args['value'] ) : '', 'desc' => '', ) ); $date_args['rendered'] = true; // Let's get the date-format, and set it up as a data attr for the field. return $this->parse_picker_options( 'date', $date_args ); } public function time_args( $args, $has_good_value ) { $time_args = wp_parse_args( $args['timepicker'], array( 'class' => 'cmb2-timepicker text-time', 'name' => $this->_name( '[time]' ), 'id' => $this->_id( '_time' ), 'value' => $has_good_value ? $this->field->get_timestamp_format( 'time_format', $args['value'] ) : '', 'desc' => $args['desc'], 'js_dependencies' => array( 'jquery-ui-core', 'jquery-ui-datepicker', 'jquery-ui-datetimepicker' ), ) ); $time_args['rendered'] = true; // Let's get the time-format, and set it up as a data attr for the field. return $this->parse_picker_options( 'time', $time_args ); } } cmb2/cmb2/includes/types/CMB2_Type_Colorpicker.php 0000644 00000005456 15151523432 0015730 0 ustar 00 <?php /** * CMB colorpicker field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Colorpicker extends CMB2_Type_Text { /** * The optional value for the colorpicker field * * @var string */ public $value = ''; /** * Constructor * * @since 2.2.2 * * @param CMB2_Types $types Object for the field type. * @param array $args Array of arguments for the type. * @param string $value Value that the field type is currently set to, or default value. */ public function __construct( CMB2_Types $types, $args = array(), $value = '' ) { parent::__construct( $types, $args ); $this->value = $value ? $value : $this->value; } /** * Render the field for the field type. * * @since 2.2.2 * * @param array $args Array of arguments for the rendering. * * @return CMB2_Type_Base|string */ public function render( $args = array() ) { $meta_value = $this->value ? $this->value : $this->field->escaped_value(); $meta_value = self::sanitize_color( $meta_value ); wp_enqueue_style( 'wp-color-picker' ); $args = wp_parse_args( $args, array( 'class' => 'cmb2-text-small', ) ); $args['class'] .= ' cmb2-colorpicker'; $args['value'] = $meta_value; $args['js_dependencies'] = array( 'wp-color-picker' ); if ( $this->field->options( 'alpha' ) ) { $args['js_dependencies'][] = 'wp-color-picker-alpha'; $args['data-alpha'] = 'true'; } $args = wp_parse_args( $this->args, $args ); return parent::render( $args ); } /** * Sanitizes the given color, or array of colors. * * @since 2.9.0 * * @param string|array $color The color or array of colors to sanitize. * * @return string|array The color or array of colors, sanitized. */ public static function sanitize_color( $color ) { if ( is_array( $color ) ) { $color = array_map( array( 'CMB2_Type_Colorpicker', 'sanitize_color' ), $color ); } else { // Regexp for hexadecimal colors $hex_color = '(([a-fA-F0-9]){3}){1,2}$'; if ( preg_match( '/^' . $hex_color . '/i', $color ) ) { // Value is just 123abc, so prepend # $color = '#' . $color; } elseif ( // If value doesn't match #123abc... ! preg_match( '/^#' . $hex_color . '/i', $color ) // And value doesn't match rgba()... && 0 !== strpos( trim( $color ), 'rgba' ) ) { // Then sanitize to just #. $color = '#'; } } return $color; } /** * Provide the option to use a rgba colorpicker. * * @since 2.2.6.2 */ public static function dequeue_rgba_colorpicker_script() { if ( wp_script_is( 'jw-cmb2-rgba-picker-js', 'enqueued' ) ) { wp_dequeue_script( 'jw-cmb2-rgba-picker-js' ); CMB2_JS::register_colorpicker_alpha( true ); } } } cmb2/cmb2/includes/types/CMB2_Type_Oembed.php 0000644 00000002011 15151523432 0014627 0 ustar 00 <?php /** * CMB oembed field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Oembed extends CMB2_Type_Text { public function render( $args = array() ) { $field = $this->field; $meta_value = trim( $field->escaped_value() ); $oembed = ! empty( $meta_value ) ? cmb2_ajax()->get_oembed( array( 'url' => $field->escaped_value(), 'object_id' => $field->object_id, 'object_type' => $field->object_type, 'oembed_args' => array( 'width' => '640', ), 'field_id' => $this->_id( '', false ), ) ) : ''; return parent::render( array( 'class' => 'cmb2-oembed regular-text', 'data-objectid' => $field->object_id, 'data-objecttype' => $field->object_type, ) ) . '<p class="cmb-spinner spinner"></p>' . '<div id="' . $this->_id( '-status' ) . '" class="cmb2-media-status ui-helper-clearfix embed_wrap">' . $oembed . '</div>'; } } cmb2/cmb2/includes/types/CMB2_Type_Text_Time.php 0000644 00000001222 15151523432 0015341 0 ustar 00 <?php /** * CMB text_time field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Text_Time extends CMB2_Type_Text_Date { public function render( $args = array() ) { $this->args = $this->parse_picker_options( 'time', wp_parse_args( $this->args, array( 'class' => 'cmb2-timepicker text-time', 'value' => $this->field->get_timestamp_format( 'time_format' ), 'js_dependencies' => array( 'jquery-ui-core', 'jquery-ui-datepicker', 'jquery-ui-datetimepicker' ), ) ) ); return parent::render(); } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Multicheck.php 0000644 00000003421 15151523432 0017430 0 ustar 00 <?php /** * CMB taxonomy_multicheck field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Taxonomy_Multicheck extends CMB2_Type_Taxonomy_Base { protected $counter = 0; public function render() { return $this->rendered( $this->types->radio( array( 'class' => $this->get_wrapper_classes(), 'options' => $this->get_term_options(), ), 'taxonomy_multicheck' ) ); } protected function get_term_options() { $all_terms = $this->get_terms(); if ( ! $all_terms || is_wp_error( $all_terms ) ) { return $this->no_terms_result( $all_terms ); } return $this->loop_terms( $all_terms, $this->get_object_term_or_default() ); } protected function loop_terms( $all_terms, $saved_terms ) { $options = ''; foreach ( $all_terms as $term ) { $options .= $this->list_term_input( $term, $saved_terms ); } return $options; } protected function list_term_input( $term, $saved_terms ) { $args = array( 'value' => $term->slug, 'label' => $term->name, 'type' => 'checkbox', 'name' => $this->_name() . '[]', ); if ( is_array( $saved_terms ) && in_array( $term->slug, $saved_terms ) ) { $args['checked'] = 'checked'; } return $this->list_input( $args, ++$this->counter ); } public function get_object_term_or_default() { $saved_terms = $this->get_object_terms(); return is_wp_error( $saved_terms ) || empty( $saved_terms ) ? $this->field->get_default() : wp_list_pluck( $saved_terms, 'slug' ); } protected function get_wrapper_classes() { $classes = 'cmb2-checkbox-list cmb2-list'; if ( false === $this->field->args( 'select_all_button' ) ) { $classes .= ' no-select-all'; } return $classes; } } cmb2/cmb2/includes/types/CMB2_Type_File_Base.php 0000644 00000020676 15151523432 0015266 0 ustar 00 <?php /** * CMB File base field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_File_Base extends CMB2_Type_Text { /** * Determines if a file has a valid image extension * * @since 1.0.0 * @param string $file File url * @return bool Whether file has a valid image extension */ public function is_valid_img_ext( $file, $blah = false ) { $file_ext = CMB2_Utils::get_file_ext( $file ); $valid_types = array( 'jpg', 'jpeg', 'jpe', 'png', 'gif', 'ico', 'icon' ); $allowed = get_allowed_mime_types(); if ( ! empty( $allowed ) ) { foreach ( (array) $allowed as $type => $mime) { if ( 0 === strpos( $mime, 'image/' ) ) { $types = explode( '|', $type ); $valid_types = array_merge( $valid_types, $types ); } } $valid_types = array_unique( $valid_types ); } /** * Which image types are considered valid image file extensions. * * @since 2.0.9 * * @param array $valid_types The valid image file extensions. */ $is_valid_types = apply_filters( 'cmb2_valid_img_types', $valid_types ); $is_valid = $file_ext && in_array( $file_ext, (array) $is_valid_types ); $field_id = $this->field->id(); /** * Filter for determining if a field value has a valid image file-type extension. * * The dynamic portion of the hook name, $field_id, refers to the field id attribute. * * @since 2.0.9 * * @param bool $is_valid Whether field value has a valid image file-type extension. * @param string $file File url. * @param string $file_ext File extension. */ return (bool) apply_filters( "cmb2_{$field_id}_is_valid_img_ext", $is_valid, $file, $file_ext ); } /** * file/file_list image wrap * * @since 2.0.2 * @param array $args Array of arguments for output * @return string Image wrap output */ public function img_status_output( $args ) { return sprintf( '<%1$s class="img-status cmb2-media-item">%2$s<p class="cmb2-remove-wrapper"><a href="#" class="cmb2-remove-file-button"%3$s>%4$s</a></p>%5$s</%1$s>', $args['tag'], $args['image'], isset( $args['cached_id'] ) ? ' rel="' . esc_attr( $args['cached_id'] ) . '"' : '', esc_html( $this->_text( 'remove_image_text', esc_html__( 'Remove Image', 'cmb2' ) ) ), isset( $args['id_input'] ) ? $args['id_input'] : '' ); } /** * file/file_list file wrap * * @since 2.0.2 * @param array $args Array of arguments for output * @return string File wrap output */ public function file_status_output( $args ) { return sprintf( '<%1$s class="file-status cmb2-media-item"><span>%2$s <strong>%3$s</strong></span> (<a href="%4$s" target="_blank" rel="external">%5$s</a> / <a href="#" class="cmb2-remove-file-button"%6$s>%7$s</a>)%8$s</%1$s>', $args['tag'], esc_html( $this->_text( 'file_text', esc_html__( 'File:', 'cmb2' ) ) ), esc_html( CMB2_Utils::get_file_name_from_path( $args['value'] ) ), esc_url( $args['value'] ), esc_html( $this->_text( 'file_download_text', esc_html__( 'Download', 'cmb2' ) ) ), isset( $args['cached_id'] ) ? ' rel="' . esc_attr( $args['cached_id'] ) . '"' : '', esc_html( $this->_text( 'remove_text', esc_html__( 'Remove', 'cmb2' ) ) ), isset( $args['id_input'] ) ? $args['id_input'] : '' ); } /** * Outputs the file/file_list underscore Javascript templates in the footer. * * @since 2.2.4 * @return void */ public static function output_js_underscore_templates() { ?> <script type="text/html" id="tmpl-cmb2-single-image"> <div class="img-status cmb2-media-item"> <img width="{{ data.sizeWidth }}" height="{{ data.sizeHeight }}" src="{{ data.sizeUrl }}" class="cmb-file-field-image" alt="{{ data.filename }}" title="{{ data.filename }}" /> <p><a href="#" class="cmb2-remove-file-button" rel="{{ data.mediaField }}">{{ data.stringRemoveImage }}</a></p> </div> </script> <script type="text/html" id="tmpl-cmb2-single-file"> <div class="file-status cmb2-media-item"> <span>{{ data.stringFile }} <strong>{{ data.filename }}</strong></span> (<a href="{{ data.url }}" target="_blank" rel="external">{{ data.stringDownload }}</a> / <a href="#" class="cmb2-remove-file-button" rel="{{ data.mediaField }}">{{ data.stringRemoveFile }}</a>) </div> </script> <script type="text/html" id="tmpl-cmb2-list-image"> <li class="img-status cmb2-media-item"> <img width="{{ data.sizeWidth }}" height="{{ data.sizeHeight }}" src="{{ data.sizeUrl }}" class="cmb-file_list-field-image" alt="{{ data.filename }}"> <p><a href="#" class="cmb2-remove-file-button" rel="{{ data.mediaField }}[{{ data.id }}]">{{ data.stringRemoveImage }}</a></p> <input type="hidden" id="filelist-{{ data.id }}" data-id="{{ data.id }}" name="{{ data.mediaFieldName }}[{{ data.id }}]" value="{{ data.url }}"> </li> </script> <script type="text/html" id="tmpl-cmb2-list-file"> <li class="file-status cmb2-media-item"> <span>{{ data.stringFile }} <strong>{{ data.filename }}</strong></span> (<a href="{{ data.url }}" target="_blank" rel="external">{{ data.stringDownload }}</a> / <a href="#" class="cmb2-remove-file-button" rel="{{ data.mediaField }}[{{ data.id }}]">{{ data.stringRemoveFile }}</a>) <input type="hidden" id="filelist-{{ data.id }}" data-id="{{ data.id }}" name="{{ data.mediaFieldName }}[{{ data.id }}]" value="{{ data.url }}"> </li> </script> <?php } /** * Utility method to return an array of meta data for a registered image size * * Uses CMB2_Utils::get_named_size() to get the closest available named size * from an array of width and height values and CMB2_Utils::get_available_image_sizes() * to get the meta data associated with a named size. * * @since 2.2.4 * @param array|string $img_size Image size. Accepts an array of width and height (in that order) * @param string $fallback Size to use if the supplied named size doesn't exist * @return array Array containing the image size meta data * $size = ( * 'width' => (int) image size width * 'height' => (int) image size height * 'name' => (string) e.g. 'thumbnail' * ) */ static function get_image_size_data( $img_size = '', $fallback = 'thumbnail' ) { $data = array(); if ( is_array( $img_size ) ) { $data['width'] = intval( $img_size[0] ); $data['height'] = intval( $img_size[1] ); $data['name'] = ''; // Try and get the closest named size from our array of dimensions if ( $named_size = CMB2_Utils::get_named_size( $img_size ) ) { $data['name'] = $named_size; } } else { $image_sizes = CMB2_Utils::get_available_image_sizes(); // The 'thumb' alias, which works elsewhere, doesn't work in the wp.media uploader if ( 'thumb' == $img_size ) { $img_size = 'thumbnail'; } // Named size doesn't exist, use $fallback if ( ! array_key_exists( $img_size, $image_sizes ) ) { $img_size = $fallback; } // Get image dimensions from named sizes $data['width'] = intval( $image_sizes[ $img_size ]['width'] ); $data['height'] = intval( $image_sizes[ $img_size ]['height'] ); $data['name'] = $img_size; } return $data; } /** * Filters attachment data prepared for JavaScript. * * Adds the url, width, height, and orientation for custom sizes to the JavaScript * object returned by the wp.media uploader. Hooked to 'wp_prepare_attachment_for_js'. * * @since 2.2.4 * @param array $response Array of prepared attachment data * @param int|object $attachment Attachment ID or object * @param array $meta Array of attachment meta data ( from wp_get_attachment_metadata() ) * @return array filtered $response array */ public static function prepare_image_sizes_for_js( $response, $attachment, $meta ) { foreach ( CMB2_Utils::get_available_image_sizes() as $size => $info ) { // registered image size exists for this attachment if ( isset( $meta['sizes'][ $size ] ) ) { $attachment_url = wp_get_attachment_url( $attachment->ID ); $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url ); $size_meta = $meta['sizes'][ $size ]; $response['sizes'][ $size ] = array( 'url' => $base_url . $size_meta['file'], 'height' => $size_meta['height'], 'width' => $size_meta['width'], 'orientation' => $size_meta['height'] > $size_meta['width'] ? 'portrait' : 'landscape', ); } } return $response; } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Base.php 0000644 00000011237 15151523432 0016216 0 ustar 00 <?php /** * CMB Taxonomy base field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ abstract class CMB2_Type_Taxonomy_Base extends CMB2_Type_Multi_Base { /** * Parent term ID when looping hierarchical terms. * * @var integer|null */ protected $parent = null; /** * Checks if we can get a post object, and if so, uses `get_the_terms` which utilizes caching. * * @since 1.0.2 * @return mixed Array of terms on success */ public function get_object_terms() { switch ( $this->field->object_type ) { case 'options-page': case 'term': return $this->options_terms(); case 'post': // WP caches internally so it's better to use return get_the_terms( $this->field->object_id, $this->field->args( 'taxonomy' ) ); default: return $this->non_post_object_terms(); } } /** * Gets the term objects for the terms stored via options boxes. * * @since 2.2.4 * @return mixed Array of terms on success */ public function options_terms() { if ( empty( $this->field->value ) ) { return array(); } $terms = (array) $this->field->value; foreach ( $terms as $index => $term ) { $terms[ $index ] = get_term_by( 'slug', $term, $this->field->args( 'taxonomy' ) ); } return $terms; } /** * For non-post objects, wraps the call to wp_get_object_terms with transient caching. * * @since 2.2.4 * @return mixed Array of terms on success */ public function non_post_object_terms() { $object_id = $this->field->object_id; $taxonomy = $this->field->args( 'taxonomy' ); $cache_key = "cmb-cache-{$taxonomy}-{$object_id}"; // Check cache $cached = get_transient( $cache_key ); if ( ! $cached ) { $cached = wp_get_object_terms( $object_id, $taxonomy ); // Do our own (minimal) caching. Long enough for a page-load. set_transient( $cache_key, $cached, 60 ); } return $cached; } /** * Wrapper for `get_terms` to account for changes in WP 4.6 where taxonomy is expected * as part of the arguments. * * @since 2.2.2 * @return mixed Array of terms on success */ public function get_terms() { $args = array( 'taxonomy' => $this->field->args( 'taxonomy' ), 'hide_empty' => false, ); if ( null !== $this->parent ) { $args['parent'] = $this->parent; } $args = wp_parse_args( $this->field->prop( 'query_args', array() ), $args ); return CMB2_Utils::wp_at_least( '4.5.0' ) ? get_terms( $args ) : get_terms( $this->field->args( 'taxonomy' ), http_build_query( $args ) ); } protected function no_terms_result( $error, $tag = 'li' ) { if ( is_wp_error( $error ) ) { $message = $error->get_error_message(); $data = 'data-error="' . esc_attr( $error->get_error_code() ) . '"'; } else { $message = $this->_text( 'no_terms_text', esc_html__( 'No terms', 'cmb2' ) ); $data = ''; } $this->field->args['select_all_button'] = false; return sprintf( '<%3$s><label %1$s>%2$s</label></%3$s>', $data, esc_html( $message ), $tag ); } public function get_object_term_or_default() { $saved_terms = $this->get_object_terms(); return is_wp_error( $saved_terms ) || empty( $saved_terms ) ? $this->field->get_default() : array_shift( $saved_terms )->slug; } /** * Takes a list of all tax terms and outputs. * * @since 2.2.5 * * @param array $all_terms Array of all terms. * @param array|string $saved Array of terms set to the object, or single term slug. * * @return string List of terms. */ protected function loop_terms( $all_terms, $saved_terms ) { return ''; } /** * Build children hierarchy. * * @param object $parent_term The parent term object. * @param array|string $saved Array of terms set to the object, or single term slug. * * @return string List of terms. */ protected function build_children( $parent_term, $saved ) { if ( empty( $parent_term->term_id ) ) { return ''; } $this->parent = $parent_term->term_id; $terms = $this->get_terms(); $options = ''; if ( ! empty( $terms ) && is_array( $terms ) ) { $options .= $this->child_option_output( $terms, $saved ); } return $options; } /** * Build child terms output. * * @since 2.6.1 * * @param array $terms Array of child terms. * @param array|string $saved Array of terms set to the object, or single term slug. * * @return string Child option output. */ public function child_option_output( $terms, $saved ) { $output = '<li class="cmb2-indented-hierarchy"><ul>'; $output .= $this->loop_terms( $terms, $saved ); $output .= '</ul></li>'; return $output; } } cmb2/cmb2/includes/types/CMB2_Type_Checkbox.php 0000644 00000003005 15151523432 0015166 0 ustar 00 <?php /** * CMB checkbox field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Checkbox extends CMB2_Type_Text { /** * If checkbox is checked * * @var mixed */ public $is_checked = null; /** * Constructor * * @since 2.2.2 * * @param CMB2_Types $types Object for the field type. * @param array $args Array of arguments for the type. * @param mixed $is_checked Whether or not the field is checked, or default value. */ public function __construct( CMB2_Types $types, $args = array(), $is_checked = null ) { parent::__construct( $types, $args ); $this->is_checked = $is_checked; } /** * Render the field for the field type. * * @since 2.2.2 * * @param array $args Array of arguments for the rendering. * @return CMB2_Type_Base|string */ public function render( $args = array() ) { $defaults = array( 'type' => 'checkbox', 'class' => 'cmb2-option cmb2-list', 'value' => 'on', 'desc' => '', ); $meta_value = $this->field->escaped_value(); $is_checked = null === $this->is_checked ? ! empty( $meta_value ) : $this->is_checked; if ( $is_checked ) { $defaults['checked'] = 'checked'; } $args = $this->parse_args( 'checkbox', $defaults ); return $this->rendered( sprintf( '%s <label for="%s">%s</label>', parent::render( $args ), $this->_id( '', false ), $this->_desc() ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Title.php 0000644 00000001745 15151523432 0014532 0 ustar 00 <?php /** * CMB title field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Title extends CMB2_Type_Base { /** * Handles outputting an 'title' element * * @return string Heading element */ public function render() { $name = $this->field->args( 'name' ); $tag = 'span'; if ( ! empty( $name ) ) { $tag = $this->field->object_type == 'post' ? 'h5' : 'h3'; } $a = $this->parse_args( 'title', array( 'tag' => $tag, 'class' => empty( $name ) ? 'cmb2-metabox-title-anchor' : 'cmb2-metabox-title', 'name' => $name, 'desc' => $this->_desc( true ), 'id' => str_replace( '_', '-', sanitize_html_class( $this->field->id() ) ), ) ); return $this->rendered( sprintf( '<%1$s %2$s>%3$s</%1$s>%4$s', $a['tag'], $this->concat_attrs( $a, array( 'tag', 'name', 'desc' ) ), $a['name'], $a['desc'] ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Radio.php 0000644 00000002034 15151523432 0014477 0 ustar 00 <?php /** * CMB radio field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Radio extends CMB2_Type_Multi_Base { /** * The type of radio field * * @var string */ public $type = 'radio'; /** * Constructor * * @since 2.2.2 * * @param CMB2_Types $types * @param array $args */ public function __construct( CMB2_Types $types, $args = array(), $type = '' ) { parent::__construct( $types, $args ); $this->type = $type ? $type : $this->type; } public function render() { $args = $this->parse_args( $this->type, array( 'class' => 'cmb2-radio-list cmb2-list', 'options' => $this->concat_items( array( 'label' => 'test', 'method' => 'list_input', ) ), 'desc' => $this->_desc( true ), ) ); return $this->rendered( $this->ul( $args ) ); } protected function ul( $a ) { return sprintf( '<ul class="%s">%s</ul>%s', $a['class'], $a['options'], $a['desc'] ); } } cmb2/cmb2/includes/types/CMB2_Type_Text_Date.php 0000644 00000001340 15151523432 0015321 0 ustar 00 <?php /** * CMB text_date field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Text_Date extends CMB2_Type_Picker_Base { public function render( $args = array() ) { $args = $this->parse_args( 'text_date', array( 'class' => 'cmb2-text-small cmb2-datepicker', 'value' => $this->field->get_timestamp_format(), 'desc' => $this->_desc(), 'js_dependencies' => array( 'jquery-ui-core', 'jquery-ui-datepicker' ), ) ); if ( false === strpos( $args['class'], 'timepicker' ) ) { $this->parse_picker_options( 'date' ); } return parent::render( $args ); } } cmb2/cmb2/includes/types/CMB2_Type_Text_Datetime_Timestamp_Timezone.php 0000644 00000003323 15151523432 0022100 0 ustar 00 <?php /** * CMB text_datetime_timestamp_timezone field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Text_Datetime_Timestamp_Timezone extends CMB2_Type_Base { public function render( $args = array() ) { $field = $this->field; $value = $field->escaped_value(); if ( empty( $value ) ) { $value = $field->get_default(); } $args = wp_parse_args( $this->args, array( 'value' => $value, 'desc' => $this->_desc( true ), 'text_datetime_timestamp' => array(), 'select_timezone' => array(), ) ); $args['value'] = $value; if ( is_array( $args['value'] ) ) { $args['value'] = ''; } $datetime = CMB2_Utils::get_datetime_from_value( $args['value'] ); $value = ''; $tzstring = ''; if ( $datetime && $datetime instanceof DateTime ) { $tzstring = $datetime->getTimezone()->getName(); $value = $datetime->getTimestamp(); } $timestamp_args = wp_parse_args( $args['text_datetime_timestamp'], array( 'desc' => '', 'value' => $value, 'rendered' => true, ) ); $datetime_timestamp = $this->types->text_datetime_timestamp( $timestamp_args ); $timezone_select_args = wp_parse_args( $args['select_timezone'], array( 'class' => 'cmb2_select cmb2-select-timezone', 'name' => $this->_name( '[timezone]' ), 'id' => $this->_id( '_timezone' ), 'options' => wp_timezone_choice( $tzstring ), 'desc' => $args['desc'], 'rendered' => true, ) ); $select = $this->types->select( $timezone_select_args ); return $this->rendered( $datetime_timestamp . "\n" . $select ); } } cmb2/cmb2/includes/types/CMB2_Type_Wysiwyg.php 0000644 00000006420 15151523432 0015126 0 ustar 00 <?php /** * CMB wysiwyg field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @method string _id() * @method string _desc() */ class CMB2_Type_Wysiwyg extends CMB2_Type_Textarea { /** * Handles outputting a 'wysiwyg' element * @since 1.1.0 * @return string Form wysiwyg element */ public function render( $args = array() ) { $field = $this->field; $a = $this->parse_args( 'wysiwyg', array( 'id' => $this->_id( '', false ), 'value' => $field->escaped_value( 'stripslashes' ), 'desc' => $this->_desc( true ), 'options' => $field->options(), ) ); if ( ! $field->group ) { $a = $this->maybe_update_attributes_for_char_counter( $a ); if ( $this->has_counter ) { $a['options']['editor_class'] = ! empty( $a['options']['editor_class'] ) ? $a['options']['editor_class'] . ' cmb2-count-chars' : 'cmb2-count-chars'; } return $this->rendered( $this->get_wp_editor( $a ) . $a['desc'] ); } // Character counter not currently working for grouped WYSIWYG $this->field->args['char_counter'] = false; // wysiwyg fields in a group need some special handling. $field->add_js_dependencies( array( 'wp-util', 'cmb2-wysiwyg' ) ); // Hook in our template-output to the footer. add_action( is_admin() ? 'admin_footer' : 'wp_footer', array( $this, 'add_wysiwyg_template_for_group' ) ); return $this->rendered( sprintf( '<div class="cmb2-wysiwyg-wrap">%s', parent::render( array( 'class' => 'cmb2_textarea cmb2-wysiwyg-placeholder', 'data-groupid' => $field->group->id(), 'data-iterator' => $field->group->index, 'data-fieldid' => $field->id( true ), 'desc' => '</div>' . $this->_desc( true ), ) ) ) ); } protected function get_wp_editor( $args ) { ob_start(); wp_editor( $args['value'], $args['id'], $args['options'] ); return ob_get_clean(); } public function add_wysiwyg_template_for_group() { $group_id = $this->field->group->id(); $field_id = $this->field->id( true ); $hash = $this->field->hash_id(); $options = $this->field->options(); $options['textarea_name'] = 'cmb2_n_' . $group_id . $field_id; // Initate the editor with special id/value/name so we can retrieve the options in JS. $editor = $this->get_wp_editor( array( 'value' => 'cmb2_v_' . $group_id . $field_id, 'id' => 'cmb2_i_' . $group_id . $field_id, 'options' => $options, ) ); // Then replace the special id/value/name with underscore placeholders. $editor = str_replace( array( 'cmb2_n_' . $group_id . $field_id, 'cmb2_v_' . $group_id . $field_id, 'cmb2_i_' . $group_id . $field_id, ), array( '{{ data.name }}', '{{{ data.value }}}', '{{ data.id }}', ), $editor ); // And put the editor instance in a JS template wrapper. echo '<script type="text/template" id="tmpl-cmb2-wysiwyg-' . $group_id . '-' . $field_id . '">'; // Need to wrap the template in a wrapper div w/ specific data attributes which will be used when adding/removing rows. echo '<div class="cmb2-wysiwyg-inner-wrap" data-iterator="{{ data.iterator }}" data-groupid="' . $group_id . '" data-id="' . $field_id . '" data-hash="' . $hash . '">' . $editor . '</div>'; echo '</script>'; } } cmb2/cmb2/includes/types/CMB2_Type_Select.php 0000644 00000001237 15151523432 0014664 0 ustar 00 <?php /** * CMB select field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Select extends CMB2_Type_Multi_Base { public function render() { $a = $this->parse_args( 'select', array( 'class' => 'cmb2_select', 'name' => $this->_name(), 'id' => $this->_id(), 'desc' => $this->_desc( true ), 'options' => $this->concat_items(), ) ); $attrs = $this->concat_attrs( $a, array( 'desc', 'options' ) ); return $this->rendered( sprintf( '<select%s>%s</select>%s', $attrs, $a['options'], $a['desc'] ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Select_Hierarchical.php 0000644 00000002754 15151523433 0021226 0 ustar 00 <?php /** * CMB taxonomy_select_hierarchical field type * * @since 2.6.1 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Taxonomy_Select_Hierarchical extends CMB2_Type_Taxonomy_Select { /** * Parent term ID when looping hierarchical terms. * * @since 2.6.1 * * @var integer */ protected $parent = 0; /** * Child loop depth. * * @since 2.6.1 * * @var integer */ protected $level = 0; public function render() { return $this->rendered( $this->types->select( array( 'options' => $this->get_term_options(), ), 'taxonomy_select_hierarchical' ) ); } public function select_option( $args = array() ) { if ( $this->level > 0 ) { $args['label'] = str_repeat( ' ', $this->level ) . $args['label']; } $option = parent::select_option( $args ); $children = $this->build_children( $this->current_term, $this->saved_term ); if ( ! empty( $children ) ) { $option .= $children; } return $option; } /** * Build children hierarchy. * * @since 2.6.1 * * @param array $terms Array of child terms. * @param array|string $saved Array of terms set to the object, or single term slug. * * @return string Child option output. */ public function child_option_output( $terms, $saved ) { $this->level++; $output = $this->loop_terms( $terms, $saved ); $this->level--; return $output; } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Select.php 0000644 00000004407 15151523433 0016565 0 ustar 00 <?php /** * CMB taxonomy_select field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Taxonomy_Select extends CMB2_Type_Taxonomy_Base { /** * Current Term Object. * * @since 2.6.1 * * @var null|WP_Term */ public $current_term = null; /** * Saved Term Object. * * @since 2.6.1 * * @var null|WP_Term */ public $saved_term = null; public function render() { return $this->rendered( $this->types->select( array( 'options' => $this->get_term_options(), ) ) ); } protected function get_term_options() { $all_terms = $this->get_terms(); if ( ! $all_terms || is_wp_error( $all_terms ) ) { return $this->no_terms_result( $all_terms, 'strong' ); } $this->saved_term = $this->get_object_term_or_default(); $option_none = $this->field->args( 'show_option_none' ); $options = ''; if ( ! empty( $option_none ) ) { $field_id = $this->_id( '', false ); /** * Default (option-none) taxonomy-select value. * * @since 1.3.0 * * @param string $option_none_value Default (option-none) taxonomy-select value. */ $option_none_value = apply_filters( 'cmb2_taxonomy_select_default_value', '' ); /** * Default (option-none) taxonomy-select value. * * The dynamic portion of the hook name, $field_id, refers to the field id attribute. * * @since 1.3.0 * * @param string $option_none_value Default (option-none) taxonomy-select value. */ $option_none_value = apply_filters( "cmb2_taxonomy_select_{$field_id}_default_value", $option_none_value ); $options .= $this->select_option( array( 'label' => $option_none, 'value' => $option_none_value, 'checked' => $this->saved_term == $option_none_value, ) ); } $options .= $this->loop_terms( $all_terms, $this->saved_term ); return $options; } protected function loop_terms( $all_terms, $saved_term ) { $options = ''; foreach ( $all_terms as $term ) { $this->current_term = $term; $options .= $this->select_option( array( 'label' => $term->name, 'value' => $term->slug, 'checked' => $this->saved_term === $term->slug, ) ); } return $options; } } cmb2/cmb2/includes/types/CMB2_Type_Picker_Base.php 0000644 00000002546 15151523433 0015621 0 ustar 00 <?php /** * CMB Picker base field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ abstract class CMB2_Type_Picker_Base extends CMB2_Type_Text { /** * Parse the picker attributes. * * @since 2.2.0 * @param string $arg 'date' or 'time' * @param array $args Optional arguments to modify (else use $this->field->args['attributes']) * @return array Array of field attributes */ public function parse_picker_options( $arg = 'date', $args = array() ) { $att = 'data-' . $arg . 'picker'; $update = empty( $args ); $atts = array(); $format = $this->field->args( $arg . '_format' ); if ( $js_format = CMB2_Utils::php_to_js_dateformat( $format ) ) { if ( $update ) { $atts = $this->field->args( 'attributes' ); } else { $atts = isset( $args['attributes'] ) ? $args['attributes'] : $atts; } // Don't override user-provided datepicker values $data = isset( $atts[ $att ] ) ? json_decode( $atts[ $att ], true ) : array(); $data[ $arg . 'Format' ] = $js_format; $atts[ $att ] = function_exists( 'wp_json_encode' ) ? wp_json_encode( $data ) : json_encode( $data ); } if ( $update ) { $this->field->args['attributes'] = $atts; } return array_merge( $args, $atts ); } } cmb2/cmb2/includes/types/CMB2_Type_Taxonomy_Multicheck_Hierarchical.php 0000644 00000001620 15151523433 0022066 0 ustar 00 <?php /** * CMB taxonomy_multicheck_hierarchical field type * * @since 2.2.5 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Taxonomy_Multicheck_Hierarchical extends CMB2_Type_Taxonomy_Multicheck { /** * Parent term ID when looping hierarchical terms. * * @var integer */ protected $parent = 0; public function render() { return $this->rendered( $this->types->radio( array( 'class' => $this->get_wrapper_classes(), 'options' => $this->get_term_options(), ), 'taxonomy_multicheck_hierarchical' ) ); } protected function list_term_input( $term, $saved_terms ) { $options = parent::list_term_input( $term, $saved_terms ); $children = $this->build_children( $term, $saved_terms ); if ( ! empty( $children ) ) { $options .= $children; } return $options; } } cmb2/cmb2/includes/types/CMB2_Type_Multi_Base.php 0000644 00000005702 15151523433 0015473 0 ustar 00 <?php /** * CMB Multi base field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ abstract class CMB2_Type_Multi_Base extends CMB2_Type_Base { /** * Generates html for an option element * * @since 1.1.0 * @param array $args Arguments array containing value, label, and checked boolean * @return string Generated option element html */ public function select_option( $args = array() ) { return sprintf( "\t" . '<option value="%s" %s>%s</option>', $args['value'], selected( isset( $args['checked'] ) && $args['checked'], true, false ), $args['label'] ) . "\n"; } /** * Generates html for list item with input * * @since 1.1.0 * @param array $args Override arguments * @param int $i Iterator value * @return string Gnerated list item html */ public function list_input( $args = array(), $i = '' ) { $a = $this->parse_args( 'list_input', array( 'type' => 'radio', 'class' => 'cmb2-option', 'name' => $this->_name(), 'id' => $this->_id( $i ), 'value' => $this->field->escaped_value(), 'label' => '', ), $args ); return sprintf( "\t" . '<li><input%s/> <label for="%s">%s</label></li>' . "\n", $this->concat_attrs( $a, array( 'label' ) ), $a['id'], $a['label'] ); } /** * Generates html for list item with checkbox input * * @since 1.1.0 * @param array $args Override arguments * @param int $i Iterator value * @return string Gnerated list item html */ public function list_input_checkbox( $args, $i ) { $saved_value = $this->field->escaped_value(); if ( is_array( $saved_value ) && in_array( $args['value'], $saved_value ) ) { $args['checked'] = 'checked'; } $args['type'] = 'checkbox'; return $this->list_input( $args, $i ); } /** * Generates html for concatenated items * * @since 1.1.0 * @param array $args Optional arguments * @return string Concatenated html items */ public function concat_items( $args = array() ) { $field = $this->field; $method = isset( $args['method'] ) ? $args['method'] : 'select_option'; unset( $args['method'] ); $value = null !== $field->escaped_value() ? $field->escaped_value() : $field->get_default(); $value = CMB2_Utils::normalize_if_numeric( $value ); $concatenated_items = ''; $i = 1; $options = array(); if ( $option_none = $field->args( 'show_option_none' ) ) { $options[''] = $option_none; } $options = $options + (array) $field->options(); foreach ( $options as $opt_value => $opt_label ) { // Clone args & modify for just this item $a = $args; $a['value'] = $opt_value; $a['label'] = $opt_label; // Check if this option is the value of the input if ( $value === CMB2_Utils::normalize_if_numeric( $opt_value ) ) { $a['checked'] = 'checked'; } $concatenated_items .= $this->$method( $a, $i++ ); } return $concatenated_items; } } cmb2/cmb2/includes/types/CMB2_Type_Multicheck.php 0000644 00000001502 15151523433 0015531 0 ustar 00 <?php /** * CMB multicheck field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Multicheck extends CMB2_Type_Radio { /** * The type of radio field * * @var string */ public $type = 'checkbox'; public function render( $args = array() ) { $classes = false === $this->field->args( 'select_all_button' ) ? 'cmb2-checkbox-list no-select-all cmb2-list' : 'cmb2-checkbox-list cmb2-list'; $args = $this->parse_args( $this->type, array( 'class' => $classes, 'options' => $this->concat_items( array( 'name' => $this->_name() . '[]', 'method' => 'list_input_checkbox', ) ), 'desc' => $this->_desc( true ), ) ); return $this->rendered( $this->ul( $args ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Text.php 0000644 00000002601 15151523433 0014366 0 ustar 00 <?php /** * CMB text field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Text extends CMB2_Type_Counter_Base { /** * The type of field * * @var string */ public $type = 'input'; /** * Constructor * * @since 2.2.2 * * @param CMB2_Types $types * @param array $args */ public function __construct( CMB2_Types $types, $args = array(), $type = '' ) { parent::__construct( $types, $args ); $this->type = $type ? $type : $this->type; } /** * Handles outputting an 'input' element * * @since 1.1.0 * @param array $args Override arguments * @return string Form input element */ public function render( $args = array() ) { $args = empty( $args ) ? $this->args : $args; $a = $this->parse_args( $this->type, array( 'type' => 'text', 'class' => 'regular-text', 'name' => $this->_name(), 'id' => $this->_id(), 'value' => $this->field->escaped_value(), 'desc' => $this->_desc( true ), 'js_dependencies' => array(), ), $args ); // Add character counter? $a = $this->maybe_update_attributes_for_char_counter( $a ); return $this->rendered( sprintf( '<input%s/>%s', $this->concat_attrs( $a, array( 'desc' ) ), $a['desc'] ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Base.php 0000644 00000011215 15151523433 0014315 0 ustar 00 <?php /** * CMB base field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ abstract class CMB2_Type_Base { /** * The CMB2_Types object * * @var CMB2_Types */ public $types; /** * Arguments for use in the render method * * @var array */ public $args; /** * Rendered output (if 'rendered' argument is set to false) * * @var string */ protected $rendered = ''; /** * Constructor * * @since 2.2.2 * @param CMB2_Types $types Object for the field type. * @param array $args Array of arguments for the type. */ public function __construct( CMB2_Types $types, $args = array() ) { $this->types = $types; $args['rendered'] = isset( $args['rendered'] ) ? (bool) $args['rendered'] : true; $this->args = $args; } /** * Handles rendering this field type. * * @since 2.2.2 * @return string Rendered field type. */ abstract public function render(); /** * Stores the rendered field output. * * @since 2.2.2 * @param string|CMB2_Type_Base $rendered Rendered output. * @return string|CMB2_Type_Base Rendered output or this object. */ public function rendered( $rendered ) { $this->field->register_js_data(); if ( $this->args['rendered'] ) { return is_a( $rendered, __CLASS__ ) ? $rendered->rendered : $rendered; } $this->rendered = is_a( $rendered, __CLASS__ ) ? $rendered->rendered : $rendered; return $this; } /** * Returns the stored rendered field output. * * @since 2.2.2 * @return string Stored rendered output (if 'rendered' argument is set to false). */ public function get_rendered() { return $this->rendered; } /** * Handles parsing and filtering attributes while preserving any passed in via field config. * * @since 1.1.0 * @param string $element Element for filter. * @param array $type_defaults Type default arguments. * @param array $type_overrides Type override arguments. * @return array Parsed and filtered arguments. */ public function parse_args( $element, $type_defaults, $type_overrides = array() ) { $args = $this->parse_args_from_overrides( $type_overrides ); /** * Filter attributes for a field type. * The dynamic portion of the hook name, $element, refers to the field type. * * @since 1.1.0 * @param array $args The array of attribute arguments. * @param array $type_defaults The array of default values. * @param array $field The `CMB2_Field` object. * @param object $field_type_object This `CMB2_Types` object. */ $args = apply_filters( "cmb2_{$element}_attributes", $args, $type_defaults, $this->field, $this->types ); $args = wp_parse_args( $args, $type_defaults ); if ( ! empty( $args['js_dependencies'] ) ) { $this->field->add_js_dependencies( $args['js_dependencies'] ); } return $args; } /** * Handles parsing and filtering attributes while preserving any passed in via field config. * * @since 2.2.4 * @param array $type_overrides Type override arguments. * @return array Parsed arguments */ protected function parse_args_from_overrides( $type_overrides = array() ) { $type_overrides = empty( $type_overrides ) ? $this->args : $type_overrides; if ( true !== $this->field->args( 'disable_hash_data_attribute' ) ) { $type_overrides['data-hash'] = $this->field->hash_id(); } $field_overrides = $this->field->args( 'attributes' ); return ! empty( $field_overrides ) ? wp_parse_args( $field_overrides, $type_overrides ) : $type_overrides; } /** * Fall back to CMB2_Types methods * * @param string $method Method name being invoked. * @param array $arguments Arguments passed for the method. * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __call( $method, $arguments ) { switch ( $method ) { case '_id': case '_name': case '_desc': case '_text': case 'concat_attrs': return call_user_func_array( array( $this->types, $method ), $arguments ); default: throw new Exception( sprintf( esc_html__( 'Invalid %1$s method: %2$s', 'cmb2' ), __CLASS__, $method ) ); } } /** * Magic getter for our object. * * @param string $field Property being requested. * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __get( $field ) { switch ( $field ) { case 'field': return $this->types->field; default: throw new Exception( sprintf( esc_html__( 'Invalid %1$s property: %2$s', 'cmb2' ), __CLASS__, $field ) ); } } } cmb2/cmb2/includes/types/CMB2_Type_File.php 0000644 00000012644 15151523433 0014331 0 ustar 00 <?php /** * CMB file field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_File extends CMB2_Type_File_Base { /** * Handles outputting an 'file' field * * @param array $args Override arguments. * @return string Form input element */ public function render( $args = array() ) { $args = empty( $args ) ? $this->args : $args; $field = $this->field; $options = (array) $field->options(); $a = $this->args = $this->parse_args( 'file', array( 'class' => 'cmb2-upload-file regular-text', 'id' => $this->_id(), 'name' => $this->_name(), 'value' => $field->escaped_value(), 'id_value' => null, 'desc' => $this->_desc( true ), 'size' => 45, 'js_dependencies' => 'media-editor', 'preview_size' => $field->args( 'preview_size' ), 'query_args' => $field->args( 'query_args' ), // if options array and 'url' => false, then hide the url field. 'type' => array_key_exists( 'url', $options ) && false === $options['url'] ? 'hidden' : 'text', ), $args ); // get an array of image size meta data, fallback to 'large'. $this->args['img_size_data'] = $img_size_data = parent::get_image_size_data( $a['preview_size'], 'large' ); $output = ''; $output .= parent::render( array( 'type' => $a['type'], 'class' => $a['class'], 'value' => $a['value'], 'id' => $a['id'], 'name' => $a['name'], 'size' => $a['size'], 'desc' => '', 'data-previewsize' => sprintf( '[%d,%d]', $img_size_data['width'], $img_size_data['height'] ), 'data-sizename' => $img_size_data['name'], 'data-queryargs' => ! empty( $a['query_args'] ) ? json_encode( $a['query_args'] ) : '', 'js_dependencies' => $a['js_dependencies'], ) ); // Now remove the data-iterator attribute if it exists. // (Possible if being used within a custom field) // This is not elegant, but compensates for CMB2_Types::_id // automagically & inelegantly adding the data-iterator attribute. // Single responsibility principle? pffft. $parts = explode( '"', $this->args['id'] ); $this->args['id'] = $parts[0]; $output .= sprintf( '<input class="cmb2-upload-button button-secondary" type="button" value="%1$s" />', esc_attr( $this->_text( 'add_upload_file_text', esc_html__( 'Add or Upload File', 'cmb2' ) ) ) ); $output .= $a['desc']; $output .= $this->get_id_field_output(); $output .= '<div id="' . esc_attr( $field->id() ) . '-status" class="cmb2-media-status">'; if ( ! empty( $a['value'] ) ) { $output .= $this->get_file_preview_output(); } $output .= '</div>'; return $this->rendered( $output ); } /** * Return attempted file preview output for a provided file. * * @since 2.2.5 * * @return string */ public function get_file_preview_output() { if ( ! $this->is_valid_img_ext( $this->args['value'] ) ) { return $this->file_status_output( array( 'value' => $this->args['value'], 'tag' => 'div', 'cached_id' => $this->args['id'], ) ); } if ( $this->args['id_value'] ) { $image = wp_get_attachment_image( $this->args['id_value'], $this->args['preview_size'], null, array( 'class' => 'cmb-file-field-image', ) ); } else { $image = '<img style="max-width: ' . absint( $this->args['img_size_data']['width'] ) . 'px; width: 100%;" src="' . esc_url( $this->args['value'] ) . '" class="cmb-file-field-image" alt="" />'; } return $this->img_status_output( array( 'image' => $image, 'tag' => 'div', 'cached_id' => $this->args['id'], ) ); } /** * Return field ID output as a hidden field. * * @since 2.2.5 * * @return string */ public function get_id_field_output() { $field = $this->field; /* * A little bit of magic (tsk tsk) replacing the $this->types->field object, * So that the render function is using the proper field object. */ $this->types->field = $this->get_id_field(); $output = parent::render( array( 'type' => 'hidden', 'class' => 'cmb2-upload-file-id', 'value' => $this->types->field->value, 'desc' => '', ) ); // We need to put the original field object back // or other fields in a custom field will be broken. $this->types->field = $field; return $output; } /** * Return field ID data. * * @since 2.2.5 * * @return mixed */ public function get_id_field() { // reset field args for attachment id. $args = array( // if we're looking at a file in a group, we need to get the non-prefixed id. 'id' => ( $this->field->group ? $this->field->args( '_id' ) : $this->args['id'] ) . '_id', 'disable_hash_data_attribute' => true, ); // and get new field object // (need to set it to the types field property). $id_field = $this->field->get_field_clone( $args ); $id_value = absint( null !== $this->args['id_value'] ? $this->args['id_value'] : $id_field->escaped_value() ); // we don't want to output "0" as a value. if ( ! $id_value ) { $id_value = ''; } // if there is no id saved yet, try to get it from the url. if ( $this->args['value'] && ! $id_value ) { $id_value = CMB2_Utils::image_id_from_url( esc_url_raw( $this->args['value'] ) ); } $id_field->value = $id_value; return $id_field; } } cmb2/cmb2/includes/types/CMB2_Type_Select_Timezone.php 0000644 00000001227 15151523433 0016536 0 ustar 00 <?php /** * CMB select_timezone field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Select_Timezone extends CMB2_Type_Select { public function render() { $this->field->args['default'] = $this->field->get_default() ? $this->field->get_default() : CMB2_Utils::timezone_string(); $this->args = wp_parse_args( $this->args, array( 'class' => 'cmb2_select cmb2-select-timezone', 'options' => wp_timezone_choice( $this->field->escaped_value() ), 'desc' => $this->_desc(), ) ); return parent::render(); } } cmb2/cmb2/includes/types/CMB2_Type_Textarea_Code.php 0000644 00000001652 15151523433 0016156 0 ustar 00 <?php /** * CMB textarea_code field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Textarea_Code extends CMB2_Type_Textarea { /** * Handles outputting an 'textarea' element * * @since 1.1.0 * @param array $args Override arguments * @return string Form textarea element */ public function render( $args = array() ) { $args = wp_parse_args( $args, array( 'class' => 'cmb2-textarea-code', 'desc' => '</pre>' . $this->_desc( true ), ) ); if ( true !== $this->field->options( 'disable_codemirror' ) && function_exists( 'wp_enqueue_code_editor' ) ) { $args['js_dependencies'] = array( 'code-editor' ); } else { $args['class'] = rtrim( $args['class'] ) . ' disable-codemirror'; } return $this->rendered( sprintf( '<pre>%s', parent::render( $args ) ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Textarea.php 0000644 00000002021 15151523433 0015213 0 ustar 00 <?php /** * CMB textarea field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Type_Textarea extends CMB2_Type_Counter_Base { /** * Handles outputting an 'textarea' element * * @since 1.1.0 * @param array $args Override arguments * @return string Form textarea element */ public function render( $args = array() ) { $args = empty( $args ) ? $this->args : $args; $a = $this->parse_args( 'textarea', array( 'class' => 'cmb2_textarea', 'name' => $this->_name(), 'id' => $this->_id(), 'cols' => 60, 'rows' => 10, 'value' => $this->field->escaped_value( 'esc_textarea' ), 'desc' => $this->_desc( true ), ), $args ); // Add character counter? $a = $this->maybe_update_attributes_for_char_counter( $a ); return $this->rendered( sprintf( '<textarea%s>%s</textarea>%s', $this->concat_attrs( $a, array( 'desc', 'value' ) ), $a['value'], $a['desc'] ) ); } } cmb2/cmb2/includes/types/CMB2_Type_Counter_Base.php 0000644 00000006630 15151523433 0016021 0 ustar 00 <?php /** * CMB base field type * * @since 2.2.2 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ abstract class CMB2_Type_Counter_Base extends CMB2_Type_Base { /** * Whether this type has the counter added. * * @since 2.7.0 * * @var boolean */ public $has_counter = false; /** * Return character counter markup for this field. * * @since 2.7.0 * * @param string $val The actual value of this field. * * @return string */ public function char_counter_markup( $val ) { $markup = ''; if ( ! $this->field->args( 'char_counter' ) ) { return $markup; } $type = (string) $this->field->args( 'char_counter' ); $field_id = $this->_id( '', false ); $char_max = (int) $this->field->prop( 'char_max' ); if ( $char_max ) { $char_max = 'data-max="' . $char_max . '"'; } switch ( $type ) { case 'words': $label = $char_max ? $this->_text( 'words_left_text', esc_html__( 'Words left', 'cmb2' ) ) : $this->_text( 'words_text', esc_html__( 'Words', 'cmb2' ) ); break; default: $type = 'characters'; $label = $char_max ? $this->_text( 'characters_left_text', esc_html__( 'Characters left', 'cmb2' ) ) : $this->_text( 'characters_text', esc_html__( 'Characters', 'cmb2' ) ); break; } $msg = $char_max ? sprintf( '<span class="cmb2-char-max-msg">%s</span>', $this->_text( 'characters_truncated_text', esc_html__( 'Your text may be truncated.', 'cmb2' ) ) ) : ''; $length = strlen( $val ); $width = $length > 1 ? ( 8 * strlen( (string) $length ) ) + 15 : false; $markup .= '<p class="cmb2-char-counter-wrap">'; $markup .= sprintf( '<label><span class="cmb2-char-counter-label">%2$s:</span> <input id="%1$s" data-field-id="%3$s" data-counter-type="%4$s" %5$s class="cmb2-char-counter" type="text" value="%6$s" readonly="readonly" style="%7$s"></label>%8$s', esc_attr( 'char-counter-' . $field_id ), $label, esc_attr( $field_id ), $type, $char_max, $length, $width ? "width: {$width}px;" : '', $msg ); $markup .= '</p>'; // Enqueue the required JS. $this->field->add_js_dependencies( array( 'word-count', 'wp-util', 'cmb2-char-counter', ) ); $this->has_counter = true; return $markup; } /** * Maybe update attributes for the character counter. * * @since 2.7.0 * * @param array $attributes Array of parsed attributes. * * @return array Potentially modified attributes. */ public function maybe_update_attributes_for_char_counter( $attributes ) { $char_counter = $this->char_counter_markup( $attributes['value'] ); // Has character counter? if ( $char_counter ) { $attributes['class'] = ! empty( $attributes['class'] ) ? $attributes['class'] . ' cmb2-count-chars' : ' cmb2-count-chars'; // Enforce max chars? $max = $this->enforce_max(); if ( $max ) { $attributes['maxlength'] = $max; } $attributes['desc'] = $char_counter . $attributes['desc']; } return $attributes; } /** * Enforce max chars? * * @since 2.7.0 * * @return bool Whether to enforce max characters. */ public function enforce_max() { $char_max = (int) $this->field->args( 'char_max' ); // Enforce max chars? return ( $this->field->args( 'char_max_enforce' ) && $char_max > 0 && 'words' !== $this->field->args( 'char_counter' ) ) ? $char_max : false; } } cmb2/cmb2/includes/CMB2_Ajax.php 0000644 00000022051 15151523433 0012161 0 ustar 00 <?php /** * CMB2 ajax methods * (i.e. a lot of work to get oEmbeds to work with non-post objects) * * @since 0.9.5 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ */ class CMB2_Ajax { // Whether to hijack the oembed cache system. protected $hijack = false; protected $object_id = 0; protected $embed_args = array(); protected $object_type = 'post'; protected $ajax_update = false; /** * Instance of this class. * * @since 2.2.2 * @var object */ protected static $instance; /** * Get the singleton instance of this class. * * @since 2.2.2 * @return CMB2_Ajax */ public static function get_instance() { if ( ! ( self::$instance instanceof self ) ) { self::$instance = new self(); } return self::$instance; } /** * Constructor * * @since 2.2.0 */ protected function __construct() { add_action( 'wp_ajax_cmb2_oembed_handler', array( $this, 'oembed_handler' ) ); add_action( 'wp_ajax_nopriv_cmb2_oembed_handler', array( $this, 'oembed_handler' ) ); // Need to occasionally clean stale oembed cache data from the option value. add_action( 'cmb2_save_options-page_fields', array( __CLASS__, 'clean_stale_options_page_oembeds' ) ); } /** * Handles our oEmbed ajax request * * @since 0.9.5 * @return mixed oEmbed embed code | fallback | error message */ public function oembed_handler() { // Verify our nonce. if ( ! ( isset( $_REQUEST['cmb2_ajax_nonce'], $_REQUEST['oembed_url'] ) && wp_verify_nonce( $_REQUEST['cmb2_ajax_nonce'], 'ajax_nonce' ) ) ) { die(); } // Sanitize our search string. $oembed_string = sanitize_text_field( $_REQUEST['oembed_url'] ); // Send back error if empty. if ( empty( $oembed_string ) ) { wp_send_json_error( '<p class="ui-state-error-text">' . esc_html__( 'Please Try Again', 'cmb2' ) . '</p>' ); } // Set width of embed. $embed_width = isset( $_REQUEST['oembed_width'] ) && intval( $_REQUEST['oembed_width'] ) < 640 ? intval( $_REQUEST['oembed_width'] ) : '640'; // Set url. $oembed_url = esc_url( $oembed_string ); // Set args. $embed_args = array( 'width' => $embed_width, ); $this->ajax_update = true; // Get embed code (or fallback link). $html = $this->get_oembed( array( 'url' => $oembed_url, 'object_id' => $_REQUEST['object_id'], 'object_type' => isset( $_REQUEST['object_type'] ) ? $_REQUEST['object_type'] : 'post', 'oembed_args' => $embed_args, 'field_id' => $_REQUEST['field_id'], ) ); wp_send_json_success( $html ); } /** * Retrieves oEmbed from url/object ID * * @since 0.9.5 * @param array $args Arguments for method. * @return mixed HTML markup with embed or fallback. */ public function get_oembed_no_edit( $args ) { global $wp_embed; $oembed_url = esc_url( $args['url'] ); // Sanitize object_id. $this->object_id = is_numeric( $args['object_id'] ) ? absint( $args['object_id'] ) : sanitize_text_field( $args['object_id'] ); $args = wp_parse_args( $args, array( 'object_type' => 'post', 'oembed_args' => array(), 'field_id' => false, 'wp_error' => false, ) ); $this->embed_args =& $args; /* * Set the post_ID so oEmbed won't fail * wp-includes/class-wp-embed.php, WP_Embed::shortcode() */ $wp_embed->post_ID = $this->object_id; // Special scenario if NOT a post object. if ( isset( $args['object_type'] ) && 'post' != $args['object_type'] ) { if ( 'options-page' == $args['object_type'] ) { // Bogus id to pass some numeric checks. Issue with a VERY large WP install? $wp_embed->post_ID = 1987645321; } // Ok, we need to hijack the oembed cache system. $this->hijack = true; $this->object_type = $args['object_type']; // Gets ombed cache from our object's meta (vs postmeta). add_filter( 'get_post_metadata', array( $this, 'hijack_oembed_cache_get' ), 10, 3 ); // Sets ombed cache in our object's meta (vs postmeta). add_filter( 'update_post_metadata', array( $this, 'hijack_oembed_cache_set' ), 10, 4 ); } $embed_args = ''; foreach ( $args['oembed_args'] as $key => $val ) { $embed_args .= " $key=\"$val\""; } // Ping WordPress for an embed. $embed = $wp_embed->run_shortcode( '[embed' . $embed_args . ']' . $oembed_url . '[/embed]' ); // Fallback that WordPress creates when no oEmbed was found. $fallback = $wp_embed->maybe_make_link( $oembed_url ); return compact( 'embed', 'fallback', 'args' ); } /** * Retrieves oEmbed from url/object ID * * @since 0.9.5 * @param array $args Arguments for method. * @return string HTML markup with embed or fallback. */ public function get_oembed( $args ) { $oembed = $this->get_oembed_no_edit( $args ); // Send back our embed. if ( $oembed['embed'] && $oembed['embed'] != $oembed['fallback'] ) { return '<div class="cmb2-oembed embed-status">' . $oembed['embed'] . '<p class="cmb2-remove-wrapper"><a href="#" class="cmb2-remove-file-button" rel="' . $oembed['args']['field_id'] . '">' . esc_html__( 'Remove Embed', 'cmb2' ) . '</a></p></div>'; } // Otherwise, send back error info that no oEmbeds were found. return sprintf( '<p class="ui-state-error-text">%s</p>', sprintf( /* translators: 1: results for. 2: link to codex.wordpress.org/Embeds */ esc_html__( 'No oEmbed Results Found for %1$s. View more info at %2$s.', 'cmb2' ), $oembed['fallback'], '<a href="https://wordpress.org/support/article/embeds/" target="_blank">codex.wordpress.org/Embeds</a>' ) ); } /** * Hijacks retrieving of cached oEmbed. * Returns cached data from relevant object metadata (vs postmeta) * * @since 0.9.5 * @param boolean $check Whether to retrieve postmeta or override. * @param int $object_id Object ID. * @param string $meta_key Object metakey. * @return mixed Object's oEmbed cached data. */ public function hijack_oembed_cache_get( $check, $object_id, $meta_key ) { if ( ! $this->hijack || ( $this->object_id != $object_id && 1987645321 !== $object_id ) ) { return $check; } if ( $this->ajax_update ) { return false; } return $this->cache_action( $meta_key ); } /** * Hijacks saving of cached oEmbed. * Saves cached data to relevant object metadata (vs postmeta) * * @since 0.9.5 * @param boolean $check Whether to continue setting postmeta. * @param int $object_id Object ID to get postmeta from. * @param string $meta_key Postmeta's key. * @param mixed $meta_value Value of the postmeta to be saved. * @return boolean Whether to continue setting. */ public function hijack_oembed_cache_set( $check, $object_id, $meta_key, $meta_value ) { if ( ! $this->hijack || ( $this->object_id != $object_id && 1987645321 !== $object_id ) // Only want to hijack oembed meta values. || 0 !== strpos( $meta_key, '_oembed_' ) ) { return $check; } $this->cache_action( $meta_key, $meta_value ); // Anything other than `null` to cancel saving to postmeta. return true; } /** * Gets/updates the cached oEmbed value from/to relevant object metadata (vs postmeta). * * @since 1.3.0 * * @param string $meta_key Postmeta's key. * @return mixed */ protected function cache_action( $meta_key ) { $func_args = func_get_args(); $action = isset( $func_args[1] ) ? 'update' : 'get'; if ( 'options-page' === $this->object_type ) { $args = array( $meta_key ); if ( 'update' === $action ) { $args[] = $func_args[1]; $args[] = true; } // Cache the result to our options. $status = call_user_func_array( array( cmb2_options( $this->object_id ), $action ), $args ); } else { $args = array( $this->object_type, $this->object_id, $meta_key ); $args[] = 'update' === $action ? $func_args[1] : true; // Cache the result to our metadata. $status = call_user_func_array( $action . '_metadata', $args ); } return $status; } /** * Hooks in when options-page data is saved to clean stale * oembed cache data from the option value. * * @since 2.2.0 * @param string $option_key The options-page option key. * @return void */ public static function clean_stale_options_page_oembeds( $option_key ) { $options = cmb2_options( $option_key )->get_options(); $modified = false; if ( is_array( $options ) ) { $ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, '', array(), 0 ); $now = time(); foreach ( $options as $key => $value ) { // Check for cached oembed data. if ( 0 === strpos( $key, '_oembed_time_' ) ) { $cached_recently = ( $now - $value ) < $ttl; if ( ! $cached_recently ) { $modified = true; // Remove the the cached ttl expiration, and the cached oembed value. unset( $options[ $key ] ); unset( $options[ str_replace( '_oembed_time_', '_oembed_', $key ) ] ); } } // End if. // Remove the cached unknown values. elseif ( '{{unknown}}' === $value ) { $modified = true; unset( $options[ $key ] ); } } } // Update the option and remove stale cache data. if ( $modified ) { $updated = cmb2_options( $option_key )->set( $options ); } } } cmb2/cmb2/includes/CMB2_Hookup_Base.php 0000644 00000005112 15151523433 0013474 0 ustar 00 <?php /** * Base class for hooking CMB2 into WordPress. * * @since 2.2.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @property-read string $object_type * @property-read CMB2 $cmb */ abstract class CMB2_Hookup_Base { /** * CMB2 object. * * @var CMB2 object * @since 2.0.2 */ protected $cmb; /** * The object type we are performing the hookup for * * @var string * @since 2.0.9 */ protected $object_type = 'post'; /** * A functionalized constructor, used for the hookup action callbacks. * * @since 2.2.6 * * @throws Exception Failed implementation. * * @param CMB2 $cmb The CMB2 object to hookup. */ public static function maybe_init_and_hookup( CMB2 $cmb ) { throw new Exception( sprintf( esc_html__( '%1$s should be implemented by the extended class.', 'cmb2' ), __FUNCTION__ ) ); } /** * Constructor * * @since 2.0.0 * @param CMB2 $cmb The CMB2 object to hookup. */ public function __construct( CMB2 $cmb ) { $this->cmb = $cmb; $this->object_type = $this->cmb->mb_object_type(); } abstract public function universal_hooks(); /** * Ensures WordPress hook only gets fired once per object. * * @since 2.0.0 * @param string $action The name of the filter to hook the $hook callback to. * @param callback $hook The callback to be run when the filter is applied. * @param integer $priority Order the functions are executed. * @param int $accepted_args The number of arguments the function accepts. */ public function once( $action, $hook, $priority = 10, $accepted_args = 1 ) { static $hooks_completed = array(); $args = func_get_args(); // Get object hash.. This bypasses issues with serializing closures. if ( is_object( $hook ) ) { $args[1] = spl_object_hash( $args[1] ); } elseif ( is_array( $hook ) && is_object( $hook[0] ) ) { $args[1][0] = spl_object_hash( $hook[0] ); } $key = md5( serialize( $args ) ); if ( ! isset( $hooks_completed[ $key ] ) ) { $hooks_completed[ $key ] = 1; add_filter( $action, $hook, $priority, $accepted_args ); } } /** * Magic getter for our object. * * @param string $field Property to return. * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __get( $field ) { switch ( $field ) { case 'object_type': case 'cmb': return $this->{$field}; default: throw new Exception( sprintf( esc_html__( 'Invalid %1$s property: %2$s', 'cmb2' ), __CLASS__, $field ) ); } } } cmb2/cmb2/includes/CMB2_Boxes.php 0000644 00000006244 15151523433 0012364 0 ustar 00 <?php /** * A CMB2 object instance registry for storing every CMB2 instance. * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Boxes { /** * Array of all metabox objects. * * @since 2.0.0 * @var array */ protected static $cmb2_instances = array(); /** * Add a CMB2 instance object to the registry. * * @since 1.X.X * * @param CMB2 $cmb_instance CMB2 instance. */ public static function add( CMB2 $cmb_instance ) { self::$cmb2_instances[ $cmb_instance->cmb_id ] = $cmb_instance; } /** * Remove a CMB2 instance object from the registry. * * @since 1.X.X * * @param string $cmb_id A CMB2 instance id. */ public static function remove( $cmb_id ) { if ( array_key_exists( $cmb_id, self::$cmb2_instances ) ) { unset( self::$cmb2_instances[ $cmb_id ] ); } } /** * Retrieve a CMB2 instance by cmb id. * * @since 1.X.X * * @param string $cmb_id A CMB2 instance id. * * @return CMB2|bool False or CMB2 object instance. */ public static function get( $cmb_id ) { if ( empty( self::$cmb2_instances ) || empty( self::$cmb2_instances[ $cmb_id ] ) ) { return false; } return self::$cmb2_instances[ $cmb_id ]; } /** * Retrieve all CMB2 instances registered. * * @since 1.X.X * @return CMB2[] Array of all registered cmb2 instances. */ public static function get_all() { return self::$cmb2_instances; } /** * Retrieve all CMB2 instances that have the specified property set. * * @since 2.4.0 * @param string $property Property name. * @param mixed $compare (Optional) The value to compare. * @return CMB2[] Array of matching cmb2 instances. */ public static function get_by( $property, $compare = 'nocompare' ) { $boxes = array(); foreach ( self::$cmb2_instances as $cmb_id => $cmb ) { $prop = $cmb->prop( $property ); if ( 'nocompare' === $compare ) { if ( ! empty( $prop ) ) { $boxes[ $cmb_id ] = $cmb; } continue; } if ( $compare === $prop ) { $boxes[ $cmb_id ] = $cmb; } } return $boxes; } /** * Retrieve all CMB2 instances as long as they do not include the ignored property. * * @since 2.4.0 * @param string $property Property name. * @param mixed $to_ignore The value to ignore. * @return CMB2[] Array of matching cmb2 instances. */ public static function filter_by( $property, $to_ignore = null ) { $boxes = array(); foreach ( self::$cmb2_instances as $cmb_id => $cmb ) { if ( $to_ignore === $cmb->prop( $property ) ) { continue; } $boxes[ $cmb_id ] = $cmb; } return $boxes; } /** * Deprecated and left for back-compatibility. The original `get_by_property` * method was misnamed and never actually used by CMB2 core. * * @since 2.2.3 * * @param string $property Property name. * @param mixed $to_ignore The value to ignore. * @return CMB2[] Array of matching cmb2 instances. */ public static function get_by_property( $property, $to_ignore = null ) { _deprecated_function( __METHOD__, '2.4.0', 'CMB2_Boxes::filter_by()' ); return self::filter_by( $property ); } } cmb2/cmb2/includes/helper-functions.php 0000644 00000031370 15151523433 0014024 0 ustar 00 <?php /** * CMB2 Helper Functions * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ /** * Helper function to provide directory path to CMB2 * * @since 2.0.0 * @param string $path Path to append. * @return string Directory with optional path appended */ function cmb2_dir( $path = '' ) { return CMB2_DIR . $path; } /** * Autoloads files with CMB2 classes when needed * * @since 1.0.0 * @param string $class_name Name of the class being requested. */ function cmb2_autoload_classes( $class_name ) { if ( 0 !== strpos( $class_name, 'CMB2' ) ) { return; } $path = 'includes'; if ( 'CMB2_Type' === $class_name || 0 === strpos( $class_name, 'CMB2_Type_' ) ) { $path .= '/types'; } if ( 'CMB2_REST' === $class_name || 0 === strpos( $class_name, 'CMB2_REST_' ) ) { $path .= '/rest-api'; } include_once( cmb2_dir( "$path/{$class_name}.php" ) ); } /** * Get instance of the CMB2_Utils class * * @since 2.0.0 * @return CMB2_Utils object CMB2 utilities class */ function cmb2_utils() { static $cmb2_utils; $cmb2_utils = $cmb2_utils ? $cmb2_utils : new CMB2_Utils(); return $cmb2_utils; } /** * Get instance of the CMB2_Ajax class * * @since 2.0.0 * @return CMB2_Ajax object CMB2 ajax class */ function cmb2_ajax() { return CMB2_Ajax::get_instance(); } /** * Get instance of the CMB2_Option class for the passed metabox ID * * @since 2.0.0 * * @param string $key Option key to fetch. * @return CMB2_Option object Options class for setting/getting options for metabox */ function cmb2_options( $key ) { return CMB2_Options::get( $key ); } /** * Get a cmb oEmbed. Handles oEmbed getting for non-post objects * * @since 2.0.0 * @param array $args Arguments. Accepts: * * 'url' - URL to retrieve the oEmbed from, * 'object_id' - $post_id, * 'object_type' - 'post', * 'oembed_args' - $embed_args, // array containing 'width', etc * 'field_id' - false, * 'cache_key' - false, * 'wp_error' - true/false, // To return a wp_error object if no embed found. * * @return string oEmbed string */ function cmb2_get_oembed( $args = array() ) { $oembed = cmb2_ajax()->get_oembed_no_edit( $args ); // Send back our embed. if ( $oembed['embed'] && $oembed['embed'] != $oembed['fallback'] ) { return '<div class="cmb2-oembed">' . $oembed['embed'] . '</div>'; } $error = sprintf( /* translators: 1: results for. 2: link to codex.wordpress.org/Embeds */ esc_html__( 'No oEmbed Results Found for %1$s. View more info at %2$s.', 'cmb2' ), $oembed['fallback'], '<a href="https://wordpress.org/support/article/embeds/" target="_blank">codex.wordpress.org/Embeds</a>' ); if ( isset( $args['wp_error'] ) && $args['wp_error'] ) { return new WP_Error( 'cmb2_get_oembed_result', $error, compact( 'oembed', 'args' ) ); } // Otherwise, send back error info that no oEmbeds were found. return '<p class="ui-state-error-text">' . $error . '</p>'; } /** * Outputs the return of cmb2_get_oembed. * * @since 2.2.2 * @see cmb2_get_oembed * * @param array $args oEmbed args. */ function cmb2_do_oembed( $args = array() ) { echo cmb2_get_oembed( $args ); } add_action( 'cmb2_do_oembed', 'cmb2_do_oembed' ); /** * A helper function to get an option from a CMB2 options array * * @since 1.0.1 * @param string $option_key Option key. * @param string $field_id Option array field key. * @param mixed $default Optional default fallback value. * @return array Options array or specific field */ function cmb2_get_option( $option_key, $field_id = '', $default = false ) { return cmb2_options( $option_key )->get( $field_id, $default ); } /** * A helper function to update an option in a CMB2 options array * * @since 2.0.0 * @param string $option_key Option key. * @param string $field_id Option array field key. * @param mixed $value Value to update data with. * @param boolean $single Whether data should not be an array. * @return boolean Success/Failure */ function cmb2_update_option( $option_key, $field_id, $value, $single = true ) { if ( cmb2_options( $option_key )->update( $field_id, $value, false, $single ) ) { return cmb2_options( $option_key )->set(); } return false; } /** * Get a CMB2 field object. * * @since 1.1.0 * @param array $meta_box Metabox ID or Metabox config array. * @param array $field_id Field ID or all field arguments. * @param int|string $object_id Object ID (string for options-page). * @param string $object_type Type of object being saved. (e.g., post, user, term, comment, or options-page). * Defaults to metabox object type. * @return CMB2_Field|null CMB2_Field object unless metabox config cannot be found */ function cmb2_get_field( $meta_box, $field_id, $object_id = 0, $object_type = '' ) { $object_id = $object_id ? $object_id : get_the_ID(); $cmb = $meta_box instanceof CMB2 ? $meta_box : cmb2_get_metabox( $meta_box, $object_id ); if ( ! $cmb ) { return; } $cmb->object_type( $object_type ? $object_type : $cmb->mb_object_type() ); return $cmb->get_field( $field_id ); } /** * Get a field's value. * * @since 1.1.0 * @param array $meta_box Metabox ID or Metabox config array. * @param array $field_id Field ID or all field arguments. * @param int|string $object_id Object ID (string for options-page). * @param string $object_type Type of object being saved. (e.g., post, user, term, comment, or options-page). * Defaults to metabox object type. * @return mixed Maybe escaped value */ function cmb2_get_field_value( $meta_box, $field_id, $object_id = 0, $object_type = '' ) { $field = cmb2_get_field( $meta_box, $field_id, $object_id, $object_type ); return $field->escaped_value(); } /** * Because OOP can be scary * * @since 2.0.2 * @param array $meta_box_config Metabox Config array. * @return CMB2 object Instantiated CMB2 object */ function new_cmb2_box( array $meta_box_config ) { return cmb2_get_metabox( $meta_box_config ); } /** * Retrieve a CMB2 instance by the metabox ID * * @since 2.0.0 * @param mixed $meta_box Metabox ID or Metabox config array. * @param int|string $object_id Object ID (string for options-page). * @param string $object_type Type of object being saved. * (e.g., post, user, term, comment, or options-page). * Defaults to metabox object type. * @return CMB2 object */ function cmb2_get_metabox( $meta_box, $object_id = 0, $object_type = '' ) { if ( $meta_box instanceof CMB2 ) { return $meta_box; } if ( is_string( $meta_box ) ) { $cmb = CMB2_Boxes::get( $meta_box ); } else { // See if we already have an instance of this metabox. $cmb = CMB2_Boxes::get( $meta_box['id'] ); // If not, we'll initate a new metabox. $cmb = $cmb ? $cmb : new CMB2( $meta_box, $object_id ); } if ( $cmb && $object_id ) { $cmb->object_id( $object_id ); } if ( $cmb && $object_type ) { $cmb->object_type( $object_type ); } return $cmb; } /** * Returns array of sanitized field values from a metabox (without saving them) * * @since 2.0.3 * @param mixed $meta_box Metabox ID or Metabox config array. * @param array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data). * @return mixed Array of sanitized values or false if no CMB2 object found */ function cmb2_get_metabox_sanitized_values( $meta_box, array $data_to_sanitize ) { $cmb = cmb2_get_metabox( $meta_box ); return $cmb ? $cmb->get_sanitized_values( $data_to_sanitize ) : false; } /** * Retrieve a metabox form * * @since 2.0.0 * @param mixed $meta_box Metabox config array or Metabox ID. * @param int|string $object_id Object ID (string for options-page). * @param array $args Optional arguments array. * @return string CMB2 html form markup */ function cmb2_get_metabox_form( $meta_box, $object_id = 0, $args = array() ) { $object_id = $object_id ? $object_id : get_the_ID(); $cmb = cmb2_get_metabox( $meta_box, $object_id ); ob_start(); // Get cmb form. cmb2_print_metabox_form( $cmb, $object_id, $args ); $form = ob_get_clean(); return apply_filters( 'cmb2_get_metabox_form', $form, $object_id, $cmb ); } /** * Display a metabox form & save it on submission * * @since 1.0.0 * @param mixed $meta_box Metabox config array or Metabox ID. * @param int|string $object_id Object ID (string for options-page). * @param array $args Optional arguments array. */ function cmb2_print_metabox_form( $meta_box, $object_id = 0, $args = array() ) { $object_id = $object_id ? $object_id : get_the_ID(); $cmb = cmb2_get_metabox( $meta_box, $object_id ); // if passing a metabox ID, and that ID was not found. if ( ! $cmb ) { return; } $args = wp_parse_args( $args, array( 'form_format' => '<form class="cmb-form" method="post" id="%1$s" enctype="multipart/form-data" encoding="multipart/form-data"><input type="hidden" name="object_id" value="%2$s">%3$s<input type="submit" name="submit-cmb" value="%4$s" class="button-primary"></form>', 'save_button' => esc_html__( 'Save', 'cmb2' ), 'object_type' => $cmb->mb_object_type(), 'cmb_styles' => $cmb->prop( 'cmb_styles' ), 'enqueue_js' => $cmb->prop( 'enqueue_js' ), ) ); // Set object type explicitly (rather than trying to guess from context). $cmb->object_type( $args['object_type'] ); // Save the metabox if it's been submitted // check permissions // @todo more hardening? if ( $cmb->prop( 'save_fields' ) // check nonce. && isset( $_POST['submit-cmb'], $_POST['object_id'], $_POST[ $cmb->nonce() ] ) && wp_verify_nonce( $_POST[ $cmb->nonce() ], $cmb->nonce() ) && $object_id && $_POST['object_id'] == $object_id ) { $cmb->save_fields( $object_id, $cmb->object_type(), $_POST ); } // Enqueue JS/CSS. if ( $args['cmb_styles'] ) { CMB2_Hookup::enqueue_cmb_css(); } if ( $args['enqueue_js'] ) { CMB2_Hookup::enqueue_cmb_js(); } $form_format = apply_filters( 'cmb2_get_metabox_form_format', $args['form_format'], $object_id, $cmb ); $format_parts = explode( '%3$s', $form_format ); // Show cmb form. printf( $format_parts[0], esc_attr( $cmb->cmb_id ), esc_attr( $object_id ) ); $cmb->show_form(); if ( isset( $format_parts[1] ) && $format_parts[1] ) { printf( str_ireplace( '%4$s', '%1$s', $format_parts[1] ), esc_attr( $args['save_button'] ) ); } } /** * Display a metabox form (or optionally return it) & save it on submission. * * @since 1.0.0 * @param mixed $meta_box Metabox config array or Metabox ID. * @param int|string $object_id Object ID (string for options-page). * @param array $args Optional arguments array. * @return string */ function cmb2_metabox_form( $meta_box, $object_id = 0, $args = array() ) { if ( ! isset( $args['echo'] ) || $args['echo'] ) { cmb2_print_metabox_form( $meta_box, $object_id, $args ); } else { return cmb2_get_metabox_form( $meta_box, $object_id, $args ); } } if ( ! function_exists( 'date_create_from_format' ) ) { /** * Reimplementation of DateTime::createFromFormat for PHP < 5.3. :( * Borrowed from http://stackoverflow.com/questions/5399075/php-datetimecreatefromformat-in-5-2 * * @param string $date_format Date format. * @param string $date_value Date value. * * @return DateTime */ function date_create_from_format( $date_format, $date_value ) { $schedule_format = str_replace( array( 'M', 'Y', 'm', 'd', 'H', 'i', 'a' ), array( '%b', '%Y', '%m', '%d', '%H', '%M', '%p' ), $date_format ); /* * %Y, %m and %d correspond to date()'s Y m and d. * %I corresponds to H, %M to i and %p to a */ // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.strptimeDeprecated $parsed_time = strptime( $date_value, $schedule_format ); $ymd = sprintf( /** * This is a format string that takes six total decimal * arguments, then left-pads them with zeros to either * 4 or 2 characters, as needed */ '%04d-%02d-%02d %02d:%02d:%02d', $parsed_time['tm_year'] + 1900, // This will be "111", so we need to add 1900. $parsed_time['tm_mon'] + 1, // This will be the month minus one, so we add one. $parsed_time['tm_mday'], $parsed_time['tm_hour'], $parsed_time['tm_min'], $parsed_time['tm_sec'] ); return new DateTime( $ymd ); } }// End if. if ( ! function_exists( 'date_timestamp_get' ) ) { /** * Returns the Unix timestamp representing the date. * Reimplementation of DateTime::getTimestamp for PHP < 5.3. :( * * @param DateTime $date DateTime instance. * * @return int */ function date_timestamp_get( DateTime $date ) { return $date->format( 'U' ); } }// End if. cmb2/cmb2/includes/CMB2_Field.php 0000644 00000133415 15151523433 0012330 0 ustar 00 <?php /** * CMB2 field objects * * @since 1.1.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @method string _id() * @method string type() * @method mixed fields() */ class CMB2_Field extends CMB2_Base { /** * The object properties name. * * @var string * @since 2.2.3 */ protected $properties_name = 'args'; /** * Field arguments * * @var mixed * @since 1.1.0 */ public $args = array(); /** * Field group object or false (if no group) * * @var mixed * @since 1.1.0 */ public $group = false; /** * Field meta value * * @var mixed * @since 1.1.0 */ public $value = null; /** * Field meta value * * @var mixed * @since 1.1.0 */ public $escaped_value = null; /** * Grouped Field's current numeric index during the save process * * @var mixed * @since 2.0.0 */ public $index = 0; /** * Array of field options * * @var array * @since 2.0.0 */ protected $field_options = array(); /** * Array of provided field text strings * * @var array * @since 2.0.0 */ protected $strings; /** * The field's render context. In most cases, 'edit', but can be 'display'. * * @var string * @since 2.2.2 */ public $render_context = 'edit'; /** * All CMB2_Field callable field arguments. * Can be used to determine if a field argument is callable. * * @var array */ public static $callable_fields = array( 'default_cb', 'classes_cb', 'options_cb', 'text_cb', 'label_cb', 'render_row_cb', 'display_cb', 'before_group', 'before_group_row', 'before_row', 'before', 'before_field', 'after_field', 'after', 'after_row', 'after_group_row', 'after_group', ); /** * Represents a unique hash representing this field. * * @since 2.2.4 * * @var string */ protected $hash_id = ''; /** * Constructs our field object * * @since 1.1.0 * @param array $args Field arguments. */ public function __construct( $args ) { if ( ! empty( $args['group_field'] ) ) { $this->group = $args['group_field']; $this->object_id = $this->group->object_id; $this->object_type = $this->group->object_type; $this->cmb_id = $this->group->cmb_id; } else { $this->object_id = isset( $args['object_id'] ) && '_' !== $args['object_id'] ? $args['object_id'] : 0; $this->object_type = isset( $args['object_type'] ) ? $args['object_type'] : 'post'; if ( isset( $args['cmb_id'] ) ) { $this->cmb_id = $args['cmb_id']; } } $this->args = $this->_set_field_defaults( $args['field_args'] ); if ( $this->object_id ) { $this->value = $this->get_data(); } } /** * Non-existent methods fallback to checking for field arguments of the same name * * @since 1.1.0 * @param string $name Method name. * @param array $arguments Array of passed-in arguments. * @return mixed Value of field argument */ public function __call( $name, $arguments ) { if ( 'string' === $name ) { return call_user_func_array( array( $this, 'get_string' ), $arguments ); } $key = isset( $arguments[0] ) ? $arguments[0] : ''; return $this->args( $name, $key ); } /** * Retrieves the field id * * @since 1.1.0 * @param boolean $raw Whether to retrieve pre-modidifed id. * @return string Field id */ public function id( $raw = false ) { $id = $raw ? '_id' : 'id'; return $this->args( $id ); } /** * Get a field argument * * @since 1.1.0 * @param string $key Argument to check. * @param string $_key Sub argument to check. * @return mixed Argument value or false if non-existent */ public function args( $key = '', $_key = '' ) { $arg = $this->_data( 'args', $key ); if ( in_array( $key, array( 'default', 'default_cb' ), true ) ) { $arg = $this->get_default(); } elseif ( $_key ) { $arg = isset( $arg[ $_key ] ) ? $arg[ $_key ] : false; } return $arg; } /** * Retrieve a portion of a field property * * @since 1.1.0 * @param string $var Field property to check. * @param string $key Field property array key to check. * @return mixed Queried property value or false */ public function _data( $var, $key = '' ) { $vars = $this->{$var}; if ( $key ) { return array_key_exists( $key, $vars ) ? $vars[ $key ] : false; } return $vars; } /** * Get Field's value * * @since 1.1.0 * @param string $key If value is an array, is used to get array key->value. * @return mixed Field value or false if non-existent */ public function value( $key = '' ) { return $this->_data( 'value', $key ); } /** * Retrieves metadata/option data * * @since 1.0.1 * @param string $field_id Meta key/Option array key. * @param array $args Override arguments. * @return mixed Meta/Option value */ public function get_data( $field_id = '', $args = array() ) { if ( $field_id ) { $args['field_id'] = $field_id; } elseif ( $this->group ) { $args['field_id'] = $this->group->id(); } $a = $this->data_args( $args ); /** * Filter whether to override getting of meta value. * Returning a non 'cmb2_field_no_override_val' value * will effectively short-circuit the value retrieval. * * @since 2.0.0 * * @param mixed $value The value get_metadata() should * return - a single metadata value, * or an array of values. * * @param int $object_id Object ID. * * @param array $args { * An array of arguments for retrieving data * * @type string $type The current object type * @type int $id The current object ID * @type string $field_id The ID of the field being requested * @type bool $repeat Whether current field is repeatable * @type bool $single Whether current field is a single database row * } * * @param CMB2_Field object $field This field object */ $data = apply_filters( 'cmb2_override_meta_value', 'cmb2_field_no_override_val', $this->object_id, $a, $this ); /** * Filter and parameters are documented for 'cmb2_override_meta_value' filter (above). * * The dynamic portion of the hook, $field_id, refers to the current * field id paramater. Returning a non 'cmb2_field_no_override_val' value * will effectively short-circuit the value retrieval. * * @since 2.0.0 */ $data = apply_filters( "cmb2_override_{$a['field_id']}_meta_value", $data, $this->object_id, $a, $this ); // If no override, get value normally. if ( 'cmb2_field_no_override_val' === $data ) { $data = 'options-page' === $a['type'] ? cmb2_options( $a['id'] )->get( $a['field_id'] ) : get_metadata( $a['type'], $a['id'], $a['field_id'], ( $a['single'] || $a['repeat'] ) ); } if ( $this->group ) { $data = is_array( $data ) && isset( $data[ $this->group->index ][ $this->args( '_id' ) ] ) ? $data[ $this->group->index ][ $this->args( '_id' ) ] : false; } return $data; } /** * Updates metadata/option data. * * @since 1.0.1 * @param mixed $new_value Value to update data with. * @param bool $single Whether data is an array (add_metadata). * @return mixed */ public function update_data( $new_value, $single = true ) { $a = $this->data_args( array( 'single' => $single, ) ); $a['value'] = $a['repeat'] ? array_values( $new_value ) : $new_value; /** * Filter whether to override saving of meta value. * Returning a non-null value will effectively short-circuit the function. * * @since 2.0.0 * * @param null|bool $check Whether to allow updating metadata for the given type. * * @param array $args { * Array of data about current field including: * * @type string $value The value to set * @type string $type The current object type * @type int $id The current object ID * @type string $field_id The ID of the field being updated * @type bool $repeat Whether current field is repeatable * @type bool $single Whether current field is a single database row * } * * @param array $field_args All field arguments * * @param CMB2_Field object $field This field object */ $override = apply_filters( 'cmb2_override_meta_save', null, $a, $this->args(), $this ); /** * Filter and parameters are documented for 'cmb2_override_meta_save' filter (above). * * The dynamic portion of the hook, $a['field_id'], refers to the current * field id paramater. Returning a non-null value * will effectively short-circuit the function. * * @since 2.0.0 */ $override = apply_filters( "cmb2_override_{$a['field_id']}_meta_save", $override, $a, $this->args(), $this ); // If override, return that. if ( null !== $override ) { return $override; } // Options page handling (or temp data store). if ( 'options-page' === $a['type'] || empty( $a['id'] ) ) { return cmb2_options( $a['id'] )->update( $a['field_id'], $a['value'], false, $a['single'] ); } // Add metadata if not single. if ( ! $a['single'] ) { return add_metadata( $a['type'], $a['id'], $a['field_id'], $a['value'], false ); } // Delete meta if we have an empty array. if ( is_array( $a['value'] ) && empty( $a['value'] ) ) { return delete_metadata( $a['type'], $a['id'], $a['field_id'], $this->value ); } // Update metadata. return update_metadata( $a['type'], $a['id'], $a['field_id'], $a['value'] ); } /** * Removes/updates metadata/option data. * * @since 1.0.1 * @param string $old Old value. * @return mixed */ public function remove_data( $old = '' ) { $a = $this->data_args( array( 'old' => $old, ) ); /** * Filter whether to override removing of meta value. * Returning a non-null value will effectively short-circuit the function. * * @since 2.0.0 * * @param null|bool $delete Whether to allow metadata deletion of the given type. * @param array $args Array of data about current field including: * 'type' : Current object type * 'id' : Current object ID * 'field_id' : Current Field ID * 'repeat' : Whether current field is repeatable * 'single' : Whether to save as a * single meta value * @param array $field_args All field arguments * @param CMB2_Field object $field This field object */ $override = apply_filters( 'cmb2_override_meta_remove', null, $a, $this->args(), $this ); /** * Filter whether to override removing of meta value. * * The dynamic portion of the hook, $a['field_id'], refers to the current * field id paramater. Returning a non-null value * will effectively short-circuit the function. * * @since 2.0.0 * * @param null|bool $delete Whether to allow metadata deletion of the given type. * @param array $args Array of data about current field including: * 'type' : Current object type * 'id' : Current object ID * 'field_id' : Current Field ID * 'repeat' : Whether current field is repeatable * 'single' : Whether to save as a * single meta value * @param array $field_args All field arguments * @param CMB2_Field object $field This field object */ $override = apply_filters( "cmb2_override_{$a['field_id']}_meta_remove", $override, $a, $this->args(), $this ); // If no override, remove as usual. if ( null !== $override ) { return $override; } // End if. // Option page handling. elseif ( 'options-page' === $a['type'] || empty( $a['id'] ) ) { return cmb2_options( $a['id'] )->remove( $a['field_id'] ); } // Remove metadata. return delete_metadata( $a['type'], $a['id'], $a['field_id'], $old ); } /** * Data variables for get/set data methods * * @since 1.1.0 * @param array $args Override arguments. * @return array Updated arguments */ public function data_args( $args = array() ) { $args = wp_parse_args( $args, array( 'type' => $this->object_type, 'id' => $this->object_id, 'field_id' => $this->id( true ), 'repeat' => $this->args( 'repeatable' ), 'single' => ! $this->args( 'multiple' ), ) ); return $args; } /** * Checks if field has a registered sanitization callback * * @since 1.0.1 * @param mixed $meta_value Meta value. * @return mixed Possibly sanitized meta value */ public function sanitization_cb( $meta_value ) { if ( $this->args( 'repeatable' ) && is_array( $meta_value ) ) { // Remove empties. $meta_value = array_filter( $meta_value ); } // Check if the field has a registered validation callback. $cb = $this->maybe_callback( 'sanitization_cb' ); if ( false === $cb ) { // If requesting NO validation, return meta value. return $meta_value; } elseif ( $cb ) { // Ok, callback is good, let's run it. return call_user_func( $cb, $meta_value, $this->args(), $this ); } $sanitizer = new CMB2_Sanitize( $this, $meta_value ); $field_type = $this->type(); /** * Filter the value before it is saved. * * The dynamic portion of the hook name, $field_type, refers to the field type. * * Passing a non-null value to the filter will short-circuit saving * the field value, saving the passed value instead. * * @param bool|mixed $override_value Sanitization/Validation override value to return. * Default: null. false to skip it. * @param mixed $value The value to be saved to this field. * @param int $object_id The ID of the object where the value will be saved * @param array $field_args The current field's arguments * @param object $sanitizer This `CMB2_Sanitize` object */ $override_value = apply_filters( "cmb2_sanitize_{$field_type}", null, $sanitizer->value, $this->object_id, $this->args(), $sanitizer ); if ( null !== $override_value ) { return $override_value; } // Sanitization via 'CMB2_Sanitize'. return $sanitizer->{$field_type}(); } /** * Process $_POST data to save this field's value * * @since 2.0.3 * @param array $data_to_save $_POST data to check. * @return array|int|bool Result of save, false on failure */ public function save_field_from_data( array $data_to_save ) { $this->data_to_save = $data_to_save; $meta_value = isset( $this->data_to_save[ $this->id( true ) ] ) ? $this->data_to_save[ $this->id( true ) ] : null; return $this->save_field( $meta_value ); } /** * Sanitize/store a value to this field * * @since 2.0.0 * @param array $meta_value Desired value to sanitize/store. * @return array|int|bool Result of save. false on failure */ public function save_field( $meta_value ) { $updated = false; $action = ''; $new_value = $this->sanitization_cb( $meta_value ); if ( ! $this->args( 'save_field' ) ) { // Nothing to see here. $action = 'disabled'; } elseif ( $this->args( 'multiple' ) && ! $this->args( 'repeatable' ) && ! $this->group ) { $this->remove_data(); $count = 0; if ( ! empty( $new_value ) ) { foreach ( $new_value as $add_new ) { if ( $this->update_data( $add_new, false ) ) { $count++; } } } $updated = $count ? $count : false; $action = 'repeatable'; } elseif ( ! CMB2_Utils::isempty( $new_value ) && $new_value !== $this->get_data() ) { $updated = $this->update_data( $new_value ); $action = 'updated'; } elseif ( CMB2_Utils::isempty( $new_value ) ) { $updated = $this->remove_data(); $action = 'removed'; } if ( $updated ) { $this->value = $this->get_data(); $this->escaped_value = null; } $field_id = $this->id( true ); /** * Hooks after save field action. * * @since 2.2.0 * * @param string $field_id the current field id paramater. * @param bool $updated Whether the metadata update action occurred. * @param string $action Action performed. Could be "repeatable", "updated", or "removed". * @param CMB2_Field object $field This field object */ do_action( 'cmb2_save_field', $field_id, $updated, $action, $this ); /** * Hooks after save field action. * * The dynamic portion of the hook, $field_id, refers to the * current field id paramater. * * @since 2.2.0 * * @param bool $updated Whether the metadata update action occurred. * @param string $action Action performed. Could be "repeatable", "updated", or "removed". * @param CMB2_Field object $field This field object */ do_action( "cmb2_save_field_{$field_id}", $updated, $action, $this ); return $updated; } /** * Determine if current type is exempt from escaping * * @since 1.1.0 * @return bool True if exempt */ public function escaping_exception() { // These types cannot be escaped. return in_array( $this->type(), array( 'file_list', 'multicheck', 'text_datetime_timestamp_timezone', ) ); } /** * Determine if current type cannot be repeatable * * @since 1.1.0 * @param string $type Field type to check. * @return bool True if type cannot be repeatable */ public function repeatable_exception( $type ) { // These types cannot be repeatable. $internal_fields = array( // Use file_list instead. 'file' => 1, 'radio' => 1, 'title' => 1, 'wysiwyg' => 1, 'checkbox' => 1, 'radio_inline' => 1, 'taxonomy_radio' => 1, 'taxonomy_radio_inline' => 1, 'taxonomy_radio_hierarchical' => 1, 'taxonomy_select' => 1, 'taxonomy_select_hierarchical' => 1, 'taxonomy_multicheck' => 1, 'taxonomy_multicheck_inline' => 1, 'taxonomy_multicheck_hierarchical' => 1, ); /** * Filter field types that are non-repeatable. * * Note that this does *not* allow overriding the default non-repeatable types. * * @since 2.1.1 * * @param array $fields Array of fields designated as non-repeatable. Note that the field names are *keys*, * and not values. The value can be anything, because it is meaningless. Example: * array( 'my_custom_field' => 1 ) */ $all_fields = array_merge( apply_filters( 'cmb2_non_repeatable_fields', array() ), $internal_fields ); return isset( $all_fields[ $type ] ); } /** * Determine if current type has its own defaults field-arguments method. * * @since 2.2.6 * @param string $type Field type to check. * @return bool True if has own method. */ public function has_args_method( $type ) { // These types have their own arguments parser. $type_methods = array( 'group' => 'set_field_defaults_group', 'wysiwyg' => 'set_field_defaults_wysiwyg', ); if ( isset( $type_methods[ $type ] ) ) { return $type_methods[ $type ]; } $all_or_nothing_types = array_flip( apply_filters( 'cmb2_all_or_nothing_types', array( 'select', 'radio', 'radio_inline', 'taxonomy_select', 'taxonomy_select_hierarchical', 'taxonomy_radio', 'taxonomy_radio_inline', 'taxonomy_radio_hierarchical', ), $this ) ); if ( isset( $all_or_nothing_types[ $type ] ) ) { return 'set_field_defaults_all_or_nothing_types'; } return false; } /** * Escape the value before output. Defaults to 'esc_attr()' * * @since 1.0.1 * @param callable|string $func Escaping function (if not esc_attr()). * @param mixed $meta_value Meta value. * @return mixed Final value. */ public function escaped_value( $func = 'esc_attr', $meta_value = '' ) { if ( null !== $this->escaped_value ) { return $this->escaped_value; } $meta_value = $meta_value ? $meta_value : $this->value(); // Check if the field has a registered escaping callback. if ( $cb = $this->maybe_callback( 'escape_cb' ) ) { // Ok, callback is good, let's run it. return call_user_func( $cb, $meta_value, $this->args(), $this ); } $field_type = $this->type(); /** * Filter the value for escaping before it is ouput. * * The dynamic portion of the hook name, $field_type, refers to the field type. * * Passing a non-null value to the filter will short-circuit the built-in * escaping for this field. * * @param bool|mixed $override_value Escaping override value to return. * Default: null. false to skip it. * @param mixed $meta_value The value to be output. * @param array $field_args The current field's arguments. * @param object $field This `CMB2_Field` object. */ $esc = apply_filters( "cmb2_types_esc_{$field_type}", null, $meta_value, $this->args(), $this ); if ( null !== $esc ) { return $esc; } if ( false === $cb || $this->escaping_exception() ) { // If requesting NO escaping, return meta value. return $this->val_or_default( $meta_value ); } // escaping function passed in? $func = $func ? $func : 'esc_attr'; $meta_value = $this->val_or_default( $meta_value ); if ( is_array( $meta_value ) ) { foreach ( $meta_value as $key => $value ) { $meta_value[ $key ] = call_user_func( $func, $value ); } } else { $meta_value = call_user_func( $func, $meta_value ); } $this->escaped_value = $meta_value; return $this->escaped_value; } /** * Return non-empty value or field default if value IS empty * * @since 2.0.0 * @param mixed $meta_value Field value. * @return mixed Field value, or default value */ public function val_or_default( $meta_value ) { return ! CMB2_Utils::isempty( $meta_value ) ? $meta_value : $this->get_default(); } /** * Offset a time value based on timezone * * @since 1.0.0 * @return string Offset time string */ public function field_timezone_offset() { return CMB2_Utils::timezone_offset( $this->field_timezone() ); } /** * Return timezone string * * @since 1.0.0 * @return string Timezone string */ public function field_timezone() { $value = ''; // Is timezone arg set? if ( $this->args( 'timezone' ) ) { $value = $this->args( 'timezone' ); } // End if. // Is there another meta key with a timezone stored as its value we should use? elseif ( $this->args( 'timezone_meta_key' ) ) { $value = $this->get_data( $this->args( 'timezone_meta_key' ) ); } return $value; } /** * Format the timestamp field value based on the field date/time format arg * * @since 2.0.0 * @param int $meta_value Timestamp. * @param string $format Either date_format or time_format. * @return string Formatted date */ public function format_timestamp( $meta_value, $format = 'date_format' ) { return date( stripslashes( $this->args( $format ) ), $meta_value ); } /** * Return a formatted timestamp for a field * * @since 2.0.0 * @param string $format Either date_format or time_format. * @param string|int $meta_value Optional meta value to check. * @return string Formatted date */ public function get_timestamp_format( $format = 'date_format', $meta_value = 0 ) { $meta_value = $meta_value ? $meta_value : $this->escaped_value(); if ( empty( $meta_value ) ) { $meta_value = $this->get_default(); } $meta_value = CMB2_Utils::make_valid_time_stamp( $meta_value ); if ( empty( $meta_value ) ) { return ''; } return is_array( $meta_value ) ? array_map( array( $this, 'format_timestamp' ), $meta_value, $format ) : $this->format_timestamp( $meta_value, $format ); } /** * Get timestamp from text date * * @since 2.2.0 * @param string $value Date value. * @return mixed Unix timestamp representing the date. */ public function get_timestamp_from_value( $value ) { $timestamp = CMB2_Utils::get_timestamp_from_value( $value, $this->args( 'date_format' ) ); if ( empty( $timestamp ) && CMB2_Utils::is_valid_date( $value ) ) { $timestamp = CMB2_Utils::make_valid_time_stamp( $value ); } return $timestamp; } /** * Get field render callback and Render the field row * * @since 1.0.0 */ public function render_field() { $this->render_context = 'edit'; $this->peform_param_callback( 'render_row_cb' ); // For chaining. return $this; } /** * Default field render callback * * @since 2.1.1 */ public function render_field_callback() { // If field is requesting to not be shown on the front-end. if ( ! is_admin() && ! $this->args( 'on_front' ) ) { return; } // If field is requesting to be conditionally shown. if ( ! $this->should_show() ) { return; } $field_type = $this->type(); /** * Hook before field row begins. * * @param CMB2_Field $field The current field object. */ do_action( 'cmb2_before_field_row', $this ); /** * Hook before field row begins. * * The dynamic portion of the hook name, $field_type, refers to the field type. * * @param CMB2_Field $field The current field object. */ do_action( "cmb2_before_{$field_type}_field_row", $this ); $this->peform_param_callback( 'before_row' ); printf( "<div class=\"cmb-row %s\" data-fieldtype=\"%s\">\n", $this->row_classes(), $field_type ); if ( ! $this->args( 'show_names' ) ) { echo "\n\t<div class=\"cmb-td\">\n"; $this->peform_param_callback( 'label_cb' ); } else { if ( $this->get_param_callback_result( 'label_cb' ) ) { echo '<div class="cmb-th">', $this->peform_param_callback( 'label_cb' ), '</div>'; } echo "\n\t<div class=\"cmb-td\">\n"; } $this->peform_param_callback( 'before' ); $types = new CMB2_Types( $this ); $types->render(); $this->peform_param_callback( 'after' ); echo "\n\t</div>\n</div>"; $this->peform_param_callback( 'after_row' ); /** * Hook after field row ends. * * The dynamic portion of the hook name, $field_type, refers to the field type. * * @param CMB2_Field $field The current field object. */ do_action( "cmb2_after_{$field_type}_field_row", $this ); /** * Hook after field row ends. * * @param CMB2_Field $field The current field object. */ do_action( 'cmb2_after_field_row', $this ); // For chaining. return $this; } /** * The default label_cb callback (if not a title field) * * @since 2.1.1 * @return string Label html markup. */ public function label() { if ( ! $this->args( 'name' ) ) { return ''; } $style = ! $this->args( 'show_names' ) ? ' style="display:none;"' : ''; return sprintf( "\n" . '<label%1$s for="%2$s">%3$s</label>' . "\n", $style, $this->id(), $this->args( 'name' ) ); } /** * Defines the classes for the current CMB2 field row * * @since 2.0.0 * @return string Space concatenated list of classes */ public function row_classes() { $classes = array(); /** * By default, 'text_url' and 'text' fields get table-like styling * * @since 2.0.0 * * @param array $field_types The types of fields which should get the 'table-layout' class */ $repeat_table_rows_types = apply_filters( 'cmb2_repeat_table_row_types', array( 'text_url', 'text', ) ); $conditional_classes = array( 'cmb-type-' . str_replace( '_', '-', sanitize_html_class( $this->type() ) ) => true, 'cmb2-id-' . str_replace( '_', '-', sanitize_html_class( $this->id() ) ) => true, 'cmb-repeat' => $this->args( 'repeatable' ), 'cmb-repeat-group-field' => $this->group, 'cmb-inline' => $this->args( 'inline' ), 'table-layout' => 'edit' === $this->render_context && in_array( $this->type(), $repeat_table_rows_types ), ); foreach ( $conditional_classes as $class => $condition ) { if ( $condition ) { $classes[] = $class; } } if ( $added_classes = $this->args( 'classes' ) ) { $added_classes = is_array( $added_classes ) ? implode( ' ', $added_classes ) : (string) $added_classes; } elseif ( $added_classes = $this->get_param_callback_result( 'classes_cb' ) ) { $added_classes = is_array( $added_classes ) ? implode( ' ', $added_classes ) : (string) $added_classes; } if ( $added_classes ) { $classes[] = esc_attr( $added_classes ); } /** * Globally filter row classes * * @since 2.0.0 * * @param string $classes Space-separated list of row classes * @param CMB2_Field object $field This field object */ return apply_filters( 'cmb2_row_classes', implode( ' ', $classes ), $this ); } /** * Get field display callback and render the display value in the column. * * @since 2.2.2 */ public function render_column() { $this->render_context = 'display'; $this->peform_param_callback( 'display_cb' ); // For chaining. return $this; } /** * The method to fetch the value for this field for the REST API. * * @since 2.5.0 */ public function get_rest_value() { $field_type = $this->type(); $field_id = $this->id( true ); if ( $cb = $this->maybe_callback( 'rest_value_cb' ) ) { add_filter( "cmb2_get_rest_value_for_{$field_id}", $cb, 99 ); } $value = $this->get_data(); /** * Filter the value before it is sent to the REST request. * * @since 2.5.0 * * @param mixed $value The value from CMB2_Field::get_data() * @param CMB2_Field $field This field object. */ $value = apply_filters( 'cmb2_get_rest_value', $value, $this ); /** * Filter the value before it is sent to the REST request. * * The dynamic portion of the hook name, $field_type, refers to the field type. * * @since 2.5.0 * * @param mixed $value The value from CMB2_Field::get_data() * @param CMB2_Field $field This field object. */ $value = apply_filters( "cmb2_get_rest_value_{$field_type}", $value, $this ); /** * Filter the value before it is sent to the REST request. * * The dynamic portion of the hook name, $field_id, refers to the field id. * * @since 2.5.0 * * @param mixed $value The value from CMB2_Field::get_data() * @param CMB2_Field $field This field object. */ return apply_filters( "cmb2_get_rest_value_for_{$field_id}", $value, $this ); } /** * Get a field object for a supporting field. (e.g. file field) * * @since 2.7.0 * * @return CMB2_Field|bool Supporting field object, if supported. */ public function get_supporting_field() { $suffix = $this->args( 'has_supporting_data' ); if ( empty( $suffix ) ) { return false; } return $this->get_field_clone( array( 'id' => $this->_id( '', false ) . $suffix, 'sanitization_cb' => false, ) ); } /** * Default callback to outputs field value in a display format. * * @since 2.2.2 */ public function display_value_callback() { // If field is requesting to be conditionally shown. if ( ! $this->should_show() ) { return; } $display = new CMB2_Field_Display( $this ); $field_type = $this->type(); /** * A filter to bypass the default display. * * The dynamic portion of the hook name, $field_type, refers to the field type. * * Passing a non-null value to the filter will short-circuit the default display. * * @param bool|mixed $pre_output Default null value. * @param CMB2_Field $field This field object. * @param CMB2_Field_Display $display The `CMB2_Field_Display` object. */ $pre_output = apply_filters( "cmb2_pre_field_display_{$field_type}", null, $this, $display ); if ( null !== $pre_output ) { echo $pre_output; return; } $this->peform_param_callback( 'before_display_wrap' ); printf( "<div class=\"cmb-column %s\" data-fieldtype=\"%s\">\n", $this->row_classes(), $field_type ); $this->peform_param_callback( 'before_display' ); CMB2_Field_Display::get( $this )->display(); $this->peform_param_callback( 'after_display' ); echo "\n</div>"; $this->peform_param_callback( 'after_display_wrap' ); // For chaining. return $this; } /** * Replaces a hash key - {#} - with the repeatable index * * @since 1.2.0 * @param string $value Value to update. * @return string Updated value */ public function replace_hash( $value ) { // Replace hash with 1 based count. return str_replace( '{#}', ( $this->index + 1 ), $value ); } /** * Retrieve text parameter from field's text array (if it has one), or use fallback text * For back-compatibility, falls back to checking the options array. * * @since 2.2.2 * @param string $text_key Key in field's text array. * @param string $fallback Fallback text. * @return string Text */ public function get_string( $text_key, $fallback ) { // If null, populate with our field strings values. if ( null === $this->strings ) { $this->strings = (array) $this->args['text']; if ( is_callable( $this->args['text_cb'] ) ) { $strings = call_user_func( $this->args['text_cb'], $this ); if ( $strings && is_array( $strings ) ) { $this->strings += $strings; } } } // If we have that string value, send it back. if ( isset( $this->strings[ $text_key ] ) ) { return $this->strings[ $text_key ]; } // Check options for back-compat. $string = $this->options( $text_key ); return $string ? $string : $fallback; } /** * Retrieve options args. * * @since 2.0.0 * @param string $key Specific option to retrieve. * @return array|mixed Array of options or specific option. */ public function options( $key = '' ) { if ( empty( $this->field_options ) ) { $this->set_options(); } if ( $key ) { return array_key_exists( $key, $this->field_options ) ? $this->field_options[ $key ] : false; } return $this->field_options; } /** * Generates/sets options args. Calls options_cb if it exists. * * @since 2.2.5 * * @return array Array of options */ public function set_options() { $this->field_options = (array) $this->args['options']; if ( is_callable( $this->args['options_cb'] ) ) { $options = call_user_func( $this->args['options_cb'], $this ); if ( $options && is_array( $options ) ) { $this->field_options = $options + $this->field_options; } } return $this->field_options; } /** * Store JS dependencies as part of the field args. * * @since 2.2.0 * @param array $dependencies Dependies to register for this field. */ public function add_js_dependencies( $dependencies = array() ) { foreach ( (array) $dependencies as $dependency ) { $this->args['js_dependencies'][ $dependency ] = $dependency; } CMB2_JS::add_dependencies( $dependencies ); } /** * Send field data to JS. * * @since 2.2.0 */ public function register_js_data() { if ( $this->group ) { CMB2_JS::add_field_data( $this->group ); } return CMB2_JS::add_field_data( $this ); } /** * Get an array of some of the field data to be used in the Javascript. * * @since 2.2.4 * * @return array */ public function js_data() { return array( 'label' => $this->args( 'name' ), 'id' => $this->id( true ), 'type' => $this->type(), 'hash' => $this->hash_id(), 'box' => $this->cmb_id, 'id_attr' => $this->id(), 'name_attr' => $this->args( '_name' ), 'default' => $this->get_default(), 'group' => $this->group_id(), 'index' => $this->group ? $this->group->index : null, ); } /** * Returns a unique hash representing this field. * * @since 2.2.4 * * @return string */ public function hash_id() { if ( '' === $this->hash_id ) { $this->hash_id = CMB2_Utils::generate_hash( $this->cmb_id . '||' . $this->id() ); } return $this->hash_id; } /** * Gets the id of the group field if this field is part of a group. * * @since 2.2.4 * * @return string */ public function group_id() { return $this->group ? $this->group->id( true ) : ''; } /** * Get CMB2_Field default value, either from default param or default_cb param. * * @since 0.2.2 * * @return mixed Default field value */ public function get_default() { $default = $this->args['default']; if ( null !== $default ) { return apply_filters( 'cmb2_default_filter', $default, $this ); } $param = is_callable( $this->args['default_cb'] ) ? 'default_cb' : 'default'; $default = $this->args['default'] = $this->get_param_callback_result( $param ); // Allow a filter override of the default value. return apply_filters( 'cmb2_default_filter', $this->args['default'], $this ); } /** * Fills in empty field parameters with defaults * * @since 1.1.0 * * @param array $args Field config array. * @return array Modified field config array. */ public function _set_field_defaults( $args ) { $defaults = $this->get_default_field_args( $args ); /** * Filter the CMB2 Field defaults. * * @since 2.6.0 * @param array $defaults Metabox field config array defaults. * @param string $id Field id for the current field to allow for selective filtering. * @param string $type Field type for the current field to allow for selective filtering. * @param CMB2_Field object $field This field object. */ $defaults = apply_filters( 'cmb2_field_defaults', $defaults, $args['id'], $args['type'], $this ); // Set up blank or default values for empty ones. $args = wp_parse_args( $args, $defaults ); /** * Filtering the CMB2 Field arguments once merged with the defaults, but before further processing. * * @since 2.6.0 * @param array $args Metabox field config array defaults. * @param CMB2_Field object $field This field object. */ $args = apply_filters( 'cmb2_field_arguments_raw', $args, $this ); /* * Deprecated usage: * * 'std' -- use 'default' (no longer works) * 'row_classes' -- use 'class', or 'class_cb' * 'default' -- as callback (use default_cb) */ $args = $this->convert_deprecated_params( $args ); $args['repeatable'] = $args['repeatable'] && ! $this->repeatable_exception( $args['type'] ); $args['inline'] = $args['inline'] || false !== stripos( $args['type'], '_inline' ); $args['_id'] = $args['id']; $args['_name'] = $args['id']; if ( $method = $this->has_args_method( $args['type'] ) ) { $args = $this->{$method}( $args ); } if ( $this->group ) { $args = $this->set_group_sub_field_defaults( $args ); } $with_supporting = array( // CMB2_Sanitize::_save_file_id_value()/CMB2_Sanitize::_get_group_file_value_array(). 'file' => '_id', // See CMB2_Sanitize::_save_utc_value(). 'text_datetime_timestamp_timezone' => '_utc', ); $args['has_supporting_data'] = isset( $with_supporting[ $args['type'] ] ) ? $with_supporting[ $args['type'] ] : false; // Repeatable fields require jQuery sortable library. if ( ! empty( $args['repeatable'] ) ) { CMB2_JS::add_dependencies( 'jquery-ui-sortable' ); } /** * Filter the CMB2 Field arguments after processing. * * @since 2.6.0 * @param array $args Metabox field config array after processing. * @param CMB2_Field object $field This field object. */ return apply_filters( 'cmb2_field_arguments', $args, $this ); } /** * Sets default arguments for the group field types. * * @since 2.2.6 * * @param array $args Field config array. * @return array Modified field config array. */ protected function set_field_defaults_group( $args ) { $args['options'] = wp_parse_args( $args['options'], array( 'add_button' => esc_html__( 'Add Group', 'cmb2' ), 'remove_button' => esc_html__( 'Remove Group', 'cmb2' ), 'remove_confirm' => '', ) ); return $args; } /** * Sets default arguments for the wysiwyg field types. * * @since 2.2.6 * * @param array $args Field config array. * @return array Modified field config array. */ protected function set_field_defaults_wysiwyg( $args ) { $args['id'] = strtolower( str_ireplace( '-', '_', $args['id'] ) ); $args['options']['textarea_name'] = $args['_name']; return $args; } /** * Sets default arguments for the all-or-nothing field types. * * @since 2.2.6 * * @param array $args Field config array. * @return array Modified field config array. */ protected function set_field_defaults_all_or_nothing_types( $args ) { $args['show_option_none'] = isset( $args['show_option_none'] ) ? $args['show_option_none'] : null; $args['show_option_none'] = true === $args['show_option_none'] ? esc_html__( 'None', 'cmb2' ) : $args['show_option_none']; if ( null === $args['show_option_none'] ) { $off_by_default = in_array( $args['type'], array( 'select', 'radio', 'radio_inline' ), true ); $args['show_option_none'] = $off_by_default ? false : esc_html__( 'None', 'cmb2' ); } return $args; } /** * Sets default arguments for group sub-fields. * * @since 2.2.6 * * @param array $args Field config array. * @return array Modified field config array. */ protected function set_group_sub_field_defaults( $args ) { $args['id'] = $this->group->args( 'id' ) . '_' . $this->group->index . '_' . $args['id']; $args['_name'] = $this->group->args( 'id' ) . '[' . $this->group->index . '][' . $args['_name'] . ']'; return $args; } /** * Gets the default arguments for all fields. * * @since 2.2.6 * * @param array $args Field config array. * @return array Field defaults. */ protected function get_default_field_args( $args ) { $type = isset( $args['type'] ) ? $args['type'] : ''; return array( 'type' => $type, 'name' => '', 'desc' => '', 'before' => '', 'after' => '', 'options' => array(), 'options_cb' => '', 'text' => array(), 'text_cb' => '', 'attributes' => array(), 'protocols' => null, 'default' => null, 'default_cb' => '', 'classes' => null, 'classes_cb' => '', 'select_all_button' => true, 'multiple' => false, 'repeatable' => 'group' === $type, 'inline' => false, 'on_front' => true, 'show_names' => true, 'save_field' => true, // Will not save if false. 'date_format' => 'm\/d\/Y', 'time_format' => 'h:i A', 'description' => isset( $args['desc'] ) ? $args['desc'] : '', 'preview_size' => 'file' === $type ? array( 350, 350 ) : array( 50, 50 ), 'render_row_cb' => array( $this, 'render_field_callback' ), 'display_cb' => array( $this, 'display_value_callback' ), 'label_cb' => 'title' !== $type ? array( $this, 'label' ) : '', 'column' => false, 'js_dependencies' => array(), 'show_in_rest' => null, 'char_counter' => false, 'char_max' => false, 'char_max_enforce' => false, ); } /** * Get default field arguments specific to this CMB2 object. * * @since 2.2.0 * @param array $field_args Metabox field config array. * @param CMB2_Field $field_group (optional) CMB2_Field object (group parent). * @return array Array of field arguments. */ protected function get_default_args( $field_args, $field_group = null ) { $args = parent::get_default_args( array(), $this->group ); if ( isset( $field_args['field_args'] ) ) { $args = wp_parse_args( $field_args, $args ); } else { $args['field_args'] = wp_parse_args( $field_args, $this->args ); } return $args; } /** * Returns a cloned version of this field object, but with * modified/overridden field arguments. * * @since 2.2.2 * @param array $field_args Array of field arguments, or entire array of * arguments for CMB2_Field. * * @return CMB2_Field The new CMB2_Field instance. */ public function get_field_clone( $field_args ) { return $this->get_new_field( $field_args ); } /** * Returns the CMB2 instance this field is registered to. * * @since 2.2.2 * * @return CMB2|WP_Error If new CMB2_Field is called without cmb_id arg, returns error. */ public function get_cmb() { if ( ! $this->cmb_id ) { return new WP_Error( 'no_cmb_id', esc_html__( 'Sorry, this field does not have a cmb_id specified.', 'cmb2' ) ); } return cmb2_get_metabox( $this->cmb_id, $this->object_id, $this->object_type ); } /** * Converts deprecated field parameters to the current/proper parameter, and throws a deprecation notice. * * @since 2.2.3 * @param array $args Metabox field config array. * @return array Modified field config array. */ protected function convert_deprecated_params( $args ) { if ( isset( $args['row_classes'] ) ) { // We'll let this one be. // $this->deprecated_param( __CLASS__ . '::__construct()', '2.2.3', self::DEPRECATED_PARAM, 'row_classes', 'classes' ); // row_classes param could be a callback. This is definitely deprecated. if ( is_callable( $args['row_classes'] ) ) { $this->deprecated_param( __CLASS__ . '::__construct()', '2.2.3', self::DEPRECATED_CB_PARAM, 'row_classes', 'classes_cb' ); $args['classes_cb'] = $args['row_classes']; $args['classes'] = null; } else { $args['classes'] = $args['row_classes']; } unset( $args['row_classes'] ); } // default param can be passed a callback as well. if ( is_callable( $args['default'] ) ) { $this->deprecated_param( __CLASS__ . '::__construct()', '2.2.3', self::DEPRECATED_CB_PARAM, 'default', 'default_cb' ); $args['default_cb'] = $args['default']; $args['default'] = null; } // options param can be passed a callback as well. if ( is_callable( $args['options'] ) ) { $this->deprecated_param( __CLASS__ . '::__construct()', '2.2.3', self::DEPRECATED_CB_PARAM, 'options', 'options_cb' ); $args['options_cb'] = $args['options']; $args['options'] = array(); } return $args; } } cmb2/cmb2/includes/CMB2.php 0000644 00000152073 15151523433 0011226 0 ustar 00 <?php /** * CMB2 - The core metabox object * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @property-read string $cmb_id * @property-read array $meta_box * @property-read array $updated * @property-read bool $has_columns * @property-read array $tax_metaboxes_to_remove */ /** * The main CMB2 object for storing box data/properties. */ class CMB2 extends CMB2_Base { /** * Supported CMB2 object types * * @var array * @since 2.11.0 */ protected $core_object_types = array( 'post', 'user', 'comment', 'term', 'options-page' ); /** * The object properties name. * * @var string * @since 2.2.3 */ protected $properties_name = 'meta_box'; /** * Metabox Config array * * @var array * @since 0.9.0 */ protected $meta_box = array(); /** * Type of object registered for metabox. (e.g., post, user, or comment) * * @var string * @since 1.0.0 */ protected $mb_object_type = null; /** * List of fields that are changed/updated on save * * @var array * @since 1.1.0 */ protected $updated = array(); /** * Metabox Defaults * * @var array * @since 1.0.1 */ protected $mb_defaults = array( 'id' => '', 'title' => '', // Post type slug, or 'user', 'term', 'comment', or 'options-page'. 'object_types' => array(), /** * The context within the screen where the boxes should display. Available contexts vary * from screen to screen. Post edit screen contexts include 'normal', 'side', and 'advanced'. * * For placement in locations outside of a metabox, other options include: * 'form_top', 'before_permalink', 'after_title', 'after_editor' * * Comments screen contexts include 'normal' and 'side'. Default is 'normal'. */ 'context' => 'normal', 'priority' => 'high', // Or 10 for options pages. 'show_names' => true, // Show field names on the left. 'show_on_cb' => null, // Callback to determine if metabox should display. 'show_on' => array(), // Post IDs or page templates to display this metabox. overrides 'show_on_cb'. 'cmb_styles' => true, // Include CMB2 stylesheet. 'enqueue_js' => true, // Include CMB2 JS. 'fields' => array(), /** * Handles hooking CMB2 forms/metaboxes into the post/attachement/user/options-page screens * and handles hooking in and saving those fields. */ 'hookup' => true, 'save_fields' => true, // Will not save during hookup if false. 'closed' => false, // Default metabox to being closed. 'taxonomies' => array(), 'new_user_section' => 'add-new-user', // or 'add-existing-user'. 'new_term_section' => true, 'show_in_rest' => false, 'classes' => null, // Optionally add classes to the CMB2 wrapper. 'classes_cb' => '', // Optionally add classes to the CMB2 wrapper (via a callback). /* * The following parameter is for post alternate-context metaboxes only. * * To output the fields 'naked' (without a postbox wrapper/style), then * add a `'remove_box_wrap' => true` to your metabox registration array. */ 'remove_box_wrap' => false, /* * The following parameter is any additional arguments passed as $callback_args * to add_meta_box, if/when applicable. * * CMB2 does not use these arguments in the add_meta_box callback, however, these args * are parsed for certain special properties, like determining Gutenberg/block-editor * compatibility. * * Examples: * * - Make sure default editor is used as metabox is not compatible with block editor * [ '__block_editor_compatible_meta_box' => false/true ] * * - Or declare this box exists for backwards compatibility * [ '__back_compat_meta_box' => false ] * * More: https://wordpress.org/gutenberg/handbook/extensibility/meta-box/ */ 'mb_callback_args' => null, /* * The following parameters are for options-page metaboxes, * and several are passed along to add_menu_page()/add_submenu_page() */ // 'menu_title' => null, // Falls back to 'title' (above). Do not define here so we can set a fallback. 'message_cb' => '', // Optionally define the options-save message (via a callback). 'option_key' => '', // The actual option key and admin menu page slug. 'parent_slug' => '', // Used as first param in add_submenu_page(). 'capability' => 'manage_options', // Cap required to view options-page. 'icon_url' => '', // Menu icon. Only applicable if 'parent_slug' is left empty. 'position' => null, // Menu position. Only applicable if 'parent_slug' is left empty. 'admin_menu_hook' => 'admin_menu', // Alternately 'network_admin_menu' to add network-level options page. 'display_cb' => false, // Override the options-page form output (CMB2_Hookup::options_page_output()). 'save_button' => '', // The text for the options-page save button. Defaults to 'Save'. 'disable_settings_errors' => false, // On settings pages (not options-general.php sub-pages), allows disabling. 'tab_group' => '', // Tab-group identifier, enables options page tab navigation. // 'tab_title' => null, // Falls back to 'title' (above). Do not define here so we can set a fallback. // 'autoload' => true, // Defaults to true, the options-page option will be autloaded. ); /** * Metabox field objects * * @var array * @since 2.0.3 */ protected $fields = array(); /** * An array of hidden fields to output at the end of the form * * @var array * @since 2.0.0 */ protected $hidden_fields = array(); /** * Array of key => value data for saving. Likely $_POST data. * * @var string * @since 2.0.0 */ protected $generated_nonce = ''; /** * Whether there are fields to be shown in columns. Set in CMB2::add_field(). * * @var bool * @since 2.2.2 */ protected $has_columns = false; /** * If taxonomy field is requesting to remove_default, we store the taxonomy here. * * @var array * @since 2.2.3 */ protected $tax_metaboxes_to_remove = array(); /** * Get started * * @since 0.4.0 * @param array $config Metabox config array. * @param integer $object_id Optional object id. */ public function __construct( $config, $object_id = 0 ) { if ( empty( $config['id'] ) ) { wp_die( esc_html__( 'Metabox configuration is required to have an ID parameter.', 'cmb2' ) ); } $this->cmb_id = $config['id']; $this->meta_box = wp_parse_args( $config, $this->mb_defaults ); $this->meta_box['fields'] = array(); // Ensures object_types is an array. $this->set_prop( 'object_types', $this->box_types() ); $this->object_id( $object_id ); if ( $this->is_options_page_mb() ) { // Check initial priority. if ( empty( $config['priority'] ) ) { // If not explicitly defined, Reset the priority to 10 // Fixes https://github.com/CMB2/CMB2/issues/1410. $this->meta_box['priority'] = 10; } $this->init_options_mb(); } $this->mb_object_type(); if ( ! empty( $config['fields'] ) && is_array( $config['fields'] ) ) { $this->add_fields( $config['fields'] ); } CMB2_Boxes::add( $this ); /** * Hook during initiation of CMB2 object * * The dynamic portion of the hook name, $this->cmb_id, is this meta_box id. * * @param array $cmb This CMB2 object */ do_action( "cmb2_init_{$this->cmb_id}", $this ); // Hook in the hookup... how meta. add_action( "cmb2_init_hookup_{$this->cmb_id}", array( 'CMB2_Hookup', 'maybe_init_and_hookup' ) ); // Hook in the rest api functionality. add_action( "cmb2_init_hookup_{$this->cmb_id}", array( 'CMB2_REST', 'maybe_init_and_hookup' ) ); } /** * Loops through and displays fields * * @since 1.0.0 * @param int $object_id Object ID. * @param string $object_type Type of object being saved. (e.g., post, user, or comment). * * @return CMB2 */ public function show_form( $object_id = 0, $object_type = '' ) { $this->render_form_open( $object_id, $object_type ); foreach ( $this->prop( 'fields' ) as $field_args ) { $this->render_field( $field_args ); } return $this->render_form_close( $object_id, $object_type ); } /** * Outputs the opening form markup and runs corresponding hooks: * 'cmb2_before_form' and "cmb2_before_{$object_type}_form_{$this->cmb_id}" * * @since 2.2.0 * @param integer $object_id Object ID. * @param string $object_type Object type. * * @return CMB2 */ public function render_form_open( $object_id = 0, $object_type = '' ) { $object_type = $this->object_type( $object_type ); $object_id = $this->object_id( $object_id ); echo "\n<!-- Begin CMB2 Fields -->\n"; $this->nonce_field(); /** * Hook before form table begins * * @param array $cmb_id The current box ID. * @param int $object_id The ID of the current object. * @param string $object_type The type of object you are working with. * Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * @param array $cmb This CMB2 object. */ do_action( 'cmb2_before_form', $this->cmb_id, $object_id, $object_type, $this ); /** * Hook before form table begins * * The first dynamic portion of the hook name, $object_type, is the type of object * you are working with. Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * * The second dynamic portion of the hook name, $this->cmb_id, is the meta_box id. * * @param array $cmb_id The current box ID * @param int $object_id The ID of the current object * @param array $cmb This CMB2 object */ do_action( "cmb2_before_{$object_type}_form_{$this->cmb_id}", $object_id, $this ); echo '<div class="', esc_attr( $this->box_classes() ), '"><div id="cmb2-metabox-', sanitize_html_class( $this->cmb_id ), '" class="cmb2-metabox cmb-field-list">'; return $this; } /** * Defines the classes for the CMB2 form/wrap. * * @since 2.0.0 * @return string Space concatenated list of classes */ public function box_classes() { $classes = array( 'cmb2-wrap', 'form-table' ); // Use the callback to fetch classes. if ( $added_classes = $this->get_param_callback_result( 'classes_cb' ) ) { $added_classes = is_array( $added_classes ) ? $added_classes : array( $added_classes ); $classes = array_merge( $classes, $added_classes ); } if ( $added_classes = $this->prop( 'classes' ) ) { $added_classes = is_array( $added_classes ) ? $added_classes : array( $added_classes ); $classes = array_merge( $classes, $added_classes ); } /** * Add our context classes for non-standard metaboxes. * * @since 2.2.4 */ if ( $this->is_alternate_context_box() ) { $context = array(); // Include custom class if requesting no title. if ( ! $this->prop( 'title' ) && ! $this->prop( 'remove_box_wrap' ) ) { $context[] = 'cmb2-context-wrap-no-title'; } // Include a generic context wrapper. $context[] = 'cmb2-context-wrap'; // Include a context-type based context wrapper. $context[] = 'cmb2-context-wrap-' . $this->prop( 'context' ); // Include an ID based context wrapper as well. $context[] = 'cmb2-context-wrap-' . $this->prop( 'id' ); // And merge all the classes back into the array. $classes = array_merge( $classes, $context ); } /** * Globally filter box wrap classes * * @since 2.2.2 * * @param string $classes Array of classes for the cmb2-wrap. * @param CMB2 $cmb This CMB2 object. */ $classes = apply_filters( 'cmb2_wrap_classes', $classes, $this ); $split = array(); foreach ( array_filter( $classes ) as $class ) { foreach ( explode( ' ', $class ) as $_class ) { // Clean up & sanitize. $split[] = sanitize_html_class( strip_tags( $_class ) ); } } $classes = $split; // Remove any duplicates. $classes = array_unique( $classes ); // Make it a string. return implode( ' ', $classes ); } /** * Outputs the closing form markup and runs corresponding hooks: * 'cmb2_after_form' and "cmb2_after_{$object_type}_form_{$this->cmb_id}" * * @since 2.2.0 * @param integer $object_id Object ID. * @param string $object_type Object type. * * @return CMB2 */ public function render_form_close( $object_id = 0, $object_type = '' ) { $object_type = $this->object_type( $object_type ); $object_id = $this->object_id( $object_id ); echo '</div></div>'; $this->render_hidden_fields(); /** * Hook after form form has been rendered * * The dynamic portion of the hook name, $this->cmb_id, is the meta_box id. * * The first dynamic portion of the hook name, $object_type, is the type of object * you are working with. Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * * @param int $object_id The ID of the current object * @param array $cmb This CMB2 object */ do_action( "cmb2_after_{$object_type}_form_{$this->cmb_id}", $object_id, $this ); /** * Hook after form form has been rendered * * @param array $cmb_id The current box ID. * @param int $object_id The ID of the current object. * @param string $object_type The type of object you are working with. * Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * @param array $cmb This CMB2 object. */ do_action( 'cmb2_after_form', $this->cmb_id, $object_id, $object_type, $this ); echo "\n<!-- End CMB2 Fields -->\n"; return $this; } /** * Renders a field based on the field type * * @since 2.2.0 * @param array $field_args A field configuration array. * @return mixed CMB2_Field object if successful. */ public function render_field( $field_args ) { $field_args['context'] = $this->prop( 'context' ); if ( 'group' === $field_args['type'] ) { if ( ! isset( $field_args['show_names'] ) ) { $field_args['show_names'] = $this->prop( 'show_names' ); } $field = $this->render_group( $field_args ); } elseif ( 'hidden' === $field_args['type'] && $this->get_field( $field_args )->should_show() ) { // Save rendering for after the metabox. $field = $this->add_hidden_field( $field_args ); } else { $field_args['show_names'] = $this->prop( 'show_names' ); // Render default fields. $field = $this->get_field( $field_args )->render_field(); } return $field; } /** * Render a group of fields. * * @param array|CMB2_Field $args Array of field arguments for a group field parent or the group parent field. * @return CMB2_Field|null Group field object. */ public function render_group( $args ) { $field_group = false; if ( $args instanceof CMB2_Field ) { $field_group = 'group' === $args->type() ? $args : false; } elseif ( isset( $args['id'], $args['fields'] ) && is_array( $args['fields'] ) ) { $field_group = $this->get_field( $args ); } if ( ! $field_group ) { return; } $field_group->render_context = 'edit'; $field_group->peform_param_callback( 'render_row_cb' ); return $field_group; } /** * The default callback to render a group of fields. * * @since 2.2.6 * * @param array $field_args Array of field arguments for the group field parent. * @param CMB2_Field $field_group The CMB2_Field group object. * * @return CMB2_Field|null Group field object. */ public function render_group_callback( $field_args, $field_group ) { // If field is requesting to be conditionally shown. if ( ! $field_group || ! $field_group->should_show() ) { return; } $field_group->index = 0; $field_group->peform_param_callback( 'before_group' ); $desc = $field_group->args( 'description' ); $label = $field_group->args( 'name' ); $group_val = (array) $field_group->value(); echo '<div class="cmb-row cmb-repeat-group-wrap ', esc_attr( $field_group->row_classes() ), '" data-fieldtype="group"><div class="cmb-td"><div data-groupid="', esc_attr( $field_group->id() ), '" id="', esc_attr( $field_group->id() ), '_repeat" ', $this->group_wrap_attributes( $field_group ), '>'; if ( $desc || $label ) { $class = $desc ? ' cmb-group-description' : ''; echo '<div class="cmb-row', $class, '"><div class="cmb-th">'; if ( $label ) { echo '<h2 class="cmb-group-name">', $label, '</h2>'; } if ( $desc ) { echo '<p class="cmb2-metabox-description">', $desc, '</p>'; } echo '</div></div>'; } if ( ! empty( $group_val ) ) { foreach ( $group_val as $group_key => $field_id ) { $this->render_group_row( $field_group ); $field_group->index++; } } else { $this->render_group_row( $field_group ); } if ( $field_group->args( 'repeatable' ) ) { echo '<div class="cmb-row"><div class="cmb-td"><p class="cmb-add-row"><button type="button" data-selector="', esc_attr( $field_group->id() ), '_repeat" data-grouptitle="', esc_attr( $field_group->options( 'group_title' ) ), '" class="cmb-add-group-row button-secondary">', $field_group->options( 'add_button' ), '</button></p></div></div>'; } echo '</div></div></div>'; $field_group->peform_param_callback( 'after_group' ); return $field_group; } /** * Get the group wrap attributes, which are passed through a filter. * * @since 2.2.3 * @param CMB2_Field $field_group The group CMB2_Field object. * @return string The attributes string. */ public function group_wrap_attributes( $field_group ) { $classes = 'cmb-nested cmb-field-list cmb-repeatable-group'; $classes .= $field_group->options( 'sortable' ) ? ' sortable' : ' non-sortable'; $classes .= $field_group->args( 'repeatable' ) ? ' repeatable' : ' non-repeatable'; $group_wrap_attributes = array( 'class' => $classes, 'style' => 'width:100%;', ); /** * Allow for adding additional HTML attributes to a group wrapper. * * The attributes will be an array of key => value pairs for each attribute. * * @since 2.2.2 * * @param string $group_wrap_attributes Current attributes array. * @param CMB2_Field $field_group The group CMB2_Field object. */ $group_wrap_attributes = apply_filters( 'cmb2_group_wrap_attributes', $group_wrap_attributes, $field_group ); $atts = array(); foreach ( $group_wrap_attributes as $att => $att_value ) { if ( ! CMB2_Utils::is_data_attribute( $att ) ) { $att_value = htmlspecialchars( $att_value, ENT_COMPAT ); } $atts[ sanitize_html_class( $att ) ] = sanitize_text_field( $att_value ); } return CMB2_Utils::concat_attrs( $atts ); } /** * Render a repeatable group row * * @since 1.0.2 * @param CMB2_Field $field_group CMB2_Field group field object. * * @return CMB2 */ public function render_group_row( $field_group ) { $field_group->peform_param_callback( 'before_group_row' ); $closed_class = $field_group->options( 'closed' ) ? ' closed' : ''; $confirm_deletion = $field_group->options( 'remove_confirm' ); $confirm_deletion = ! empty( $confirm_deletion ) ? $confirm_deletion : ''; echo ' <div id="cmb-group-', $field_group->id(), '-', $field_group->index, '" class="postbox cmb-row cmb-repeatable-grouping', $closed_class, '" data-iterator="', $field_group->index, '">'; if ( $field_group->args( 'repeatable' ) ) { echo '<button type="button" data-selector="', $field_group->id(), '_repeat" data-confirm="', esc_attr( $confirm_deletion ), '" class="dashicons-before dashicons-no-alt cmb-remove-group-row" title="', esc_attr( $field_group->options( 'remove_button' ) ), '"></button>'; } echo ' <div class="cmbhandle" title="' , esc_attr__( 'Click to toggle', 'cmb2' ), '"><br></div> <h3 class="cmb-group-title cmbhandle-title"><span>', $field_group->replace_hash( $field_group->options( 'group_title' ) ), '</span></h3> <div class="inside cmb-td cmb-nested cmb-field-list">'; // Loop and render repeatable group fields. foreach ( array_values( $field_group->args( 'fields' ) ) as $field_args ) { if ( 'hidden' === $field_args['type'] ) { // Save rendering for after the metabox. $this->add_hidden_field( $field_args, $field_group ); } else { $field_args['show_names'] = $field_group->args( 'show_names' ); $field_args['context'] = $field_group->args( 'context' ); $this->get_field( $field_args, $field_group )->render_field(); } } if ( $field_group->args( 'repeatable' ) ) { echo ' <div class="cmb-row cmb-remove-field-row"> <div class="cmb-remove-row"> <button type="button" data-selector="', $field_group->id(), '_repeat" data-confirm="', esc_attr( $confirm_deletion ), '" class="cmb-remove-group-row cmb-remove-group-row-button alignright button-secondary">', $field_group->options( 'remove_button' ), '</button> </div> </div> '; } echo ' </div> </div> '; $field_group->peform_param_callback( 'after_group_row' ); return $this; } /** * Add a hidden field to the list of hidden fields to be rendered later. * * @since 2.0.0 * * @param array $field_args Array of field arguments to be passed to CMB2_Field. * @param CMB2_Field|null $field_group CMB2_Field group field object. * @return CMB2_Field */ public function add_hidden_field( $field_args, $field_group = null ) { if ( isset( $field_args['field_args'] ) ) { // For back-compatibility. $field = new CMB2_Field( $field_args ); } else { $field = $this->get_new_field( $field_args, $field_group ); } $types = new CMB2_Types( $field ); if ( $field_group ) { $types->iterator = $field_group->index; } $this->hidden_fields[] = $types; return $field; } /** * Loop through and output hidden fields * * @since 2.0.0 * * @return CMB2 */ public function render_hidden_fields() { if ( ! empty( $this->hidden_fields ) ) { foreach ( $this->hidden_fields as $hidden ) { $hidden->render(); } } return $this; } /** * Returns array of sanitized field values (without saving them) * * @since 2.0.3 * @param array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data). * @return mixed */ public function get_sanitized_values( array $data_to_sanitize ) { $this->data_to_save = $data_to_sanitize; $stored_id = $this->object_id(); // We do this So CMB will sanitize our data for us, but not save it. $this->object_id( '_' ); // Ensure temp. data store is empty. cmb2_options( 0 )->set(); // We want to get any taxonomy values back. add_filter( "cmb2_return_taxonomy_values_{$this->cmb_id}", '__return_true' ); // Process/save fields. $this->process_fields(); // Put things back the way they were. remove_filter( "cmb2_return_taxonomy_values_{$this->cmb_id}", '__return_true' ); // Get data from temp. data store. $sanitized_values = cmb2_options( 0 )->get_options(); // Empty out temp. data store again. cmb2_options( 0 )->set(); // Reset the object id. $this->object_id( $stored_id ); return $sanitized_values; } /** * Loops through and saves field data * * @since 1.0.0 * @param int $object_id Object ID. * @param string $object_type Type of object being saved. (e.g., post, user, or comment). * @param array $data_to_save Array of key => value data for saving. Likely $_POST data. * * @return CMB2 */ public function save_fields( $object_id = 0, $object_type = '', $data_to_save = array() ) { // Fall-back to $_POST data. $this->data_to_save = ! empty( $data_to_save ) ? $data_to_save : $_POST; $object_id = $this->object_id( $object_id ); $object_type = $this->object_type( $object_type ); $this->process_fields(); // If options page, save the updated options. if ( 'options-page' === $object_type ) { cmb2_options( $object_id )->set(); } return $this->after_save(); } /** * Process and save form fields * * @since 2.0.0 * * @return CMB2 */ public function process_fields() { $this->pre_process(); // Remove the show_on properties so saving works. $this->prop( 'show_on', array() ); // save field ids of those that are updated. $this->updated = array(); foreach ( $this->prop( 'fields' ) as $field_args ) { $this->process_field( $field_args ); } return $this; } /** * Process and save a field * * @since 2.0.0 * @param array $field_args Array of field arguments. * * @return CMB2 */ public function process_field( $field_args ) { switch ( $field_args['type'] ) { case 'group': if ( $this->save_group( $field_args ) ) { $this->updated[] = $field_args['id']; } break; case 'title': // Don't process title fields. break; default: $field = $this->get_new_field( $field_args ); if ( $field->save_field_from_data( $this->data_to_save ) ) { $this->updated[] = $field->id(); } break; } return $this; } /** * Fires the "cmb2_{$object_type}_process_fields_{$cmb_id}" action hook. * * @since 2.2.2 * * @return CMB2 */ public function pre_process() { $object_type = $this->object_type(); /** * Fires before fields have been processed/saved. * * The dynamic portion of the hook name, $object_type, refers to the * metabox/form's object type * Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * * The dynamic portion of the hook name, $this->cmb_id, is the meta_box id. * * @param array $cmb This CMB2 object * @param int $object_id The ID of the current object */ do_action( "cmb2_{$object_type}_process_fields_{$this->cmb_id}", $this, $this->object_id() ); return $this; } /** * Fires the "cmb2_save_{$object_type}_fields" and * "cmb2_save_{$object_type}_fields_{$cmb_id}" action hooks. * * @since 2.x.x * * @return CMB2 */ public function after_save() { $object_type = $this->object_type(); $object_id = $this->object_id(); /** * Fires after all fields have been saved. * * The dynamic portion of the hook name, $object_type, refers to the metabox/form's object type * Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * * @param int $object_id The ID of the current object * @param array $cmb_id The current box ID * @param string $updated Array of field ids that were updated. * Will only include field ids that had values change. * @param array $cmb This CMB2 object */ do_action( "cmb2_save_{$object_type}_fields", $object_id, $this->cmb_id, $this->updated, $this ); /** * Fires after all fields have been saved. * * The dynamic portion of the hook name, $this->cmb_id, is the meta_box id. * * The dynamic portion of the hook name, $object_type, refers to the metabox/form's object type * Usually `post` (this applies to all post-types). * Could also be `comment`, `user` or `options-page`. * * @param int $object_id The ID of the current object * @param string $updated Array of field ids that were updated. * Will only include field ids that had values change. * @param array $cmb This CMB2 object */ do_action( "cmb2_save_{$object_type}_fields_{$this->cmb_id}", $object_id, $this->updated, $this ); return $this; } /** * Save a repeatable group * * @since 1.x.x * @param array $args Field arguments array. * @return mixed Return of CMB2_Field::update_data(). */ public function save_group( $args ) { if ( ! isset( $args['id'], $args['fields'] ) || ! is_array( $args['fields'] ) ) { return; } return $this->save_group_field( $this->get_new_field( $args ) ); } /** * Save a repeatable group * * @since 1.x.x * @param CMB2_Field $field_group CMB2_Field group field object. * @return mixed Return of CMB2_Field::update_data(). */ public function save_group_field( $field_group ) { $base_id = $field_group->id(); if ( ! isset( $this->data_to_save[ $base_id ] ) ) { return; } $old = $field_group->get_data(); // Check if group field has sanitization_cb. $group_vals = $field_group->sanitization_cb( $this->data_to_save[ $base_id ] ); $saved = array(); $field_group->index = 0; $field_group->data_to_save = $this->data_to_save; foreach ( array_values( $field_group->fields() ) as $field_args ) { if ( 'title' === $field_args['type'] ) { // Don't process title fields. continue; } $field = $this->get_new_field( $field_args, $field_group ); $sub_id = $field->id( true ); if ( empty( $saved[ $field_group->index ] ) ) { $saved[ $field_group->index ] = array(); } foreach ( (array) $group_vals as $field_group->index => $post_vals ) { // Get value. $new_val = isset( $group_vals[ $field_group->index ][ $sub_id ] ) ? $group_vals[ $field_group->index ][ $sub_id ] : false; // Sanitize. $new_val = $field->sanitization_cb( $new_val ); if ( is_array( $new_val ) && $field->args( 'has_supporting_data' ) ) { if ( $field->args( 'repeatable' ) ) { $_new_val = array(); foreach ( $new_val as $group_index => $grouped_data ) { // Add the supporting data to the $saved array stack. $saved[ $field_group->index ][ $grouped_data['supporting_field_id'] ][] = $grouped_data['supporting_field_value']; // Reset var to the actual value. $_new_val[ $group_index ] = $grouped_data['value']; } $new_val = $_new_val; } else { // Add the supporting data to the $saved array stack. $saved[ $field_group->index ][ $new_val['supporting_field_id'] ] = $new_val['supporting_field_value']; // Reset var to the actual value. $new_val = $new_val['value']; } } // Get old value. $old_val = is_array( $old ) && isset( $old[ $field_group->index ][ $sub_id ] ) ? $old[ $field_group->index ][ $sub_id ] : false; $is_updated = ( ! CMB2_Utils::isempty( $new_val ) && $new_val !== $old_val ); $is_removed = ( CMB2_Utils::isempty( $new_val ) && ! CMB2_Utils::isempty( $old_val ) ); // Compare values and add to `$updated` array. if ( $is_updated || $is_removed ) { $this->updated[] = $base_id . '::' . $field_group->index . '::' . $sub_id; } // Add to `$saved` array. $saved[ $field_group->index ][ $sub_id ] = $new_val; }// End foreach. $saved[ $field_group->index ] = CMB2_Utils::filter_empty( $saved[ $field_group->index ] ); }// End foreach. $saved = CMB2_Utils::filter_empty( $saved ); return $field_group->update_data( $saved, true ); } /** * Get object id from global space if no id is provided * * @since 1.0.0 * @param integer|string $object_id Object ID. * @return integer|string $object_id Object ID. */ public function object_id( $object_id = 0 ) { global $pagenow; if ( $object_id ) { $this->object_id = $object_id; return $this->object_id; } if ( $this->object_id ) { return $this->object_id; } // Try to get our object ID from the global space. switch ( $this->object_type() ) { case 'user': $object_id = isset( $_REQUEST['user_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['user_id'] ) ) : $object_id; $object_id = ! $object_id && 'user-new.php' !== $pagenow && isset( $GLOBALS['user_ID'] ) ? $GLOBALS['user_ID'] : $object_id; break; case 'comment': $object_id = isset( $_REQUEST['c'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['c'] ) ) : $object_id; $object_id = ! $object_id && isset( $GLOBALS['comments']->comment_ID ) ? $GLOBALS['comments']->comment_ID : $object_id; break; case 'term': $object_id = isset( $_REQUEST['tag_ID'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['tag_ID'] ) ) : $object_id; break; case 'options-page': $key = $this->doing_options_page(); if ( ! empty( $key ) ) { $object_id = $key; } break; default: $object_id = isset( $GLOBALS['post']->ID ) ? $GLOBALS['post']->ID : $object_id; $object_id = isset( $_REQUEST['post'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['post'] ) ) : $object_id; break; } /** * Filter the object id. * * @since 2.11.0 * * @param integer|string $object_id Object ID. * @param CMB2 $cmb This CMB2 object. */ $object_id = apply_filters( 'cmb2_set_object_id', $object_id, $this ); // reset to id or 0. $this->object_id = ! empty( $object_id ) ? $object_id : 0; return $this->object_id; } /** * Sets the $object_type based on metabox settings * * @since 1.0.0 * @return string Object type. */ public function mb_object_type() { if ( null !== $this->mb_object_type ) { return $this->mb_object_type; } $found_type = ''; if ( $this->is_options_page_mb() ) { $found_type = 'options-page'; } else { $registered_types = $this->box_types(); // if it's an array of one, extract it. if ( 1 === count( $registered_types ) ) { $last = end( $registered_types ); if ( is_string( $last ) ) { $found_type = $last; } } else { $current_object_type = $this->current_object_type(); if ( in_array( $current_object_type, $registered_types, true ) ) { $found_type = $current_object_type; } } } // Get our object type. $mb_object_type = $this->is_supported_core_object_type( $found_type ) ? $found_type : 'post'; /** * Filter the metabox object type. * * @since 2.11.0 * * @param string $mb_object_type The metabox object type. * @param string $found_type The found object type. * @param CMB2 $cmb This CMB2 object. */ $this->mb_object_type = apply_filters( 'cmb2_set_box_object_type', $mb_object_type, $found_type, $this ); return $this->mb_object_type; } /** * Gets the box 'object_types' array based on box settings. * * @since 2.2.3 * @param array $fallback Fallback value. * * @return array Object types. */ public function box_types( $fallback = array() ) { return CMB2_Utils::ensure_array( $this->prop( 'object_types' ), $fallback ); } /** * Check if given object_type(s) matches any of the registered object types or * taxonomies for this box. * * @since 2.7.0 * @param string|array $object_types The object type(s) to check. * @param array $fallback Fallback object_types value. * * @return bool Whether given object type(s) are registered to this box. */ public function is_box_type( $object_types = array(), $fallback = array() ) { $object_types = (array) $object_types; $box_types = $this->box_types( $fallback ); if ( in_array( 'term', $box_types, true ) ) { $taxonomies = CMB2_Utils::ensure_array( $this->prop( 'taxonomies' ) ); $box_types = array_merge( $box_types, $taxonomies ); } $found = array_intersect( $object_types, $box_types ); return ! empty( $found ); } /** * Initates the object types and option key for an options page metabox. * * @since 2.2.5 * * @return void */ public function init_options_mb() { $keys = $this->options_page_keys(); $types = $this->box_types(); if ( empty( $keys ) ) { $keys = ''; $types = $this->deinit_options_mb( $types ); } else { // Make sure 'options-page' is one of the object types. $types[] = 'options-page'; } // Set/Reset the option_key property. $this->set_prop( 'option_key', $keys ); // Reset the object types. $this->set_prop( 'object_types', array_unique( $types ) ); } /** * If object-page initiation failed, remove traces options page setup. * * @since 2.2.5 * * @param array $types Array of types. * @return array */ protected function deinit_options_mb( $types ) { if ( isset( $this->meta_box['show_on']['key'] ) && 'options-page' === $this->meta_box['show_on']['key'] ) { unset( $this->meta_box['show_on']['key'] ); } if ( array_key_exists( 'options-page', $this->meta_box['show_on'] ) ) { unset( $this->meta_box['show_on']['options-page'] ); } $index = array_search( 'options-page', $types ); if ( false !== $index ) { unset( $types[ $index ] ); } return $types; } /** * Determines if metabox is for an options page * * @since 1.0.1 * @return boolean True/False. */ public function is_options_page_mb() { return ( // 'show_on' values checked for back-compatibility. $this->is_old_school_options_page_mb() || in_array( 'options-page', $this->box_types() ) ); } /** * Determines if metabox uses old-schoold options page config. * * @since 2.2.5 * @return boolean True/False. */ public function is_old_school_options_page_mb() { return ( // 'show_on' values checked for back-compatibility. isset( $this->meta_box['show_on']['key'] ) && 'options-page' === $this->meta_box['show_on']['key'] || array_key_exists( 'options-page', $this->meta_box['show_on'] ) ); } /** * Determine if we are on an options page (or saving the options page). * * @since 2.2.5 * * @return bool */ public function doing_options_page() { $found_key = false; $keys = $this->options_page_keys(); if ( empty( $keys ) ) { return $found_key; } if ( ! empty( $_GET['page'] ) && in_array( $_GET['page'], $keys ) ) { $found_key = $_GET['page']; } if ( ! empty( $_POST['action'] ) && in_array( $_POST['action'], $keys ) ) { $found_key = $_POST['action']; } return $found_key ? $found_key : false; } /** * Get the options page key. * * @since 2.2.5 * @return string|array */ public function options_page_keys() { $key = ''; if ( ! $this->is_options_page_mb() ) { return $key; } $values = null; if ( ! empty( $this->meta_box['show_on']['value'] ) ) { $values = $this->meta_box['show_on']['value']; } elseif ( ! empty( $this->meta_box['show_on']['options-page'] ) ) { $values = $this->meta_box['show_on']['options-page']; } elseif ( $this->prop( 'option_key' ) ) { $values = $this->prop( 'option_key' ); } if ( $values ) { $key = $values; } if ( ! is_array( $key ) ) { $key = array( $key ); } return $key; } /** * Returns the object type * * @since 1.0.0 * @param string $object_type Type of object being saved. (e.g., post, user, or comment). Optional. * @return string Object type. */ public function object_type( $object_type = '' ) { if ( $object_type ) { $this->object_type = $object_type; return $this->object_type; } if ( $this->object_type ) { return $this->object_type; } $this->object_type = $this->current_object_type(); return $this->object_type; } /** * Get the object type for the current page, based on the $pagenow global. * * @since 2.2.2 * @return string Page object type name. */ public function current_object_type() { global $pagenow; $type = 'post'; if ( in_array( $pagenow, array( 'user-edit.php', 'profile.php', 'user-new.php' ), true ) ) { $type = 'user'; } if ( in_array( $pagenow, array( 'edit-comments.php', 'comment.php' ), true ) ) { $type = 'comment'; } if ( in_array( $pagenow, array( 'edit-tags.php', 'term.php' ), true ) ) { $type = 'term'; } if ( defined( 'DOING_AJAX' ) && isset( $_POST['action'] ) && 'add-tag' === $_POST['action'] ) { $type = 'term'; } if ( in_array( $pagenow, array( 'admin.php', 'admin-post.php' ), true ) && $this->doing_options_page() ) { $type = 'options-page'; } return $type; } /** * Set metabox property. * * @since 2.2.2 * @param string $property Metabox config property to retrieve. * @param mixed $value Value to set if no value found. * @return mixed Metabox config property value or false. */ public function set_prop( $property, $value ) { $this->meta_box[ $property ] = $value; return $this->prop( $property ); } /** * Get metabox property and optionally set a fallback * * @since 2.0.0 * @param string $property Metabox config property to retrieve. * @param mixed $fallback Fallback value to set if no value found. * @return mixed Metabox config property value or false. */ public function prop( $property, $fallback = null ) { if ( array_key_exists( $property, $this->meta_box ) ) { return $this->meta_box[ $property ]; } elseif ( $fallback ) { return $this->meta_box[ $property ] = $fallback; } } /** * Get a field object * * @since 2.0.3 * @param string|array|CMB2_Field $field Metabox field id or field config array or CMB2_Field object. * @param CMB2_Field|null $field_group (optional) CMB2_Field object (group parent). * @param bool $reset_cached (optional) Reset the internal cache for this field object. * Use sparingly. * * @return CMB2_Field|false CMB2_Field object (or false). */ public function get_field( $field, $field_group = null, $reset_cached = false ) { if ( $field instanceof CMB2_Field ) { return $field; } $field_id = is_string( $field ) ? $field : $field['id']; $parent_field_id = ! empty( $field_group ) ? $field_group->id() : ''; $ids = $this->get_field_ids( $field_id, $parent_field_id ); if ( ! $ids ) { return false; } list( $field_id, $sub_field_id ) = $ids; $index = $field_id . ( $sub_field_id ? '|' . $sub_field_id : '' ) . ( $field_group ? '|' . $field_group->index : '' ); if ( array_key_exists( $index, $this->fields ) && ! $reset_cached ) { return $this->fields[ $index ]; } $this->fields[ $index ] = new CMB2_Field( $this->get_field_args( $field_id, $field, $sub_field_id, $field_group ) ); return $this->fields[ $index ]; } /** * Handles determining which type of arguments to pass to CMB2_Field * * @since 2.0.7 * @param mixed $field_id Field (or group field) ID. * @param mixed $field_args Array of field arguments. * @param mixed $sub_field_id Sub field ID (if field_group exists). * @param CMB2_Field|null $field_group If a sub-field, will be the parent group CMB2_Field object. * @return array Array of CMB2_Field arguments. */ public function get_field_args( $field_id, $field_args, $sub_field_id, $field_group ) { // Check if group is passed and if fields were added in the old-school fields array. if ( $field_group && ( $sub_field_id || 0 === $sub_field_id ) ) { // Update the fields array w/ any modified properties inherited from the group field. $this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ] = $field_args; return $this->get_default_args( $field_args, $field_group ); } if ( is_array( $field_args ) ) { $this->meta_box['fields'][ $field_id ] = array_merge( $field_args, $this->meta_box['fields'][ $field_id ] ); } return $this->get_default_args( $this->meta_box['fields'][ $field_id ] ); } /** * Get default field arguments specific to this CMB2 object. * * @since 2.2.0 * @param array $field_args Metabox field config array. * @param CMB2_Field $field_group (optional) CMB2_Field object (group parent). * @return array Array of field arguments. */ protected function get_default_args( $field_args, $field_group = null ) { if ( $field_group ) { $args = array( 'field_args' => $field_args, 'group_field' => $field_group, ); } else { $args = array( 'field_args' => $field_args, 'object_type' => $this->object_type(), 'object_id' => $this->object_id(), 'cmb_id' => $this->cmb_id, ); } return $args; } /** * When fields are added in the old-school way, intitate them as they should be * * @since 2.1.0 * @param array $fields Array of fields to add. * @param mixed $parent_field_id Parent field id or null. * * @return CMB2 */ protected function add_fields( $fields, $parent_field_id = null ) { foreach ( $fields as $field ) { $sub_fields = false; if ( array_key_exists( 'fields', $field ) ) { $sub_fields = $field['fields']; unset( $field['fields'] ); } $field_id = $parent_field_id ? $this->add_group_field( $parent_field_id, $field ) : $this->add_field( $field ); if ( $sub_fields ) { $this->add_fields( $sub_fields, $field_id ); } } return $this; } /** * Add a field to the metabox * * @since 2.0.0 * @param array $field Metabox field config array. * @param int $position (optional) Position of metabox. 1 for first, etc. * @return string|false Field id or false. */ public function add_field( array $field, $position = 0 ) { if ( ! array_key_exists( 'id', $field ) ) { return false; } $this->_add_field_to_array( $field, $this->meta_box['fields'], $position ); return $field['id']; } /** * Add a field to a group * * @since 2.0.0 * @param string $parent_field_id The field id of the group field to add the field. * @param array $field Metabox field config array. * @param int $position (optional) Position of metabox. 1 for first, etc. * @return mixed Array of parent/field ids or false. */ public function add_group_field( $parent_field_id, array $field, $position = 0 ) { if ( ! array_key_exists( $parent_field_id, $this->meta_box['fields'] ) ) { return false; } $parent_field = $this->meta_box['fields'][ $parent_field_id ]; if ( 'group' !== $parent_field['type'] ) { return false; } if ( ! isset( $parent_field['fields'] ) ) { $this->meta_box['fields'][ $parent_field_id ]['fields'] = array(); } $this->_add_field_to_array( $field, $this->meta_box['fields'][ $parent_field_id ]['fields'], $position ); return array( $parent_field_id, $field['id'] ); } /** * Perform some field-type-specific initiation actions. * * @since 2.7.0 * @param array $field Metabox field config array. * @return void */ protected function field_actions( $field ) { $field = CMB2_Hookup_Field::init( $field, $this ); if ( isset( $field['column'] ) && false !== $field['column'] ) { $field = $this->define_field_column( $field ); } if ( isset( $field['taxonomy'] ) && ! empty( $field['remove_default'] ) ) { $this->tax_metaboxes_to_remove[ $field['taxonomy'] ] = $field['taxonomy']; } return $field; } /** * Defines a field's column if requesting to be show in admin columns. * * @since 2.2.3 * @param array $field Metabox field config array. * @return array Modified metabox field config array. */ protected function define_field_column( array $field ) { $this->has_columns = true; $column = is_array( $field['column'] ) ? $field['column'] : array(); $field['column'] = wp_parse_args( $column, array( 'name' => isset( $field['name'] ) ? $field['name'] : '', 'position' => false, ) ); return $field; } /** * Add a field array to a fields array in desired position * * @since 2.0.2 * @param array $field Metabox field config array. * @param array $fields Array (passed by reference) to append the field (array) to. * @param integer $position Optionally specify a position in the array to be inserted. */ protected function _add_field_to_array( $field, &$fields, $position = 0 ) { $field = $this->field_actions( $field ); if ( $position ) { CMB2_Utils::array_insert( $fields, array( $field['id'] => $field ), $position ); } else { $fields[ $field['id'] ] = $field; } } /** * Remove a field from the metabox * * @since 2.0.0 * @param string $field_id The field id of the field to remove. * @param string $parent_field_id (optional) The field id of the group field to remove field from. * @return bool True if field was removed. */ public function remove_field( $field_id, $parent_field_id = '' ) { $ids = $this->get_field_ids( $field_id, $parent_field_id ); if ( ! $ids ) { return false; } list( $field_id, $sub_field_id ) = $ids; unset( $this->fields[ implode( '', $ids ) ] ); if ( ! $sub_field_id ) { unset( $this->meta_box['fields'][ $field_id ] ); return true; } if ( isset( $this->fields[ $field_id ]->args['fields'][ $sub_field_id ] ) ) { unset( $this->fields[ $field_id ]->args['fields'][ $sub_field_id ] ); } if ( isset( $this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ] ) ) { unset( $this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ] ); } return true; } /** * Update or add a property to a field * * @since 2.0.0 * @param string $field_id Field id. * @param string $property Field property to set/update. * @param mixed $value Value to set the field property. * @param string $parent_field_id (optional) The field id of the group field to remove field from. * @return mixed Field id. Strict compare to false, as success can return a falsey value (like 0). */ public function update_field_property( $field_id, $property, $value, $parent_field_id = '' ) { $ids = $this->get_field_ids( $field_id, $parent_field_id ); if ( ! $ids ) { return false; } list( $field_id, $sub_field_id ) = $ids; if ( ! $sub_field_id ) { $this->meta_box['fields'][ $field_id ][ $property ] = $value; return $field_id; } $this->meta_box['fields'][ $field_id ]['fields'][ $sub_field_id ][ $property ] = $value; return $field_id; } /** * Check if field ids match a field and return the index/field id * * @since 2.0.2 * @param string $field_id Field id. * @param string $parent_field_id (optional) Parent field id. * @return mixed Array of field/parent ids, or false. */ public function get_field_ids( $field_id, $parent_field_id = '' ) { $sub_field_id = $parent_field_id ? $field_id : ''; $field_id = $parent_field_id ? $parent_field_id : $field_id; $fields =& $this->meta_box['fields']; if ( ! array_key_exists( $field_id, $fields ) ) { $field_id = $this->search_old_school_array( $field_id, $fields ); } if ( false === $field_id ) { return false; } if ( ! $sub_field_id ) { return array( $field_id, $sub_field_id ); } if ( 'group' !== $fields[ $field_id ]['type'] ) { return false; } if ( ! array_key_exists( $sub_field_id, $fields[ $field_id ]['fields'] ) ) { $sub_field_id = $this->search_old_school_array( $sub_field_id, $fields[ $field_id ]['fields'] ); } return false === $sub_field_id ? false : array( $field_id, $sub_field_id ); } /** * When using the old array filter, it is unlikely field array indexes will be the field id. * * @since 2.0.2 * @param string $field_id The field id. * @param array $fields Array of fields to search. * @return mixed Field index or false. */ public function search_old_school_array( $field_id, $fields ) { $ids = wp_list_pluck( $fields, 'id' ); $index = array_search( $field_id, $ids ); return false !== $index ? $index : false; } /** * Handles metabox property callbacks, and passes this $cmb object as property. * * @since 2.2.3 * @param callable $cb The callback method/function/closure. * @param mixed $additional_params Any additoinal parameters which should be passed to the callback. * @return mixed Return of the callback function. */ public function do_callback( $cb, $additional_params = null ) { return call_user_func( $cb, $this, $additional_params ); } /** * Generate a unique nonce field for each registered meta_box * * @since 2.0.0 * @return void */ public function nonce_field() { wp_nonce_field( $this->nonce(), $this->nonce(), false, true ); } /** * Generate a unique nonce for each registered meta_box * * @since 2.0.0 * @return string unique nonce string. */ public function nonce() { if ( ! $this->generated_nonce ) { $this->generated_nonce = sanitize_html_class( 'nonce_' . basename( __FILE__ ) . $this->cmb_id ); } return $this->generated_nonce; } /** * Checks if field-saving updated any fields. * * @since 2.2.5 * * @return bool */ public function was_updated() { return ! empty( $this->updated ); } /** * Whether this box is an "alternate context" box. This means the box has a 'context' property defined as: * 'form_top', 'before_permalink', 'after_title', or 'after_editor'. * * @since 2.2.4 * @return bool */ public function is_alternate_context_box() { return $this->prop( 'context' ) && in_array( $this->prop( 'context' ), array( 'form_top', 'before_permalink', 'after_title', 'after_editor' ), true ); } /** * Whether given object type is one of the core supported object types. * * @since 2.11.0 * @return bool */ public function is_supported_core_object_type( $object_type ) { return in_array( $object_type, $this->core_object_types, true ); } /** * Magic getter for our object. * * @param string $property Object property. * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __get( $property ) { switch ( $property ) { case 'updated': case 'has_columns': case 'tax_metaboxes_to_remove': case 'core_object_types': return $this->{$property}; default: return parent::__get( $property ); } } } cmb2/cmb2/includes/rest-api/CMB2_REST.php 0000644 00000055677 15151523433 0013623 0 ustar 00 <?php /** * Handles hooking CMB2 objects/fields into the WordPres REST API * which can allow fields to be read and/or updated. * * @since 2.2.3 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @property-read read_fields Array of readable field objects. * @property-read edit_fields Array of editable field objects. * @property-read rest_read Whether CMB2 object is readable via the rest api. * @property-read rest_edit Whether CMB2 object is editable via the rest api. */ class CMB2_REST extends CMB2_Hookup_Base { /** * The current CMB2 REST endpoint version * * @var string * @since 2.2.3 */ const VERSION = '1'; /** * The CMB2 REST base namespace (v should always be followed by $version) * * @var string * @since 2.2.3 */ const NAME_SPACE = 'cmb2/v1'; /** * @var CMB2 object * @since 2.2.3 */ public $cmb; /** * @var CMB2_REST[] objects * @since 2.2.3 */ protected static $boxes = array(); /** * @var array Array of cmb ids for each type. * @since 2.2.3 */ protected static $type_boxes = array( 'post' => array(), 'user' => array(), 'comment' => array(), 'term' => array(), ); /** * Array of readable field objects. * * @var CMB2_Field[] * @since 2.2.3 */ protected $read_fields = array(); /** * Array of editable field objects. * * @var CMB2_Field[] * @since 2.2.3 */ protected $edit_fields = array(); /** * Whether CMB2 object is readable via the rest api. * * @var boolean */ protected $rest_read = false; /** * Whether CMB2 object is editable via the rest api. * * @var boolean */ protected $rest_edit = false; /** * A functionalized constructor, used for the hookup action callbacks. * * @since 2.2.6 * * @param CMB2 $cmb The CMB2 object to hookup * * @return CMB2_Hookup_Base $hookup The hookup object. */ public static function maybe_init_and_hookup( CMB2 $cmb ) { if ( $cmb->prop( 'show_in_rest' ) && function_exists( 'rest_get_server' ) ) { $hookup = new self( $cmb ); return $hookup->universal_hooks(); } return false; } /** * Constructor * * @since 2.2.3 * * @param CMB2 $cmb The CMB2 object to be registered for the API. */ public function __construct( CMB2 $cmb ) { $this->cmb = $cmb; self::$boxes[ $cmb->cmb_id ] = $this; $show_value = $this->cmb->prop( 'show_in_rest' ); $this->rest_read = self::is_readable( $show_value ); $this->rest_edit = self::is_editable( $show_value ); } /** * Hooks to register on frontend and backend. * * @since 2.2.3 * * @return void */ public function universal_hooks() { // hook up the CMB rest endpoint classes $this->once( 'rest_api_init', array( __CLASS__, 'init_routes' ), 0 ); if ( function_exists( 'register_rest_field' ) ) { $this->once( 'rest_api_init', array( __CLASS__, 'register_cmb2_fields' ), 50 ); } $this->declare_read_edit_fields(); add_filter( 'is_protected_meta', array( $this, 'is_protected_meta' ), 10, 3 ); return $this; } /** * Initiate the CMB2 Boxes and Fields routes * * @since 2.2.3 * * @return void */ public static function init_routes() { $wp_rest_server = rest_get_server(); $boxes_controller = new CMB2_REST_Controller_Boxes( $wp_rest_server ); $boxes_controller->register_routes(); $fields_controller = new CMB2_REST_Controller_Fields( $wp_rest_server ); $fields_controller->register_routes(); } /** * Loop through REST boxes and call register_rest_field for each object type. * * @since 2.2.3 * * @return void */ public static function register_cmb2_fields() { $alltypes = $taxonomies = array(); foreach ( self::$boxes as $cmb_id => $rest_box ) { // Hook box specific filter callbacks. $callback = $rest_box->cmb->prop( 'register_rest_field_cb' ); if ( is_callable( $callback ) ) { call_user_func( $callback, $rest_box ); continue; } $types = array_flip( $rest_box->cmb->box_types( array( 'post' ) ) ); if ( isset( $types['user'] ) ) { unset( $types['user'] ); self::$type_boxes['user'][ $cmb_id ] = $cmb_id; } if ( isset( $types['comment'] ) ) { unset( $types['comment'] ); self::$type_boxes['comment'][ $cmb_id ] = $cmb_id; } if ( isset( $types['term'] ) ) { unset( $types['term'] ); $taxonomies = array_merge( $taxonomies, CMB2_Utils::ensure_array( $rest_box->cmb->prop( 'taxonomies' ) ) ); self::$type_boxes['term'][ $cmb_id ] = $cmb_id; } if ( ! empty( $types ) ) { $alltypes = array_merge( $alltypes, array_flip( $types ) ); self::$type_boxes['post'][ $cmb_id ] = $cmb_id; } } $alltypes = array_unique( $alltypes ); if ( ! empty( $alltypes ) ) { self::register_rest_field( $alltypes, 'post' ); } if ( ! empty( self::$type_boxes['user'] ) ) { self::register_rest_field( 'user', 'user' ); } if ( ! empty( self::$type_boxes['comment'] ) ) { self::register_rest_field( 'comment', 'comment' ); } if ( ! empty( self::$type_boxes['term'] ) ) { self::register_rest_field( $taxonomies, 'term' ); } } /** * Wrapper for register_rest_field. * * @since 2.2.3 * * @param string|array $object_types Object(s) the field is being registered * to, "post"|"term"|"comment" etc. * @param string $object_types Canonical object type for callbacks. * * @return void */ protected static function register_rest_field( $object_types, $object_type ) { register_rest_field( $object_types, 'cmb2', array( 'get_callback' => array( __CLASS__, "get_{$object_type}_rest_values" ), 'update_callback' => array( __CLASS__, "update_{$object_type}_rest_values" ), 'schema' => null, // @todo add schema ) ); } /** * Setup readable and editable fields. * * @since 2.2.3 * * @return void */ protected function declare_read_edit_fields() { foreach ( $this->cmb->prop( 'fields' ) as $field ) { $show_in_rest = isset( $field['show_in_rest'] ) ? $field['show_in_rest'] : null; if ( false === $show_in_rest ) { continue; } if ( $this->can_read( $show_in_rest ) ) { $this->read_fields[] = $field['id']; } if ( $this->can_edit( $show_in_rest ) ) { $this->edit_fields[] = $field['id']; } } } /** * Determines if a field is readable based on it's show_in_rest value * and the box's show_in_rest value. * * @since 2.2.3 * * @param bool $show_in_rest Field's show_in_rest value. Default null. * * @return bool Whether field is readable. */ protected function can_read( $show_in_rest ) { // if 'null', then use default box value. if ( null === $show_in_rest ) { return $this->rest_read; } // Else check if the value represents readable. return self::is_readable( $show_in_rest ); } /** * Determines if a field is editable based on it's show_in_rest value * and the box's show_in_rest value. * * @since 2.2.3 * * @param bool $show_in_rest Field's show_in_rest value. Default null. * * @return bool Whether field is editable. */ protected function can_edit( $show_in_rest ) { // if 'null', then use default box value. if ( null === $show_in_rest ) { return $this->rest_edit; } // Else check if the value represents editable. return self::is_editable( $show_in_rest ); } /** * Handler for getting post custom field data. * * @since 2.2.3 * * @param array $object The object data from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return mixed */ public static function get_post_rest_values( $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::get_rest_values( $object, $request, $object_type, 'post' ); } } /** * Handler for getting user custom field data. * * @since 2.2.3 * * @param array $object The object data from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return mixed */ public static function get_user_rest_values( $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::get_rest_values( $object, $request, $object_type, 'user' ); } } /** * Handler for getting comment custom field data. * * @since 2.2.3 * * @param array $object The object data from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return mixed */ public static function get_comment_rest_values( $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::get_rest_values( $object, $request, $object_type, 'comment' ); } } /** * Handler for getting term custom field data. * * @since 2.2.3 * * @param array $object The object data from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return mixed */ public static function get_term_rest_values( $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::get_rest_values( $object, $request, $object_type, 'term' ); } } /** * Handler for getting custom field data. * * @since 2.2.3 * * @param array $object The object data from the response * @param WP_REST_Request $request Current request * @param string $object_type The request object type * @param string $main_object_type The cmb main object type * * @return mixed */ protected static function get_rest_values( $object, $request, $object_type, $main_object_type = 'post' ) { if ( ! isset( $object['id'] ) ) { return; } $values = array(); if ( ! empty( self::$type_boxes[ $main_object_type ] ) ) { foreach ( self::$type_boxes[ $main_object_type ] as $cmb_id ) { $rest_box = self::$boxes[ $cmb_id ]; if ( ! $rest_box->cmb->is_box_type( $object_type ) ) { continue; } $result = self::get_box_rest_values( $rest_box, $object['id'], $main_object_type ); if ( ! empty( $result ) ) { if ( empty( $values[ $cmb_id ] ) ) { $values[ $cmb_id ] = $result; } else { $values[ $cmb_id ] = array_merge( $values[ $cmb_id ], $result ); } } } } return $values; } /** * Get box rest values. * * @since 2.7.0 * * @param CMB2_REST $rest_box The CMB2_REST object. * @param integer $object_id The object ID. * @param string $main_object_type The object type (post, user, term, etc) * * @return array Array of box rest values. */ public static function get_box_rest_values( $rest_box, $object_id = 0, $main_object_type = 'post' ) { $rest_box->cmb->object_id( $object_id ); $rest_box->cmb->object_type( $main_object_type ); $values = array(); foreach ( $rest_box->read_fields as $field_id ) { $field = $rest_box->cmb->get_field( $field_id ); $field->object_id( $object_id ); $field->object_type( $main_object_type ); $values[ $field->id( true ) ] = $field->get_rest_value(); if ( $field->args( 'has_supporting_data' ) ) { $field = $field->get_supporting_field(); $values[ $field->id( true ) ] = $field->get_rest_value(); } } return $values; } /** * Handler for updating post custom field data. * * @since 2.2.3 * * @param mixed $values The value of the field * @param object $object The object from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return bool|int */ public static function update_post_rest_values( $values, $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::update_rest_values( $values, $object, $request, $object_type, 'post' ); } } /** * Handler for updating user custom field data. * * @since 2.2.3 * * @param mixed $values The value of the field * @param object $object The object from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return bool|int */ public static function update_user_rest_values( $values, $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::update_rest_values( $values, $object, $request, $object_type, 'user' ); } } /** * Handler for updating comment custom field data. * * @since 2.2.3 * * @param mixed $values The value of the field * @param object $object The object from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return bool|int */ public static function update_comment_rest_values( $values, $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::update_rest_values( $values, $object, $request, $object_type, 'comment' ); } } /** * Handler for updating term custom field data. * * @since 2.2.3 * * @param mixed $values The value of the field * @param object $object The object from the response * @param string $field_name Name of field * @param WP_REST_Request $request Current request * @param string $object_type The request object type * * @return bool|int */ public static function update_term_rest_values( $values, $object, $field_name, $request, $object_type ) { if ( 'cmb2' === $field_name ) { return self::update_rest_values( $values, $object, $request, $object_type, 'term' ); } } /** * Handler for updating custom field data. * * @since 2.2.3 * * @param mixed $values The value of the field * @param object $object The object from the response * @param WP_REST_Request $request Current request * @param string $object_type The request object type * @param string $main_object_type The cmb main object type * * @return bool|int */ protected static function update_rest_values( $values, $object, $request, $object_type, $main_object_type = 'post' ) { if ( empty( $values ) || ! is_array( $values ) ) { return; } $object_id = self::get_object_id( $object, $main_object_type ); if ( ! $object_id ) { return; } $updated = array(); if ( ! empty( self::$type_boxes[ $main_object_type ] ) ) { foreach ( self::$type_boxes[ $main_object_type ] as $cmb_id ) { $result = self::santize_box_rest_values( $values, self::$boxes[ $cmb_id ], $object_id, $main_object_type ); if ( ! empty( $result ) ) { $updated[ $cmb_id ] = $result; } } } return $updated; } /** * Updates box rest values. * * @since 2.7.0 * * @param array $values Array of values. * @param CMB2_REST $rest_box The CMB2_REST object. * @param integer $object_id The object ID. * @param string $main_object_type The object type (post, user, term, etc) * * @return mixed|bool Array of updated statuses if successful. */ public static function santize_box_rest_values( $values, $rest_box, $object_id = 0, $main_object_type = 'post' ) { if ( ! array_key_exists( $rest_box->cmb->cmb_id, $values ) ) { return false; } $rest_box->cmb->object_id( $object_id ); $rest_box->cmb->object_type( $main_object_type ); return $rest_box->sanitize_box_values( $values ); } /** * Loop through box fields and sanitize the values. * * @since 2.2.o * * @param array $values Array of values being provided. * @return array Array of updated/sanitized values. */ public function sanitize_box_values( array $values ) { $updated = array(); $this->cmb->pre_process(); foreach ( $this->edit_fields as $field_id ) { $updated[ $field_id ] = $this->sanitize_field_value( $values, $field_id ); } $this->cmb->after_save(); return $updated; } /** * Handles returning a sanitized field value. * * @since 2.2.3 * * @param array $values Array of values being provided. * @param string $field_id The id of the field to update. * * @return mixed The results of saving/sanitizing a field value. */ protected function sanitize_field_value( array $values, $field_id ) { if ( ! array_key_exists( $field_id, $values[ $this->cmb->cmb_id ] ) ) { return; } $field = $this->cmb->get_field( $field_id ); if ( 'title' == $field->type() ) { return; } $field->object_id( $this->cmb->object_id() ); $field->object_type( $this->cmb->object_type() ); if ( 'group' == $field->type() ) { return $this->sanitize_group_value( $values, $field ); } return $field->save_field( $values[ $this->cmb->cmb_id ][ $field_id ] ); } /** * Handles returning a sanitized group field value. * * @since 2.2.3 * * @param array $values Array of values being provided. * @param CMB2_Field $field CMB2_Field object. * * @return mixed The results of saving/sanitizing the group field value. */ protected function sanitize_group_value( array $values, CMB2_Field $field ) { $fields = $field->fields(); if ( empty( $fields ) ) { return; } $this->cmb->data_to_save[ $field->_id( '', false ) ] = $values[ $this->cmb->cmb_id ][ $field->_id( '', false ) ]; return $this->cmb->save_group_field( $field ); } /** * Filter whether a meta key is protected. * * @since 2.2.3 * * @param bool $protected Whether the key is protected. Default false. * @param string $meta_key Meta key. * @param string $meta_type Meta type. */ public function is_protected_meta( $protected, $meta_key, $meta_type ) { if ( $this->field_can_edit( $meta_key ) ) { return false; } return $protected; } /** * Get the object ID for the given object/type. * * @since 2.2.3 * * @param mixed $object The object to get the ID for. * @param string $object_type The object type we are looking for. * * @return int The object ID if found. */ public static function get_object_id( $object, $object_type = 'post' ) { switch ( $object_type ) { case 'user': case 'post': if ( isset( $object->ID ) ) { return intval( $object->ID ); } case 'comment': if ( isset( $object->comment_ID ) ) { return intval( $object->comment_ID ); } case 'term': if ( is_array( $object ) && isset( $object['term_id'] ) ) { return intval( $object['term_id'] ); } elseif ( isset( $object->term_id ) ) { return intval( $object->term_id ); } } return 0; } /** * Checks if a given field can be read. * * @since 2.2.3 * * @param string|CMB2_Field $field_id Field ID or CMB2_Field object. * @param boolean $return_object Whether to return the Field object. * * @return mixed False if field can't be read or true|CMB2_Field object. */ public function field_can_read( $field_id, $return_object = false ) { return $this->field_can( 'read_fields', $field_id, $return_object ); } /** * Checks if a given field can be edited. * * @since 2.2.3 * * @param string|CMB2_Field $field_id Field ID or CMB2_Field object. * @param boolean $return_object Whether to return the Field object. * * @return mixed False if field can't be edited or true|CMB2_Field object. */ public function field_can_edit( $field_id, $return_object = false ) { return $this->field_can( 'edit_fields', $field_id, $return_object ); } /** * Checks if a given field can be read or edited. * * @since 2.2.3 * * @param string $type Whether we are checking for read or edit fields. * @param string|CMB2_Field $field_id Field ID or CMB2_Field object. * @param boolean $return_object Whether to return the Field object. * * @return mixed False if field can't be read or edited or true|CMB2_Field object. */ protected function field_can( $type, $field_id, $return_object = false ) { if ( ! in_array( $field_id instanceof CMB2_Field ? $field_id->id() : $field_id, $this->{$type}, true ) ) { return false; } return $return_object ? $this->cmb->get_field( $field_id ) : true; } /** * Get a CMB2_REST instance object from the registry by a CMB2 id. * * @since 2.2.3 * * @param string $cmb_id CMB2 config id * * @return CMB2_REST|false The CMB2_REST object or false. */ public static function get_rest_box( $cmb_id ) { return isset( self::$boxes[ $cmb_id ] ) ? self::$boxes[ $cmb_id ] : false; } /** * Remove a CMB2_REST instance object from the registry. * * @since 2.2.3 * * @param string $cmb_id A CMB2 instance id. */ public static function remove( $cmb_id ) { if ( array_key_exists( $cmb_id, self::$boxes ) ) { unset( self::$boxes[ $cmb_id ] ); } } /** * Retrieve all CMB2_REST instances from the registry. * * @since 2.2.3 * @return CMB2[] Array of all registered CMB2_REST instances. */ public static function get_all() { return self::$boxes; } /** * Checks if given value is readable. * * Value is considered readable if it is not empty and if it does not match the editable blacklist. * * @since 2.2.3 * * @param mixed $value Value to check. * * @return boolean Whether value is considered readable. */ public static function is_readable( $value ) { return ! empty( $value ) && ! in_array( $value, array( WP_REST_Server::CREATABLE, WP_REST_Server::EDITABLE, WP_REST_Server::DELETABLE, ), true ); } /** * Checks if given value is editable. * * Value is considered editable if matches the editable whitelist. * * @since 2.2.3 * * @param mixed $value Value to check. * * @return boolean Whether value is considered editable. */ public static function is_editable( $value ) { return in_array( $value, array( WP_REST_Server::EDITABLE, WP_REST_Server::ALLMETHODS, ), true ); } /** * Magic getter for our object. * * @param string $field * @throws Exception Throws an exception if the field is invalid. * * @return mixed */ public function __get( $field ) { switch ( $field ) { case 'read_fields': case 'edit_fields': case 'rest_read': case 'rest_edit': return $this->{$field}; default: throw new Exception( 'Invalid ' . __CLASS__ . ' property: ' . $field ); } } } cmb2/cmb2/includes/rest-api/CMB2_REST_Controller_Fields.php 0000644 00000037706 15151523433 0017305 0 ustar 00 <?php /** * CMB2 objects/fields endpoint for WordPres REST API. * Allows access to fields registered to a specific box. * * @todo Add better documentation. * @todo Research proper schema. * * @since 2.2.3 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_REST_Controller_Fields extends CMB2_REST_Controller_Boxes { /** * Register the routes for the objects of the controller. * * @since 2.2.3 */ public function register_routes() { $args = array( '_embed' => array( 'description' => __( 'Includes the box object which the fields are registered to in the response.', 'cmb2' ), ), '_rendered' => array( 'description' => __( 'When the \'_rendered\' argument is passed, the renderable field attributes will be returned fully rendered. By default, the names of the callback handers for the renderable attributes will be returned.', 'cmb2' ), ), 'object_id' => array( 'description' => __( 'To view or modify the field\'s value, the \'object_id\' and \'object_type\' arguments are required.', 'cmb2' ), ), 'object_type' => array( 'description' => __( 'To view or modify the field\'s value, the \'object_id\' and \'object_type\' arguments are required.', 'cmb2' ), ), ); // Returns specific box's fields. register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)/fields/', array( array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'callback' => array( $this, 'get_items' ), 'args' => $args, ), 'schema' => array( $this, 'get_item_schema' ), ) ); $delete_args = $args; $delete_args['object_id']['required'] = true; $delete_args['object_type']['required'] = true; // Returns specific field data. register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)/fields/(?P<field_id>[\w-]+)', array( array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'callback' => array( $this, 'get_item' ), 'args' => $args, ), array( 'methods' => WP_REST_Server::EDITABLE, 'permission_callback' => array( $this, 'update_item_permissions_check' ), 'callback' => array( $this, 'update_item' ), 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), 'args' => $args, ), array( 'methods' => WP_REST_Server::DELETABLE, 'permission_callback' => array( $this, 'delete_item_permissions_check' ), 'callback' => array( $this, 'delete_item' ), 'args' => $delete_args, ), 'schema' => array( $this, 'get_item_schema' ), ) ); } /** * Check if a given request has access to get fields. * By default, no special permissions needed, but filtering return value. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function get_items_permissions_check( $request ) { $this->initiate_rest_read_box( $request, 'fields_read' ); $can_access = true; /** * By default, no special permissions needed. * * @since 2.2.3 * * @param bool $can_access Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_get_fields_permissions_check', $can_access ); } /** * Get all public CMB2 box fields. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_items( $request ) { if ( ! $this->rest_box ) { $this->initiate_rest_read_box( $request, 'fields_read' ); } if ( is_wp_error( $this->rest_box ) ) { return $this->rest_box; } $fields = array(); foreach ( $this->rest_box->cmb->prop( 'fields', array() ) as $field ) { // Make sure this field can be read. $this->field = $this->rest_box->field_can_read( $field['id'], true ); // And make sure current user can view this box. if ( $this->field && $this->get_item_permissions_check_filter() ) { $fields[ $field['id'] ] = $this->server->response_to_data( $this->prepare_field_response(), isset( $this->request['_embed'] ) ); } } return $this->prepare_item( $fields ); } /** * Check if a given request has access to a field. * By default, no special permissions needed, but filtering return value. * * @since 2.2.3 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|boolean */ public function get_item_permissions_check( $request ) { $this->initiate_rest_read_box( $request, 'field_read' ); if ( ! is_wp_error( $this->rest_box ) ) { $this->field = $this->rest_box->field_can_read( $this->request->get_param( 'field_id' ), true ); } return $this->get_item_permissions_check_filter(); } /** * Check by filter if a given request has access to a field. * By default, no special permissions needed, but filtering return value. * * @since 2.2.3 * * @param bool $can_access Whether the current request has access to view the field by default. * @return WP_Error|boolean */ public function get_item_permissions_check_filter( $can_access = true ) { /** * By default, no special permissions needed. * * @since 2.2.3 * * @param bool $can_access Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_get_field_permissions_check', $can_access ); } /** * Get one CMB2 field from the collection. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { $this->initiate_rest_read_box( $request, 'field_read' ); if ( is_wp_error( $this->rest_box ) ) { return $this->rest_box; } return $this->prepare_read_field( $this->request->get_param( 'field_id' ) ); } /** * Check if a given request has access to update a field value. * By default, requires 'edit_others_posts' capability, but filtering return value. * * @since 2.2.3 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|boolean */ public function update_item_permissions_check( $request ) { $this->initiate_rest_read_box( $request, 'field_value_update' ); if ( ! is_wp_error( $this->rest_box ) ) { $this->field = $this->rest_box->field_can_edit( $this->request->get_param( 'field_id' ), true ); } $can_update = current_user_can( 'edit_others_posts' ); /** * By default, 'edit_others_posts' is required capability. * * @since 2.2.3 * * @param bool $can_update Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_update_field_value_permissions_check', $can_update ); } /** * Update CMB2 field value. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function update_item( $request ) { $this->initiate_rest_read_box( $request, 'field_value_update' ); if ( ! $this->request['value'] ) { return new WP_Error( 'cmb2_rest_update_field_error', __( 'CMB2 Field value cannot be updated without the value parameter specified.', 'cmb2' ), array( 'status' => 400, ) ); } return $this->modify_field_value( 'updated' ); } /** * Check if a given request has access to delete a field value. * By default, requires 'delete_others_posts' capability, but filtering return value. * * @since 2.2.3 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|boolean */ public function delete_item_permissions_check( $request ) { $this->initiate_rest_read_box( $request, 'field_value_delete' ); if ( ! is_wp_error( $this->rest_box ) ) { $this->field = $this->rest_box->field_can_edit( $this->request->get_param( 'field_id' ), true ); } $can_delete = current_user_can( 'delete_others_posts' ); /** * By default, 'delete_others_posts' is required capability. * * @since 2.2.3 * * @param bool $can_delete Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_delete_field_value_permissions_check', $can_delete ); } /** * Delete CMB2 field value. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function delete_item( $request ) { $this->initiate_rest_read_box( $request, 'field_value_delete' ); return $this->modify_field_value( 'deleted' ); } /** * Modify CMB2 field value. * * @since 2.2.3 * * @param string $activity The modification activity (updated or deleted). * @return WP_Error|WP_REST_Response */ public function modify_field_value( $activity ) { if ( ! $this->request['object_id'] || ! $this->request['object_type'] ) { return new WP_Error( 'cmb2_rest_modify_field_value_error', __( 'CMB2 Field value cannot be modified without the object_id and object_type parameters specified.', 'cmb2' ), array( 'status' => 400, ) ); } if ( is_wp_error( $this->rest_box ) ) { return $this->rest_box; } $this->field = $this->rest_box->field_can_edit( $this->field ? $this->field : $this->request->get_param( 'field_id' ), true ); if ( ! $this->field ) { return new WP_Error( 'cmb2_rest_no_field_by_id_error', __( 'No field found by that id.', 'cmb2' ), array( 'status' => 403, ) ); } $this->field->args[ "value_{$activity}" ] = (bool) 'deleted' === $activity ? $this->field->remove_data() : $this->field->save_field( $this->request['value'] ); // If options page, save the $activity options if ( 'options-page' == $this->request['object_type'] ) { $this->field->args[ "value_{$activity}" ] = cmb2_options( $this->request['object_id'] )->set(); } return $this->prepare_read_field( $this->field ); } /** * Get a response object for a specific field ID. * * @since 2.2.3 * * @param string\CMB2_Field Field id or Field object. * @return WP_Error|WP_REST_Response */ public function prepare_read_field( $field ) { $this->field = $this->rest_box->field_can_read( $field, true ); if ( ! $this->field ) { return new WP_Error( 'cmb2_rest_no_field_by_id_error', __( 'No field found by that id.', 'cmb2' ), array( 'status' => 403, ) ); } return $this->prepare_item( $this->prepare_field_response() ); } /** * Get a specific field response. * * @since 2.2.3 * * @param CMB2_Field Field object. * @return array Response array. */ public function prepare_field_response() { $field_data = $this->prepare_field_data( $this->field ); $response = rest_ensure_response( $field_data ); $response->add_links( $this->prepare_links( $this->field ) ); return $response; } /** * Prepare the field data array for JSON. * * @since 2.2.3 * * @param CMB2_Field $field field object. * * @return array Array of field data. */ protected function prepare_field_data( CMB2_Field $field ) { $field_data = array(); $params_to_ignore = array( 'show_in_rest', 'options' ); $params_to_rename = array( 'label_cb' => 'label', 'options_cb' => 'options', ); // Run this first so the js_dependencies arg is populated. $rendered = ( $cb = $field->maybe_callback( 'render_row_cb' ) ) // Ok, callback is good, let's run it. ? $this->get_cb_results( $cb, $field->args(), $field ) : false; $field_args = $field->args(); foreach ( $field_args as $key => $value ) { if ( in_array( $key, $params_to_ignore, true ) ) { continue; } if ( 'options_cb' === $key ) { $value = $field->options(); } elseif ( in_array( $key, CMB2_Field::$callable_fields, true ) ) { if ( isset( $this->request['_rendered'] ) ) { $value = $key === 'render_row_cb' ? $rendered : $field->get_param_callback_result( $key ); } elseif ( is_array( $value ) ) { // We need to rewrite callbacks as string as they will cause // JSON recursion errors. $class = is_string( $value[0] ) ? $value[0] : get_class( $value[0] ); $value = $class . '::' . $value[1]; } } $key = isset( $params_to_rename[ $key ] ) ? $params_to_rename[ $key ] : $key; if ( empty( $value ) || is_scalar( $value ) || is_array( $value ) ) { $field_data[ $key ] = $value; } else { $field_data[ $key ] = sprintf( __( 'Value Error for %s', 'cmb2' ), $key ); } } if ( $field->args( 'has_supporting_data' ) ) { $field_data = $this->get_supporting_data( $field_data, $field ); } if ( $this->request['object_id'] && $this->request['object_type'] ) { $field_data['value'] = $field->get_rest_value(); } return $field_data; } /** * Gets field supporting data (field id and value). * * @since 2.7.0 * * @param CMB2_Field $field Field object. * @param array $field_data Array of field data. * * @return array Array of field data. */ public function get_supporting_data( $field_data, $field ) { // Reset placement of this property. unset( $field_data['has_supporting_data'] ); $field_data['has_supporting_data'] = true; $field = $field->get_supporting_field(); $field_data['supporting_data'] = array( 'id' => $field->_id( '', false ), ); if ( $this->request['object_id'] && $this->request['object_type'] ) { $field_data['supporting_data']['value'] = $field->get_rest_value(); } return $field_data; } /** * Return an array of contextual links for field/fields. * * @since 2.2.3 * * @param CMB2_Field $field Field object to build links from. * * @return array Array of links */ protected function prepare_links( $field ) { $boxbase = $this->namespace_base . '/' . $this->rest_box->cmb->cmb_id; $query_string = $this->get_query_string(); $links = array( 'self' => array( 'href' => rest_url( trailingslashit( $boxbase ) . 'fields/' . $field->_id( '', false ) . $query_string ), ), 'collection' => array( 'href' => rest_url( trailingslashit( $boxbase ) . 'fields' . $query_string ), ), 'up' => array( 'embeddable' => true, 'href' => rest_url( $boxbase . $query_string ), ), ); return $links; } /** * Checks if the CMB2 box or field has any registered callback parameters for the given filter. * * The registered handlers will have a property name which matches the filter, except: * - The 'cmb2_api' prefix will be removed * - A '_cb' suffix will be added (to stay inline with other '*_cb' parameters). * * @since 2.2.3 * * @param string $filter The filter name. * @param bool $default_val The default filter value. * * @return bool The possibly-modified filter value (if the _cb param is a non-callable). */ public function maybe_hook_registered_callback( $filter, $default_val ) { $default_val = parent::maybe_hook_registered_callback( $filter, $default_val ); if ( $this->field ) { // Hook field specific filter callbacks. $val = $this->field->maybe_hook_parameter( $filter, $default_val ); if ( null !== $val ) { $default_val = $val; } } return $default_val; } /** * Unhooks any CMB2 box or field registered callback parameters for the given filter. * * @since 2.2.3 * * @param string $filter The filter name. * * @return void */ public function maybe_unhook_registered_callback( $filter ) { parent::maybe_unhook_registered_callback( $filter ); if ( $this->field ) { // Unhook field specific filter callbacks. $this->field->maybe_hook_parameter( $filter, null, 'remove_filter' ); } } } cmb2/cmb2/includes/rest-api/CMB2_REST_Controller.php 0000644 00000025635 15151523433 0016015 0 ustar 00 <?php if ( ! class_exists( 'WP_REST_Controller' ) ) { // Shim the WP_REST_Controller class if wp-api plugin not installed, & not in core. require_once cmb2_dir( 'includes/shim/WP_REST_Controller.php' ); } /** * Creates CMB2 objects/fields endpoint for WordPres REST API. * Allows access to fields registered to a specific post type and more. * * @todo Add better documentation. * @todo Research proper schema. * * @since 2.2.3 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ abstract class CMB2_REST_Controller extends WP_REST_Controller { /** * The namespace of this controller's route. * * @var string */ protected $namespace = CMB2_REST::NAME_SPACE; /** * The base of this controller's route. * * @var string */ protected $rest_base; /** * The current request object * * @var WP_REST_Request $request * @since 2.2.3 */ public $request; /** * The current server object * * @var WP_REST_Server $server * @since 2.2.3 */ public $server; /** * Box object id * * @var mixed * @since 2.2.3 */ public $object_id = null; /** * Box object type * * @var string * @since 2.2.3 */ public $object_type = ''; /** * CMB2 Instance * * @var CMB2_REST */ protected $rest_box; /** * CMB2_Field Instance * * @var CMB2_Field */ protected $field; /** * The initial route * * @var string * @since 2.2.3 */ protected static $route = ''; /** * Defines which endpoint the initial request is. * * @var string $request_type * @since 2.2.3 */ protected static $request_type = ''; /** * Constructor * * @since 2.2.3 */ public function __construct( WP_REST_Server $wp_rest_server ) { $this->server = $wp_rest_server; } /** * A wrapper for `apply_filters` which checks for box/field properties to hook to the filter. * * Checks if a CMB object callback property exists, and if it does, * hook it to the permissions filter. * * @since 2.2.3 * * @param string $filter The name of the filter to apply. * @param bool $default_access The default access for this request. * * @return void */ public function maybe_hook_callback_and_apply_filters( $filter, $default_access ) { if ( ! $this->rest_box && $this->request->get_param( 'cmb_id' ) ) { $this->rest_box = CMB2_REST::get_rest_box( $this->request->get_param( 'cmb_id' ) ); } $default_access = $this->maybe_hook_registered_callback( $filter, $default_access ); /** * Apply the permissions check filter. * * @since 2.2.3 * * @param bool $default_access Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ $default_access = apply_filters( $filter, $default_access, $this ); $this->maybe_unhook_registered_callback( $filter ); return $default_access; } /** * Checks if the CMB2 box has any registered callback parameters for the given filter. * * The registered handlers will have a property name which matches the filter, except: * - The 'cmb2_api' prefix will be removed * - A '_cb' suffix will be added (to stay inline with other '*_cb' parameters). * * @since 2.2.3 * * @param string $filter The filter name. * @param bool $default_val The default filter value. * * @return bool The possibly-modified filter value (if the '*_cb' param is non-callable). */ public function maybe_hook_registered_callback( $filter, $default_val ) { if ( ! $this->rest_box || is_wp_error( $this->rest_box ) ) { return $default_val; } // Hook box specific filter callbacks. $val = $this->rest_box->cmb->maybe_hook_parameter( $filter, $default_val ); if ( null !== $val ) { $default_val = $val; } return $default_val; } /** * Unhooks any CMB2 box registered callback parameters for the given filter. * * @since 2.2.3 * * @param string $filter The filter name. * * @return void */ public function maybe_unhook_registered_callback( $filter ) { if ( ! $this->rest_box || is_wp_error( $this->rest_box ) ) { return; } // Unhook box specific filter callbacks. $this->rest_box->cmb->maybe_hook_parameter( $filter, null, 'remove_filter' ); } /** * Prepare a CMB2 object for serialization * * @since 2.2.3 * * @param mixed $data * @return array $data */ public function prepare_item( $data ) { return $this->prepare_item_for_response( $data, $this->request ); } /** * Output buffers a callback and returns the results. * * @since 2.2.3 * * @param mixed $cb Callable function/method. * @return mixed Results of output buffer after calling function/method. */ public function get_cb_results( $cb ) { $args = func_get_args(); array_shift( $args ); // ignore $cb ob_start(); call_user_func_array( $cb, $args ); return ob_get_clean(); } /** * Prepare the CMB2 item for the REST response. * * @since 2.2.3 * * @param mixed $item WordPress representation of the item. * @param WP_REST_Request $request Request object. * @return WP_REST_Response $response */ public function prepare_item_for_response( $data, $request = null ) { $data = $this->filter_response_by_context( $data, $this->request['context'] ); /** * Filter the prepared CMB2 item response. * * @since 2.2.3 * * @param mixed $data Prepared data * @param object $request The WP_REST_Request object * @param object $cmb2_endpoints This endpoints object */ return apply_filters( 'cmb2_rest_prepare', rest_ensure_response( $data ), $this->request, $this ); } /** * Initiates the request property and the rest_box property if box is readable. * * @since 2.2.3 * * @param WP_REST_Request $request Request object. * @param string $request_type A description of the type of request being made. * * @return void */ protected function initiate_rest_read_box( $request, $request_type ) { $this->initiate_rest_box( $request, $request_type ); if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_read ) { $this->rest_box = new WP_Error( 'cmb2_rest_no_read_error', __( 'This box does not have read permissions.', 'cmb2' ), array( 'status' => 403, ) ); } } /** * Initiates the request property and the rest_box property if box is writeable. * * @since 2.2.3 * * @param WP_REST_Request $request Request object. * @param string $request_type A description of the type of request being made. * * @return void */ protected function initiate_rest_edit_box( $request, $request_type ) { $this->initiate_rest_box( $request, $request_type ); if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_edit ) { $this->rest_box = new WP_Error( 'cmb2_rest_no_write_error', __( 'This box does not have write permissions.', 'cmb2' ), array( 'status' => 403, ) ); } } /** * Initiates the request property and the rest_box property. * * @since 2.2.3 * * @param WP_REST_Request $request Request object. * @param string $request_type A description of the type of request being made. * * @return void */ protected function initiate_rest_box( $request, $request_type ) { $this->initiate_request( $request, $request_type ); $this->rest_box = CMB2_REST::get_rest_box( $this->request->get_param( 'cmb_id' ) ); if ( ! $this->rest_box ) { $this->rest_box = new WP_Error( 'cmb2_rest_box_not_found_error', __( 'No box found by that id. A box needs to be registered with the "show_in_rest" parameter configured.', 'cmb2' ), array( 'status' => 403, ) ); } else { if ( isset( $this->request['object_id'] ) ) { $this->rest_box->cmb->object_id( sanitize_text_field( $this->request['object_id'] ) ); } if ( isset( $this->request['object_type'] ) ) { $this->rest_box->cmb->object_type( sanitize_text_field( $this->request['object_type'] ) ); } } } /** * Initiates the request property and sets up the initial static properties. * * @since 2.2.3 * * @param WP_REST_Request $request Request object. * @param string $request_type A description of the type of request being made. * * @return void */ public function initiate_request( $request, $request_type ) { $this->request = $request; if ( ! isset( $this->request['context'] ) || empty( $this->request['context'] ) ) { $this->request['context'] = 'view'; } if ( ! self::$request_type ) { self::$request_type = $request_type; } if ( ! self::$route ) { self::$route = $this->request->get_route(); } } /** * Useful when getting `_embed`-ed items * * @since 2.2.3 * * @return string Initial requested type. */ public static function get_intial_request_type() { return self::$request_type; } /** * Useful when getting `_embed`-ed items * * @since 2.2.3 * * @return string Initial requested route. */ public static function get_intial_route() { return self::$route; } /** * Get CMB2 fields schema, conforming to JSON Schema * * @since 2.2.3 * * @return array */ public function get_item_schema() { $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'CMB2', 'type' => 'object', 'properties' => array( 'description' => array( 'description' => __( 'A human-readable description of the object.', 'cmb2' ), 'type' => 'string', 'context' => array( 'view', ), ), 'name' => array( 'description' => __( 'The id for the object.', 'cmb2' ), 'type' => 'integer', 'context' => array( 'view', ), ), 'name' => array( 'description' => __( 'The title for the object.', 'cmb2' ), 'type' => 'string', 'context' => array( 'view', ), ), ), ); return $this->add_additional_fields_schema( $schema ); } /** * Return an array of contextual links for endpoint/object * * @link http://v2.wp-api.org/extending/linking/ * @link http://www.iana.org/assignments/link-relations/link-relations.xhtml * * @since 2.2.3 * * @param mixed $object Object to build links from. * * @return array Array of links */ abstract protected function prepare_links( $object ); /** * Get whitelisted query strings from URL for appending to link URLS. * * @since 2.2.3 * * @return string URL query stringl */ public function get_query_string() { $defaults = array( 'object_id' => 0, 'object_type' => '', '_rendered' => '', // '_embed' => '', ); $query_string = ''; foreach ( $defaults as $key => $value ) { if ( isset( $this->request[ $key ] ) ) { $query_string .= $query_string ? '&' : '?'; $query_string .= $key; if ( $value = sanitize_text_field( $this->request[ $key ] ) ) { $query_string .= '=' . $value; } } } return $query_string; } } cmb2/cmb2/includes/rest-api/CMB2_REST_Controller_Boxes.php 0000644 00000016717 15151523433 0017156 0 ustar 00 <?php /** * CMB2 objects/boxes endpoint for WordPres REST API. * Allows access to boxes configuration data. * * @todo Add better documentation. * @todo Research proper schema. * * @since 2.2.3 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_REST_Controller_Boxes extends CMB2_REST_Controller { /** * The base of this controller's route. * * @var string */ protected $rest_base = 'boxes'; /** * The combined $namespace and $rest_base for these routes. * * @var string */ protected $namespace_base = ''; /** * Constructor * * @since 2.2.3 */ public function __construct( WP_REST_Server $wp_rest_server ) { $this->namespace_base = $this->namespace . '/' . $this->rest_base; parent::__construct( $wp_rest_server ); } /** * Register the routes for the objects of the controller. * * @since 2.2.3 */ public function register_routes() { $args = array( '_embed' => array( 'description' => __( 'Includes the registered fields for the box in the response.', 'cmb2' ), ), ); // @todo determine what belongs in the context param. // $args['context'] = $this->get_context_param(); // $args['context']['required'] = false; // $args['context']['default'] = 'view'; // $args['context']['enum'] = array( 'view', 'embed' ); // Returns all boxes data. register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'callback' => array( $this, 'get_items' ), 'args' => $args, ), 'schema' => array( $this, 'get_item_schema' ), ) ); $args['_rendered'] = array( 'description' => __( 'Includes the fully rendered attributes, \'form_open\', \'form_close\', as well as the enqueued \'js_dependencies\' script handles, and \'css_dependencies\' stylesheet handles.', 'cmb2' ), ); // Returns specific box's data. register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)', array( array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'callback' => array( $this, 'get_item' ), 'args' => $args, ), 'schema' => array( $this, 'get_item_schema' ), ) ); } /** * Check if a given request has access to get boxes. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|boolean */ public function get_items_permissions_check( $request ) { $this->initiate_request( $request, __FUNCTION__ ); /** * By default, no special permissions needed. * * @since 2.2.3 * * @param bool $can_access Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ return apply_filters( 'cmb2_api_get_boxes_permissions_check', true, $this ); } /** * Get all public CMB2 boxes. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_items( $request ) { $this->initiate_request( $request, 'boxes_read' ); $boxes = CMB2_REST::get_all(); if ( empty( $boxes ) ) { return new WP_Error( 'cmb2_rest_no_boxes', __( 'No boxes found.', 'cmb2' ), array( 'status' => 403, ) ); } $boxes_data = array(); // Loop and prepare boxes data. foreach ( $boxes as $this->rest_box ) { if ( // Make sure this box can be read $this->rest_box->rest_read // And make sure current user can view this box. && $this->get_item_permissions_check_filter( $this->request ) ) { $boxes_data[] = $this->server->response_to_data( $this->get_rest_box(), isset( $this->request['_embed'] ) ); } } return $this->prepare_item( $boxes_data ); } /** * Check if a given request has access to a box. * By default, no special permissions needed, but filtering return value. * * @since 2.2.3 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|boolean */ public function get_item_permissions_check( $request ) { $this->initiate_rest_read_box( $request, 'box_read' ); return $this->get_item_permissions_check_filter(); } /** * Check by filter if a given request has access to a box. * By default, no special permissions needed, but filtering return value. * * @since 2.2.3 * * @param bool $can_access Whether the current request has access to view the box by default. * @return WP_Error|boolean */ public function get_item_permissions_check_filter( $can_access = true ) { /** * By default, no special permissions needed. * * @since 2.2.3 * * @param bool $can_access Whether this CMB2 endpoint can be accessed. * @param object $controller This CMB2_REST_Controller object. */ return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_get_box_permissions_check', $can_access ); } /** * Get one CMB2 box from the collection. * * @since 2.2.3 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_item( $request ) { $this->initiate_rest_read_box( $request, 'box_read' ); if ( is_wp_error( $this->rest_box ) ) { return $this->rest_box; } return $this->prepare_item( $this->get_rest_box() ); } /** * Get a CMB2 box prepared for REST * * @since 2.2.3 * * @return array */ public function get_rest_box() { $cmb = $this->rest_box->cmb; $boxes_data = $cmb->meta_box; if ( isset( $this->request['_rendered'] ) && $this->namespace_base !== ltrim( CMB2_REST_Controller::get_intial_route(), '/' ) ) { $boxes_data['form_open'] = $this->get_cb_results( array( $cmb, 'render_form_open' ) ); $boxes_data['form_close'] = $this->get_cb_results( array( $cmb, 'render_form_close' ) ); global $wp_scripts, $wp_styles; $before_css = $wp_styles->queue; $before_js = $wp_scripts->queue; CMB2_JS::enqueue(); $boxes_data['js_dependencies'] = array_values( array_diff( $wp_scripts->queue, $before_js ) ); $boxes_data['css_dependencies'] = array_values( array_diff( $wp_styles->queue, $before_css ) ); } // TODO: look into 'embed' parameter. // http://demo.wp-api.org/wp-json/wp/v2/posts?_embed unset( $boxes_data['fields'] ); // Handle callable properties. unset( $boxes_data['show_on_cb'] ); $response = rest_ensure_response( $boxes_data ); $response->add_links( $this->prepare_links( $cmb ) ); return $response; } /** * Return an array of contextual links for box/boxes. * * @since 2.2.3 * * @param CMB2_REST $cmb CMB2_REST object to build links from. * * @return array Array of links */ protected function prepare_links( $cmb ) { $boxbase = $this->namespace_base . '/' . $cmb->cmb_id; $query_string = $this->get_query_string(); return array( // Standard Link Relations -- http://v2.wp-api.org/extending/linking/ 'self' => array( 'href' => rest_url( $boxbase . $query_string ), ), 'collection' => array( 'href' => rest_url( $this->namespace_base . $query_string ), ), // Custom Link Relations -- http://v2.wp-api.org/extending/linking/ // TODO URL should document relationship. 'https://cmb2.io/fields' => array( 'href' => rest_url( trailingslashit( $boxbase ) . 'fields' . $query_string ), 'embeddable' => true, ), ); } } cmb2/cmb2/includes/CMB2_Types.php 0000644 00000051642 15151523433 0012412 0 ustar 00 <?php /** * CMB field type objects * * @since 1.0.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Types { /** * An iterator value for repeatable fields * * @var integer * @since 1.0.0 */ public $iterator = 0; /** * Current CMB2_Field field object * * @var CMB2_Field object * @since 1.0.0 */ public $field; /** * Current CMB2_Type_Base object * * @var CMB2_Type_Base object * @since 2.2.2 */ public $type = null; public function __construct( CMB2_Field $field ) { $this->field = $field; } /** * Default fallback. Allows rendering fields via "cmb2_render_$fieldtype" hook * * @since 1.0.0 * @param string $fieldtype Non-existent field type name * @param array $arguments All arguments passed to the method */ public function __call( $fieldtype, $arguments ) { // Check for methods to be proxied to the CMB2_Type_Base object. if ( $exists = $this->maybe_proxy_method( $fieldtype, $arguments ) ) { return $exists['value']; } // Check for custom field type class. if ( $object = $this->maybe_custom_field_object( $fieldtype, $arguments ) ) { return $object->render(); } /** * Pass non-existent field types through an action. * * The dynamic portion of the hook name, $fieldtype, refers to the field type. * * @param array $field The passed in `CMB2_Field` object * @param mixed $escaped_value The value of this field escaped. * It defaults to `sanitize_text_field`. * If you need the unescaped value, you can access it * via `$field->value()` * @param int $object_id The ID of the current object * @param string $object_type The type of object you are working with. * Most commonly, `post` (this applies to all post-types), * but could also be `comment`, `user` or `options-page`. * @param object $field_type_object This `CMB2_Types` object */ do_action( "cmb2_render_{$fieldtype}", $this->field, $this->field->escaped_value(), $this->field->object_id, $this->field->object_type, $this ); } /** * Render a field (and handle repeatable) * * @since 1.1.0 */ public function render() { if ( $this->field->args( 'repeatable' ) ) { $this->render_repeatable_field(); } else { $this->_render(); } } /** * Render a field type * * @since 1.1.0 */ protected function _render() { $this->field->peform_param_callback( 'before_field' ); echo $this->{$this->field->type()}(); $this->field->peform_param_callback( 'after_field' ); } /** * Proxies the method call to the CMB2_Type_Base object, if it exists, otherwise returns a default fallback value. * * @since 2.2.2 * * @param string $method Method to call on the CMB2_Type_Base object. * @param mixed $default Default fallback value if method is not found. * @param array $args Optional arguments to pass to proxy method. * * @return mixed Results from called method. */ protected function proxy_method( $method, $default, $args = array() ) { if ( ! is_object( $this->type ) ) { $this->guess_type_object( $method ); } if ( is_object( $this->type ) && method_exists( $this->type, $method ) ) { return empty( $args ) ? $this->type->$method() : call_user_func_array( array( $this->type, $method ), $args ); } return $default; } /** * If no CMB2_Types::$type object is initiated when a proxy method is called, it means * it's a custom field type (which SHOULD be instantiating a Type), but let's try and * guess the type object for them and instantiate it. * * @since 2.2.3 * * @param string $method Method attempting to be called on the CMB2_Type_Base object. * @return bool */ protected function guess_type_object( $method ) { $fieldtype = $this->field->type(); // Try to "guess" the Type object based on the method requested. switch ( $method ) { case 'select_option': case 'list_input': case 'list_input_checkbox': case 'concat_items': $this->get_new_render_type( $fieldtype, 'CMB2_Type_Select' ); break; case 'is_valid_img_ext': case 'img_status_output': case 'file_status_output': $this->get_new_render_type( $fieldtype, 'CMB2_Type_File_Base' ); break; case 'parse_picker_options': $this->get_new_render_type( $fieldtype, 'CMB2_Type_Text_Date' ); break; case 'get_object_terms': case 'get_terms': $this->get_new_render_type( $fieldtype, 'CMB2_Type_Taxonomy_Multicheck' ); break; case 'date_args': case 'time_args': $this->get_new_render_type( $fieldtype, 'CMB2_Type_Text_Datetime_Timestamp' ); break; case 'parse_args': $this->get_new_render_type( $fieldtype, 'CMB2_Type_Text' ); break; } return null !== $this->type; } /** * Check for methods to be proxied to the CMB2_Type_Base object. * * @since 2.2.4 * @param string $method The possible method to proxy. * @param array $arguments All arguments passed to the method. * @return bool|array False if not proxied, else array with 'value' key being the return of the method. */ public function maybe_proxy_method( $method, $arguments ) { $exists = false; $proxied = array( 'get_object_terms' => array(), 'is_valid_img_ext' => false, 'parse_args' => array(), 'concat_items' => '', 'select_option' => '', 'list_input' => '', 'list_input_checkbox' => '', 'img_status_output' => '', 'file_status_output' => '', 'parse_picker_options' => array(), ); if ( isset( $proxied[ $method ] ) ) { $exists = array( // Ok, proxy the method call to the CMB2_Type_Base object. 'value' => $this->proxy_method( $method, $proxied[ $method ], $arguments ), ); } return $exists; } /** * Checks for a custom field CMB2_Type_Base class to use for rendering. * * @since 2.2.4 * * @param string $fieldtype Non-existent field type name. * @param array $args Optional field arguments. * * @return bool|CMB2_Type_Base Type object if custom field is an object, false if field was added with * `cmb2_render_{$field_type}` action. * @throws Exception if custom field type class does not extend CMB2_Type_Base. */ public function maybe_custom_field_object( $fieldtype, $args = array() ) { if ( $render_class_name = $this->get_render_type_class( $fieldtype ) ) { $this->type = new $render_class_name( $this, $args ); if ( ! ( $this->type instanceof CMB2_Type_Base ) ) { throw new Exception( __( 'Custom CMB2 field type classes must extend CMB2_Type_Base.', 'cmb2' ) ); } return $this->type; } return false; } /** * Gets the render type CMB2_Type_Base object to use for rendering the field. * * @since 2.2.4 * @param string $fieldtype The type of field being rendered. * @param string $render_class_name The default field type class to use. Defaults to null. * @param array $args Optional arguments to pass to type class. * @param mixed $additional Optional additional argument to pass to type class. * @return CMB2_Type_Base Type object. */ public function get_new_render_type( $fieldtype, $render_class_name = null, $args = array(), $additional = '' ) { $render_class_name = $this->get_render_type_class( $fieldtype, $render_class_name ); $this->type = new $render_class_name( $this, $args, $additional ); return $this->type; } /** * Checks for the render type class to use for rendering the field. * * @since 2.2.4 * @param string $fieldtype The type of field being rendered. * @param string $render_class_name The default field type class to use. Defaults to null. * @return string The field type class to use. */ public function get_render_type_class( $fieldtype, $render_class_name = null ) { $render_class_name = $this->field->args( 'render_class' ) ? $this->field->args( 'render_class' ) : $render_class_name; if ( has_action( "cmb2_render_class_{$fieldtype}" ) ) { /** * Filters the custom field type class used for rendering the field. Class is required to extend CMB2_Type_Base. * * The dynamic portion of the hook name, $fieldtype, refers to the (custom) field type. * * @since 2.2.4 * * @param string $render_class_name The custom field type class to use. Default null. * @param object $field_type_object This `CMB2_Types` object. */ $render_class_name = apply_filters( "cmb2_render_class_{$fieldtype}", $render_class_name, $this ); } return $render_class_name && class_exists( $render_class_name ) ? $render_class_name : false; } /** * Retrieve text parameter from field's options array (if it has one), or use fallback text * * @since 2.0.0 * @param string $text_key Key in field's options array. * @param string $fallback Fallback text. * @return string */ public function _text( $text_key, $fallback = '' ) { return $this->field->get_string( $text_key, $fallback ); } /** * Determine a file's extension * * @since 1.0.0 * @param string $file File url * @return string|false File extension or false */ public function get_file_ext( $file ) { return CMB2_Utils::get_file_ext( $file ); } /** * Get the file name from a url * * @since 2.0.0 * @param string $value File url or path * @return string File name */ public function get_file_name_from_path( $value ) { return CMB2_Utils::get_file_name_from_path( $value ); } /** * Combines attributes into a string for a form element * * @since 1.1.0 * @param array $attrs Attributes to concatenate * @param array $attr_exclude Attributes that should NOT be concatenated * @return string String of attributes for form element */ public function concat_attrs( $attrs, $attr_exclude = array() ) { return CMB2_Utils::concat_attrs( $attrs, $attr_exclude ); } /** * Generates repeatable field table markup * * @since 1.0.0 */ public function render_repeatable_field() { $table_id = $this->field->id() . '_repeat'; $this->_desc( true, true, true ); ?> <div id="<?php echo $table_id; ?>" class="cmb-repeat-table cmb-nested"> <div class="cmb-tbody cmb-field-list"> <?php $this->repeatable_rows(); ?> </div> </div> <p class="cmb-add-row"> <button type="button" data-selector="<?php echo $table_id; ?>" class="cmb-add-row-button button-secondary"><?php echo esc_html( $this->_text( 'add_row_text', esc_html__( 'Add Row', 'cmb2' ) ) ); ?></button> </p> <?php // reset iterator $this->iterator = 0; } /** * Generates repeatable field rows * * @since 1.1.0 */ public function repeatable_rows() { $meta_value = array_filter( (array) $this->field->escaped_value() ); // check for default content $default = $this->field->get_default(); // check for saved data if ( ! empty( $meta_value ) ) { $meta_value = is_array( $meta_value ) ? array_filter( $meta_value ) : $meta_value; $meta_value = ! empty( $meta_value ) ? $meta_value : $default; } else { $meta_value = $default; } // Loop value array and add a row if ( ! empty( $meta_value ) ) { foreach ( (array) $meta_value as $val ) { $this->field->escaped_value = $val; $this->repeat_row(); $this->iterator++; } } else { // If value is empty (including empty array), then clear the value. $this->field->escaped_value = $this->field->value = null; // Otherwise add one row $this->repeat_row(); } // Then add an empty row $this->field->escaped_value = $default; $this->iterator = $this->iterator ? $this->iterator : 1; $this->repeat_row( 'empty-row hidden' ); } /** * Generates a repeatable row's markup * * @since 1.1.0 * @param string $classes Repeatable table row's class */ protected function repeat_row( $classes = 'cmb-repeat-row' ) { $classes = explode( ' ', $classes ); $classes = array_map( 'sanitize_html_class', $classes ); ?> <div class="cmb-row <?php echo esc_attr( implode( ' ', $classes ) ); ?>"> <div class="cmb-td"> <?php $this->_render(); ?> </div> <div class="cmb-td cmb-remove-row"> <button type="button" class="button-secondary cmb-remove-row-button" title="<?php echo esc_attr( $this->_text( 'remove_row_button_title', esc_html__( 'Remove Row', 'cmb2' ) ) ); ?>"><?php echo esc_html( $this->_text( 'remove_row_text', esc_html__( 'Remove', 'cmb2' ) ) ); ?></button> </div> </div> <?php } /** * Generates description markup. * * @since 1.0.0 * @param bool $paragraph Paragraph tag or span. * @param bool $echo Whether to echo description or only return it. * @param bool $repeat_group Whether to repeat the group. * @return string Field's description markup. */ public function _desc( $paragraph = false, $echo = false, $repeat_group = false ) { // Prevent description from printing multiple times for repeatable fields if ( ! $repeat_group && ( $this->field->args( 'repeatable' ) || $this->iterator > 0 ) ) { return ''; } $desc = $this->field->args( 'description' ); if ( ! $desc ) { return; } $tag = $paragraph ? 'p' : 'span'; $desc = sprintf( "\n" . '<%1$s class="cmb2-metabox-description">%2$s</%1$s>' . "\n", $tag, $desc ); if ( $echo ) { echo $desc; } return $desc; } /** * Generate field name attribute * * @since 1.1.0 * @param string $suffix For multi-part fields * @return string Name attribute */ public function _name( $suffix = '' ) { return $this->field->args( '_name' ) . ( $this->field->args( 'repeatable' ) ? '[' . $this->iterator . ']' : '' ) . $suffix; } /** * Generate field id attribute * * @since 1.1.0 * @param string $suffix For multi-part fields * @param bool $append_repeatable_iterator Whether to append the iterator attribue if the field is repeatable. * @return string Id attribute */ public function _id( $suffix = '', $append_repeatable_iterator = true ) { $id = $this->field->id() . $suffix . ( $this->field->args( 'repeatable' ) ? '_' . $this->iterator : '' ); if ( $append_repeatable_iterator && $this->field->args( 'repeatable' ) ) { $id .= '" data-iterator="' . $this->iterator; } return $id; } /** * Handles outputting an 'input' element * * @since 1.1.0 * @param array $args Override arguments * @param string $type Field type * @return string Form input element */ public function input( $args = array(), $type = __FUNCTION__ ) { return $this->get_new_render_type( 'text', 'CMB2_Type_Text', $args, $type )->render(); } /** * Handles outputting an 'textarea' element * * @since 1.1.0 * @param array $args Override arguments * @return string Form textarea element */ public function textarea( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Textarea', $args )->render(); } /** * Begin Field Types */ public function text() { return $this->input(); } public function hidden() { $args = array( 'type' => 'hidden', 'desc' => '', 'class' => 'cmb2-hidden', ); if ( $this->field->group ) { $args['data-groupid'] = $this->field->group->id(); $args['data-iterator'] = $this->iterator; } return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text', $args, 'input' )->render(); } public function text_small() { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text', array( 'class' => 'cmb2-text-small', 'desc' => $this->_desc(), ), 'input' )->render(); } public function text_medium() { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text', array( 'class' => 'cmb2-text-medium', 'desc' => $this->_desc(), ), 'input' )->render(); } public function text_email() { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text', array( 'class' => 'cmb2-text-email cmb2-text-medium', 'type' => 'email', ), 'input' )->render(); } public function text_url() { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text', array( 'class' => 'cmb2-text-url cmb2-text-medium regular-text', 'value' => $this->field->escaped_value( 'esc_url' ), ), 'input' )->render(); } public function text_money() { $input = $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text', array( 'class' => 'cmb2-text-money', 'desc' => $this->_desc(), ), 'input' )->render(); return ( ! $this->field->get_param_callback_result( 'before_field' ) ? '$ ' : ' ' ) . $input; } public function textarea_small() { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Textarea', array( 'class' => 'cmb2-textarea-small', 'rows' => 4, ) )->render(); } public function textarea_code( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Textarea_Code', $args )->render(); } public function wysiwyg( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Wysiwyg', $args )->render(); } public function text_date( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text_Date', $args )->render(); } // Alias for text_date public function text_date_timestamp( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text_Date', $args )->render(); } public function text_time( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text_Time', $args )->render(); } public function text_datetime_timestamp( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text_Datetime_Timestamp', $args )->render(); } public function text_datetime_timestamp_timezone( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Text_Datetime_Timestamp_Timezone', $args )->render(); } public function select_timezone( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Select_Timezone', $args )->render(); } public function colorpicker( $args = array(), $meta_value = '' ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Colorpicker', $args, $meta_value )->render(); } public function title( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Title', $args )->render(); } public function select( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Select', $args )->render(); } public function taxonomy_select( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Taxonomy_Select', $args )->render(); } public function taxonomy_select_hierarchical( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Taxonomy_Select_Hierarchical', $args )->render(); } public function radio( $args = array(), $type = __FUNCTION__ ) { return $this->get_new_render_type( $type, 'CMB2_Type_Radio', $args, $type )->render(); } public function radio_inline( $args = array() ) { return $this->radio( $args, __FUNCTION__ ); } public function multicheck( $type = 'checkbox' ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Multicheck', array(), $type )->render(); } public function multicheck_inline() { return $this->multicheck( 'multicheck_inline' ); } public function checkbox( $args = array(), $is_checked = null ) { // Avoid get_new_render_type since we need a different default for the 3rd argument than ''. $render_class_name = $this->get_render_type_class( __FUNCTION__, 'CMB2_Type_Checkbox' ); $this->type = new $render_class_name( $this, $args, $is_checked ); return $this->type->render(); } public function taxonomy_radio( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Taxonomy_Radio', $args )->render(); } public function taxonomy_radio_hierarchical( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Taxonomy_Radio_Hierarchical', $args )->render(); } public function taxonomy_radio_inline( $args = array() ) { return $this->taxonomy_radio( $args ); } public function taxonomy_multicheck( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Taxonomy_Multicheck', $args )->render(); } public function taxonomy_multicheck_hierarchical( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Taxonomy_Multicheck_Hierarchical', $args )->render(); } public function taxonomy_multicheck_inline( $args = array() ) { return $this->taxonomy_multicheck( $args ); } public function oembed( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_Oembed', $args )->render(); } public function file_list( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_File_List', $args )->render(); } public function file( $args = array() ) { return $this->get_new_render_type( __FUNCTION__, 'CMB2_Type_File', $args )->render(); } } cmb2/cmb2/includes/CMB2_Utils.php 0000644 00000053270 15151523433 0012405 0 ustar 00 <?php /** * CMB2 Utilities * * @since 1.1.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Utils { /** * The WordPress ABSPATH constant. * * @var string * @since 2.2.3 */ protected static $ABSPATH = ABSPATH; /** * The url which is used to load local resources. * * @var string * @since 2.0.0 */ protected static $url = ''; /** * Utility method that attempts to get an attachment's ID by it's url * * @since 1.0.0 * @param string $img_url Attachment url. * @return int|false Attachment ID or false */ public static function image_id_from_url( $img_url ) { $attachment_id = 0; $dir = wp_upload_dir(); // Is URL in uploads directory? if ( false === strpos( $img_url, $dir['baseurl'] . '/' ) ) { return false; } $file = basename( $img_url ); $query_args = array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'fields' => 'ids', 'meta_query' => array( array( 'value' => $file, 'compare' => 'LIKE', 'key' => '_wp_attachment_metadata', ), ), ); $query = new WP_Query( $query_args ); if ( $query->have_posts() ) { foreach ( $query->posts as $post_id ) { $meta = wp_get_attachment_metadata( $post_id ); $original_file = basename( $meta['file'] ); $cropped_image_files = isset( $meta['sizes'] ) ? wp_list_pluck( $meta['sizes'], 'file' ) : array(); if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) { $attachment_id = $post_id; break; } } } return 0 === $attachment_id ? false : $attachment_id; } /** * Utility method to get a combined list of default and custom registered image sizes * * @since 2.2.4 * @link http://core.trac.wordpress.org/ticket/18947 * @global array $_wp_additional_image_sizes * @return array The image sizes */ public static function get_available_image_sizes() { global $_wp_additional_image_sizes; $default_image_sizes = array( 'thumbnail', 'medium', 'large' ); foreach ( $default_image_sizes as $size ) { $image_sizes[ $size ] = array( 'height' => intval( get_option( "{$size}_size_h" ) ), 'width' => intval( get_option( "{$size}_size_w" ) ), 'crop' => get_option( "{$size}_crop" ) ? get_option( "{$size}_crop" ) : false, ); } if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) { $image_sizes = array_merge( $image_sizes, $_wp_additional_image_sizes ); } return $image_sizes; } /** * Utility method to return the closest named size from an array of values * * Based off of WordPress's image_get_intermediate_size() * If the size matches an existing size then it will be used. If there is no * direct match, then the nearest image size larger than the specified size * will be used. If nothing is found, then the function will return false. * Uses get_available_image_sizes() to get all available sizes. * * @since 2.2.4 * @param array|string $size Image size. Accepts an array of width and height (in that order). * @return false|string Named image size e.g. 'thumbnail' */ public static function get_named_size( $size ) { $data = array(); // Find the best match when '$size' is an array. if ( is_array( $size ) ) { $image_sizes = self::get_available_image_sizes(); $candidates = array(); foreach ( $image_sizes as $_size => $data ) { // If there's an exact match to an existing image size, short circuit. if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) { $candidates[ $data['width'] * $data['height'] ] = array( $_size, $data ); break; } // If it's not an exact match, consider larger sizes with the same aspect ratio. if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) { /** * To test for varying crops, we constrain the dimensions of the larger image * to the dimensions of the smaller image and see if they match. */ if ( $data['width'] > $size[0] ) { $constrained_size = wp_constrain_dimensions( $data['width'], $data['height'], $size[0] ); $expected_size = array( $size[0], $size[1] ); } else { $constrained_size = wp_constrain_dimensions( $size[0], $size[1], $data['width'] ); $expected_size = array( $data['width'], $data['height'] ); } // If the image dimensions are within 1px of the expected size, we consider it a match. $matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ); if ( $matched ) { $candidates[ $data['width'] * $data['height'] ] = array( $_size, $data ); } } } if ( ! empty( $candidates ) ) { // Sort the array by size if we have more than one candidate. if ( 1 < count( $candidates ) ) { ksort( $candidates ); } $data = array_shift( $candidates ); $data = $data[0]; } elseif ( ! empty( $image_sizes['thumbnail'] ) && $image_sizes['thumbnail']['width'] >= $size[0] && $image_sizes['thumbnail']['width'] >= $size[1] ) { /* * When the size requested is smaller than the thumbnail dimensions, we * fall back to the thumbnail size. */ $data = 'thumbnail'; } else { return false; } } elseif ( ! empty( $image_sizes[ $size ] ) ) { $data = $size; }// End if. // If we still don't have a match at this point, return false. if ( empty( $data ) ) { return false; } return $data; } /** * Utility method that returns time string offset by timezone * * @since 1.0.0 * @param string $tzstring Time string. * @return string Offset time string */ public static function timezone_offset( $tzstring ) { $tz_offset = 0; if ( ! empty( $tzstring ) && is_string( $tzstring ) ) { if ( 'UTC' === substr( $tzstring, 0, 3 ) ) { $tzstring = str_replace( array( ':15', ':30', ':45' ), array( '.25', '.5', '.75' ), $tzstring ); return intval( floatval( substr( $tzstring, 3 ) ) * HOUR_IN_SECONDS ); } try { $date_time_zone_selected = new DateTimeZone( $tzstring ); $tz_offset = timezone_offset_get( $date_time_zone_selected, date_create() ); } catch ( Exception $e ) { self::log_if_debug( __METHOD__, __LINE__, $e->getMessage() ); } } return $tz_offset; } /** * Utility method that returns a timezone string representing the default timezone for the site. * * Roughly copied from WordPress, as get_option('timezone_string') will return * an empty string if no value has been set on the options page. * A timezone string is required by the wp_timezone_choice() used by the * select_timezone field. * * @since 1.0.0 * @return string Timezone string */ public static function timezone_string() { $current_offset = get_option( 'gmt_offset' ); $tzstring = get_option( 'timezone_string' ); // Remove old Etc mappings. Fallback to gmt_offset. if ( false !== strpos( $tzstring, 'Etc/GMT' ) ) { $tzstring = ''; } if ( empty( $tzstring ) ) { // Create a UTC+- zone if no timezone string exists. if ( 0 == $current_offset ) { $tzstring = 'UTC+0'; } elseif ( $current_offset < 0 ) { $tzstring = 'UTC' . $current_offset; } else { $tzstring = 'UTC+' . $current_offset; } } return $tzstring; } /** * Returns a unix timestamp, first checking if value already is a timestamp. * * @since 2.0.0 * @param string|int $string Possible timestamp string. * @return int Time stamp. */ public static function make_valid_time_stamp( $string ) { if ( ! $string ) { return 0; } $valid = self::is_valid_time_stamp( $string ); if ( $valid ) { $timestamp = (int) $string; $length = strlen( (string) $timestamp ); $unixlength = strlen( (string) time() ); $diff = $length - $unixlength; // If value is larger than a unix timestamp, we need to round to the // nearest unix timestamp (in seconds). if ( $diff > 0 ) { $divider = (int) '1' . str_repeat( '0', $diff ); $timestamp = round( $timestamp / $divider ); } } else { $timestamp = @strtotime( (string) $string ); } return $timestamp; } /** * Determine if a value is a valid date. * * @since 2.9.1 * @param mixed $date Value to check. * @return boolean Whether value is a valid date */ public static function is_valid_date( $date ) { return ( is_string( $date ) && @strtotime( $date ) ) || self::is_valid_time_stamp( $date ); } /** * Determine if a value is a valid timestamp * * @since 2.0.0 * @param mixed $timestamp Value to check. * @return boolean Whether value is a valid timestamp */ public static function is_valid_time_stamp( $timestamp ) { return (string) (int) $timestamp === (string) $timestamp && $timestamp <= PHP_INT_MAX && $timestamp >= ~PHP_INT_MAX; } /** * Checks if a value is 'empty'. Still accepts 0. * * @since 2.0.0 * @param mixed $value Value to check. * @return bool True or false */ public static function isempty( $value ) { return null === $value || '' === $value || false === $value || array() === $value; } /** * Checks if a value is not 'empty'. 0 doesn't count as empty. * * @since 2.2.2 * @param mixed $value Value to check. * @return bool True or false */ public static function notempty( $value ) { return null !== $value && '' !== $value && false !== $value && array() !== $value; } /** * Filters out empty values (not including 0). * * @since 2.2.2 * @param mixed $value Value to check. * @return array True or false. */ public static function filter_empty( $value ) { return array_filter( $value, array( __CLASS__, 'notempty' ) ); } /** * Insert a single array item inside another array at a set position * * @since 2.0.2 * @param array $array Array to modify. Is passed by reference, and no return is needed. Passed by reference. * @param array $new New array to insert. * @param int $position Position in the main array to insert the new array. */ public static function array_insert( &$array, $new, $position ) { $before = array_slice( $array, 0, $position - 1 ); $after = array_diff_key( $array, $before ); $array = array_merge( $before, $new, $after ); } /** * Defines the url which is used to load local resources. * This may need to be filtered for local Window installations. * If resources do not load, please check the wiki for details. * * @since 1.0.1 * * @param string $path URL path. * @return string URL to CMB2 resources */ public static function url( $path = '' ) { if ( self::$url ) { return self::$url . $path; } $cmb2_url = self::get_url_from_dir( cmb2_dir() ); /** * Filter the CMB location url. * * @param string $cmb2_url Currently registered url. */ self::$url = trailingslashit( apply_filters( 'cmb2_meta_box_url', $cmb2_url, CMB2_VERSION ) ); return self::$url . $path; } /** * Converts a system path to a URL * * @since 2.2.2 * @param string $dir Directory path to convert. * @return string Converted URL. */ public static function get_url_from_dir( $dir ) { $dir = self::normalize_path( $dir ); // Let's test if We are in the plugins or mu-plugins dir. $test_dir = trailingslashit( $dir ) . 'unneeded.php'; if ( 0 === strpos( $test_dir, self::normalize_path( WPMU_PLUGIN_DIR ) ) || 0 === strpos( $test_dir, self::normalize_path( WP_PLUGIN_DIR ) ) ) { // Ok, then use plugins_url, as it is more reliable. return trailingslashit( plugins_url( '', $test_dir ) ); } // Ok, now let's test if we are in the theme dir. $theme_root = self::normalize_path( get_theme_root() ); if ( 0 === strpos( $dir, $theme_root ) ) { // Ok, then use get_theme_root_uri. return set_url_scheme( trailingslashit( str_replace( untrailingslashit( $theme_root ), untrailingslashit( get_theme_root_uri() ), $dir ) ) ); } // Check to see if it's anywhere in the root directory. $site_dir = self::get_normalized_abspath(); $site_url = trailingslashit( is_multisite() ? network_site_url() : site_url() ); $url = str_replace( array( $site_dir, WP_PLUGIN_DIR ), array( $site_url, WP_PLUGIN_URL ), $dir ); return set_url_scheme( $url ); } /** * Get the normalized absolute path defined by WordPress. * * @since 2.2.6 * * @return string Normalized absolute path. */ protected static function get_normalized_abspath() { return self::normalize_path( self::$ABSPATH ); } /** * `wp_normalize_path` wrapper for back-compat. Normalize a filesystem path. * * On windows systems, replaces backslashes with forward slashes * and forces upper-case drive letters. * Allows for two leading slashes for Windows network shares, but * ensures that all other duplicate slashes are reduced to a single. * * @since 2.2.0 * * @param string $path Path to normalize. * @return string Normalized path. */ protected static function normalize_path( $path ) { if ( function_exists( 'wp_normalize_path' ) ) { return wp_normalize_path( $path ); } // Replace newer WP's version of wp_normalize_path. $path = str_replace( '\\', '/', $path ); $path = preg_replace( '|(?<=.)/+|', '/', $path ); if ( ':' === substr( $path, 1, 1 ) ) { $path = ucfirst( $path ); } return $path; } /** * Get timestamp from text date * * @since 2.2.0 * @param string $value Date value. * @param string $date_format Expected date format. * @return mixed Unix timestamp representing the date. */ public static function get_timestamp_from_value( $value, $date_format ) { $date_object = date_create_from_format( $date_format, $value ); return $date_object ? $date_object->setTime( 0, 0, 0 )->getTimeStamp() : strtotime( $value ); } /** * Takes a php date() format string and returns a string formatted to suit for the date/time pickers * It will work only with the following subset of date() options: * * Formats: d, l, j, z, m, F, n, y, and Y. * * A slight effort is made to deal with escaped characters. * * Other options are ignored, because they would either bring compatibility problems between PHP and JS, or * bring even more translation troubles. * * @since 2.2.0 * @param string $format PHP date format. * @return string reformatted string */ public static function php_to_js_dateformat( $format ) { // order is relevant here, since the replacement will be done sequentially. $supported_options = array( 'd' => 'dd', // Day, leading 0. 'j' => 'd', // Day, no 0. 'z' => 'o', // Day of the year, no leading zeroes. // 'D' => 'D', // Day name short, not sure how it'll work with translations. 'l ' => 'DD ', // Day name full, idem before. 'l, ' => 'DD, ', // Day name full, idem before. 'm' => 'mm', // Month of the year, leading 0. 'n' => 'm', // Month of the year, no leading 0. // 'M' => 'M', // Month, Short name. 'F ' => 'MM ', // Month, full name. 'F, ' => 'MM, ', // Month, full name. 'y' => 'y', // Year, two digit. 'Y' => 'yy', // Year, full. 'H' => 'HH', // Hour with leading 0 (24 hour). 'G' => 'H', // Hour with no leading 0 (24 hour). 'h' => 'hh', // Hour with leading 0 (12 hour). 'g' => 'h', // Hour with no leading 0 (12 hour). 'i' => 'mm', // Minute with leading 0. 's' => 'ss', // Second with leading 0. 'a' => 'tt', // am/pm. 'A' => 'TT', // AM/PM. ); foreach ( $supported_options as $php => $js ) { // replaces every instance of a supported option, but skips escaped characters. $format = preg_replace( "~(?<!\\\\)$php~", $js, $format ); } $supported_options = array( 'l' => 'DD', // Day name full, idem before. 'F' => 'MM', // Month, full name. ); if ( isset( $supported_options[ $format ] ) ) { $format = $supported_options[ $format ]; } $format = preg_replace_callback( '~(?:\\\.)+~', array( __CLASS__, 'wrap_escaped_chars' ), $format ); return $format; } /** * Get a DateTime object from a value. * * @since 2.11.0 * * @param string $value The value to convert to a DateTime object. * * @return DateTime|null */ public static function get_datetime_from_value( $value ) { return is_serialized( $value ) // Ok, we need to unserialize the value // -- allows back-compat for older field values with serialized DateTime objects. ? self::unserialize_datetime( $value ) // Handle new json formatted values. : self::json_to_datetime( $value ); } /** * Unserialize a datetime value string. * * This is a back-compat method for older field values with serialized DateTime objects. * * @since 2.11.0 * * @param string $date_value The serialized datetime value. * * @return DateTime|null */ public static function unserialize_datetime( $date_value ) { $datetime = @unserialize( trim( $date_value ), array( 'allowed_classes' => array( 'DateTime' ) ) ); return $datetime && $datetime instanceof DateTime ? $datetime : null; } /** * Convert a json datetime value string to a DateTime object. * * @since 2.11.0 * * @param string $json_string The json value string. * * @return DateTime|null */ public static function json_to_datetime( $json_string ) { if ( ! is_string( $json_string ) ) { return null; } $json = json_decode( $json_string ); // Check if json decode was successful if ( json_last_error() !== JSON_ERROR_NONE ) { return null; } // If so, convert to DateTime object. return self::unserialize_datetime( str_replace( 'stdClass', 'DateTime', serialize( $json ) ) ); } /** * Helper function for CMB_Utils::php_to_js_dateformat(). * * @since 2.2.0 * @param string $value Value to wrap/escape. * @return string Modified value */ public static function wrap_escaped_chars( $value ) { return ''' . str_replace( '\\', '', $value[0] ) . '''; } /** * Send to debug.log if WP_DEBUG is defined and true * * @since 2.2.0 * * @param string $function Function name. * @param int $line Line number. * @param mixed $msg Message to output. * @param mixed $debug Variable to print_r. */ public static function log_if_debug( $function, $line, $msg, $debug = null ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( "In $function, $line:" . print_r( $msg, true ) . ( $debug ? print_r( $debug, true ) : '' ) ); } } /** * Determine a file's extension * * @since 1.0.0 * @param string $file File url. * @return string|false File extension or false */ public static function get_file_ext( $file ) { $parsed = parse_url( $file, PHP_URL_PATH ); return $parsed ? strtolower( pathinfo( $parsed, PATHINFO_EXTENSION ) ) : false; } /** * Get the file name from a url * * @since 2.0.0 * @param string $value File url or path. * @return string File name */ public static function get_file_name_from_path( $value ) { $parts = explode( '/', $value ); return is_array( $parts ) ? end( $parts ) : $value; } /** * Check if WP version is at least $version. * * @since 2.2.2 * @param string $version WP version string to compare. * @return bool Result of comparison check. */ public static function wp_at_least( $version ) { return version_compare( get_bloginfo( 'version' ), $version, '>=' ); } /** * Combines attributes into a string for a form element. * * @since 1.1.0 * @param array $attrs Attributes to concatenate. * @param array $attr_exclude Attributes that should NOT be concatenated. * @return string String of attributes for form element. */ public static function concat_attrs( $attrs, $attr_exclude = array() ) { $attr_exclude[] = 'rendered'; $attr_exclude[] = 'js_dependencies'; $attributes = ''; foreach ( $attrs as $attr => $val ) { $excluded = in_array( $attr, (array) $attr_exclude, true ); $empty = false === $val && 'value' !== $attr; if ( ! $excluded && ! $empty ) { $val = is_array( $val ) ? implode( ',', $val ) : $val; // if data attribute, use single quote wraps, else double. $quotes = self::is_data_attribute( $attr ) ? "'" : '"'; $attributes .= sprintf( ' %1$s=%3$s%2$s%3$s', $attr, $val, $quotes ); } } return $attributes; } /** * Check if given attribute is a data attribute. * * @since 2.2.5 * * @param string $att HTML attribute. * @return boolean */ public static function is_data_attribute( $att ) { return 0 === stripos( $att, 'data-' ); } /** * Ensures value is an array. * * @since 2.2.3 * * @param mixed $value Value to ensure is array. * @param array $default Default array. Defaults to empty array. * * @return array The array. */ public static function ensure_array( $value, $default = array() ) { if ( empty( $value ) ) { return $default; } if ( is_array( $value ) || is_object( $value ) ) { return (array) $value; } // Not sure anything would be non-scalar that is not an array or object? if ( ! is_scalar( $value ) ) { return $default; } return (array) $value; } /** * If number is numeric, normalize it with floatval or intval, depending on if decimal is found. * * @since 2.2.6 * * @param mixed $value Value to normalize (if numeric). * @return mixed Possibly normalized value. */ public static function normalize_if_numeric( $value ) { if ( is_numeric( $value ) ) { $value = false !== strpos( $value, '.' ) ? floatval( $value ) : intval( $value ); } return $value; } /** * Generates a 12 character unique hash from a string. * * @since 2.4.0 * * @param string $string String to create a hash from. * * @return string */ public static function generate_hash( $string ) { return substr( base_convert( md5( $string ), 16, 32 ), 0, 12 ); } } cmb2/cmb2/includes/CMB2_Sanitize.php 0000644 00000042163 15151523433 0013072 0 ustar 00 <?php /** * CMB2 field sanitization * * @since 0.0.4 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @method string _id() */ class CMB2_Sanitize { /** * A CMB field object * * @var CMB2_Field object */ public $field; /** * Field's value * * @var mixed */ public $value; /** * Setup our class vars * * @since 1.1.0 * @param CMB2_Field $field A CMB2 field object. * @param mixed $value Field value. */ public function __construct( CMB2_Field $field, $value ) { $this->field = $field; $this->value = $value; } /** * Catchall method if field's 'sanitization_cb' is NOT defined, * or field type does not have a corresponding validation method. * * @since 1.0.0 * * @param string $name Non-existent method name. * @param array $arguments All arguments passed to the method. * @return mixed */ public function __call( $name, $arguments ) { return $this->default_sanitization(); } /** * Default fallback sanitization method. Applies filters. * * @since 1.0.2 */ public function default_sanitization() { $field_type = $this->field->type(); /** * This exists for back-compatibility, but validation * is not what happens here. * * @deprecated See documentation for "cmb2_sanitize_{$field_type}". */ if ( function_exists( 'apply_filters_deprecated' ) ) { $override_value = apply_filters_deprecated( "cmb2_validate_{$field_type}", array( null, $this->value, $this->field->object_id, $this->field->args(), $this ), '2.0.0', "cmb2_sanitize_{$field_type}" ); } else { $override_value = apply_filters( "cmb2_validate_{$field_type}", null, $this->value, $this->field->object_id, $this->field->args(), $this ); } if ( null !== $override_value ) { return $override_value; } $sanitized_value = ''; switch ( $field_type ) { case 'wysiwyg': case 'textarea_small': case 'oembed': $sanitized_value = $this->textarea(); break; case 'taxonomy_select': case 'taxonomy_select_hierarchical': case 'taxonomy_radio': case 'taxonomy_radio_inline': case 'taxonomy_radio_hierarchical': case 'taxonomy_multicheck': case 'taxonomy_multicheck_hierarchical': case 'taxonomy_multicheck_inline': $sanitized_value = $this->taxonomy(); break; case 'multicheck': case 'multicheck_inline': case 'file_list': case 'group': // no filtering $sanitized_value = $this->value; break; default: // Handle repeatable fields array // We'll fallback to 'sanitize_text_field' $sanitized_value = $this->_default_sanitization(); break; } return $this->_is_empty_array( $sanitized_value ) ? '' : $sanitized_value; } /** * Default sanitization method, sanitize_text_field. Checks if value is array. * * @since 2.2.4 * @return mixed Sanitized value. */ protected function _default_sanitization() { // Handle repeatable fields array. return is_array( $this->value ) ? array_map( 'sanitize_text_field', $this->value ) : sanitize_text_field( $this->value ); } /** * Sets the object terms to the object (if not options-page) and optionally returns the sanitized term values. * * @since 2.2.4 * @return mixed Blank value, or sanitized term values if "cmb2_return_taxonomy_values_{$cmb_id}" is true. */ public function taxonomy() { $sanitized_value = ''; if ( ! $this->field->args( 'taxonomy' ) ) { CMB2_Utils::log_if_debug( __METHOD__, __LINE__, "{$this->field->type()} {$this->field->_id( '', false )} is missing the 'taxonomy' parameter." ); } else { if ( in_array( $this->field->object_type, array( 'options-page', 'term' ), true ) ) { $return_values = true; } else { wp_set_object_terms( $this->field->object_id, $this->value, $this->field->args( 'taxonomy' ) ); $return_values = false; } $cmb_id = $this->field->cmb_id; /** * Filter whether 'taxonomy_*' fields should return their value when being sanitized. * * By default, these fields do not return a value as we do not want them stored to meta * (as they are stored as terms). This allows overriding that and is used by CMB2::get_sanitized_values(). * * The dynamic portion of the hook, $cmb_id, refers to the this field's CMB2 box id. * * @since 2.2.4 * * @param bool $return_values By default, this is only true for 'options-page' boxes. To enable: * `add_filter( "cmb2_return_taxonomy_values_{$cmb_id}", '__return_true' );` * @param CMB2_Sanitize $sanitizer This object. */ if ( apply_filters( "cmb2_return_taxonomy_values_{$cmb_id}", $return_values, $this ) ) { $sanitized_value = $this->_default_sanitization(); } } return $sanitized_value; } /** * Simple checkbox validation * * @since 1.0.1 * @return string|false 'on' or false */ public function checkbox() { return $this->value === 'on' ? 'on' : false; } /** * Validate url in a meta value. * * @since 1.0.1 * @return string Empty string or escaped url */ public function text_url() { $protocols = $this->field->args( 'protocols' ); $default = $this->field->get_default(); // for repeatable. if ( is_array( $this->value ) ) { foreach ( $this->value as $key => $val ) { $this->value[ $key ] = self::sanitize_and_secure_url( $val, $protocols, $default ); } } else { $this->value = self::sanitize_and_secure_url( $this->value, $protocols, $default ); } return $this->value; } public function colorpicker() { // for repeatable. if ( is_array( $this->value ) ) { $check = $this->value; $this->value = array(); foreach ( $check as $key => $val ) { if ( $val && '#' != $val ) { $this->value[ $key ] = esc_attr( $val ); } } } else { $this->value = ! $this->value || '#' == $this->value ? '' : esc_attr( $this->value ); } return $this->value; } /** * Validate email in a meta value * * @since 1.0.1 * @return string Empty string or sanitized email */ public function text_email() { // for repeatable. if ( is_array( $this->value ) ) { foreach ( $this->value as $key => $val ) { $val = trim( $val ); $this->value[ $key ] = is_email( $val ) ? $val : ''; } } else { $this->value = trim( $this->value ); $this->value = is_email( $this->value ) ? $this->value : ''; } return $this->value; } /** * Validate money in a meta value * * @since 1.0.1 * @return string Empty string or sanitized money value */ public function text_money() { if ( ! $this->value ) { return ''; } global $wp_locale; $search = array( $wp_locale->number_format['thousands_sep'], $wp_locale->number_format['decimal_point'] ); $replace = array( '', '.' ); // Strip slashes. Example: 2\'180.00. // See https://github.com/CMB2/CMB2/issues/1014. $this->value = wp_unslash( $this->value ); // for repeatable. if ( is_array( $this->value ) ) { foreach ( $this->value as $key => $val ) { if ( $val ) { $this->value[ $key ] = number_format_i18n( (float) str_ireplace( $search, $replace, $val ), 2 ); } } } else { $this->value = number_format_i18n( (float) str_ireplace( $search, $replace, $this->value ), 2 ); } return $this->value; } /** * Converts text date to timestamp * * @since 1.0.2 * @return string Timestring */ public function text_date_timestamp() { // date_create_from_format if there is a slash in the value. $this->value = wp_unslash( $this->value ); return is_array( $this->value ) ? array_map( array( $this->field, 'get_timestamp_from_value' ), $this->value ) : $this->field->get_timestamp_from_value( $this->value ); } /** * Datetime to timestamp * * @since 1.0.1 * * @param bool $repeat Whether or not to repeat. * @return string|array Timestring */ public function text_datetime_timestamp( $repeat = false ) { // date_create_from_format if there is a slash in the value. $this->value = wp_unslash( $this->value ); if ( $this->is_empty_value() ) { return ''; } $repeat_value = $this->_check_repeat( __FUNCTION__, $repeat ); if ( false !== $repeat_value ) { return $repeat_value; } // Account for timestamp values passed through REST API. if ( $this->is_valid_date_value() ) { $this->value = CMB2_Utils::make_valid_time_stamp( $this->value ); } elseif ( isset( $this->value['date'], $this->value['time'] ) ) { $this->value = $this->field->get_timestamp_from_value( $this->value['date'] . ' ' . $this->value['time'] ); } if ( $tz_offset = $this->field->field_timezone_offset() ) { $this->value += (int) $tz_offset; } return $this->value; } /** * Datetime to timestamp with timezone * * @since 1.0.1 * * @param bool $repeat Whether or not to repeat. * @return string Timestring */ public function text_datetime_timestamp_timezone( $repeat = false ) { static $utc_values = array(); if ( $this->is_empty_value() ) { return ''; } // date_create_from_format if there is a slash in the value. $this->value = wp_unslash( $this->value ); $utc_key = $this->field->_id( '', false ) . '_utc'; $repeat_value = $this->_check_repeat( __FUNCTION__, $repeat ); if ( false !== $repeat_value ) { if ( ! empty( $utc_values[ $utc_key ] ) ) { $this->_save_utc_value( $utc_key, $utc_values[ $utc_key ] ); unset( $utc_values[ $utc_key ] ); } return $repeat_value; } $tzstring = null; if ( is_array( $this->value ) && array_key_exists( 'timezone', $this->value ) ) { $tzstring = $this->value['timezone']; } if ( empty( $tzstring ) ) { $tzstring = CMB2_Utils::timezone_string(); } $offset = CMB2_Utils::timezone_offset( $tzstring ); if ( 'UTC' === substr( $tzstring, 0, 3 ) ) { $tzstring = timezone_name_from_abbr( '', $offset, 0 ); /** * The timezone_name_from_abbr() returns false if not found based on offset. * Since there are currently some invalid timezones in wp_timezone_dropdown(), * fallback to an offset of 0 (UTC+0) * https://core.trac.wordpress.org/ticket/29205 */ $tzstring = false !== $tzstring ? $tzstring : timezone_name_from_abbr( '', 0, 0 ); } $full_format = $this->field->args['date_format'] . ' ' . $this->field->args['time_format']; try { $datetime = null; if ( is_array( $this->value ) ) { $full_date = $this->value['date'] . ' ' . $this->value['time']; $datetime = date_create_from_format( $full_format, $full_date ); } elseif ( $this->is_valid_date_value() ) { $timestamp = CMB2_Utils::make_valid_time_stamp( $this->value ); if ( $timestamp ) { $datetime = new DateTime(); $datetime->setTimestamp( $timestamp ); } } if ( ! is_object( $datetime ) ) { $this->value = $utc_stamp = ''; } else { $datetime->setTimezone( new DateTimeZone( $tzstring ) ); $utc_stamp = date_timestamp_get( $datetime ) - $offset; $this->value = json_encode( $datetime ); } if ( $this->field->group ) { $this->value = array( 'supporting_field_value' => $utc_stamp, 'supporting_field_id' => $utc_key, 'value' => $this->value, ); } else { // Save the utc timestamp supporting field. if ( $repeat ) { $utc_values[ $utc_key ][] = $utc_stamp; } else { $this->_save_utc_value( $utc_key, $utc_stamp ); } } } catch ( Exception $e ) { $this->value = ''; CMB2_Utils::log_if_debug( __METHOD__, __LINE__, $e->getMessage() ); } return $this->value; } /** * Sanitize textareas and wysiwyg fields * * @since 1.0.1 * @return string Sanitized data */ public function textarea() { return is_array( $this->value ) ? array_map( 'wp_kses_post', $this->value ) : wp_kses_post( $this->value ); } /** * Sanitize code textareas * * @since 1.0.2 * * @param bool $repeat Whether or not to repeat. * @return string Sanitized data */ public function textarea_code( $repeat = false ) { $repeat_value = $this->_check_repeat( __FUNCTION__, $repeat ); if ( false !== $repeat_value ) { return $repeat_value; } return htmlspecialchars_decode( stripslashes( $this->value ), ENT_COMPAT ); } /** * Handles saving of attachment post ID and sanitizing file url * * @since 1.1.0 * @return string Sanitized url */ public function file() { $file_id_key = $this->field->_id( '', false ) . '_id'; if ( $this->field->group ) { // Return an array with url/id if saving a group field. $this->value = $this->_get_group_file_value_array( $file_id_key ); } else { $this->_save_file_id_value( $file_id_key ); $this->text_url(); } return $this->value; } /** * Gets the values for the `file` field type from the data being saved. * * @since 2.2.0 * * @param mixed $id_key ID key to use. * @return array */ public function _get_group_file_value_array( $id_key ) { $alldata = $this->field->group->data_to_save; $base_id = $this->field->group->_id( '', false ); $i = $this->field->group->index; // Check group $alldata data. $id_val = isset( $alldata[ $base_id ][ $i ][ $id_key ] ) ? absint( $alldata[ $base_id ][ $i ][ $id_key ] ) : ''; // We don't want to save 0 to the DB for file fields. if ( 0 === $id_val ) { $id_val = ''; } return array( 'value' => $this->text_url(), 'supporting_field_value' => $id_val, 'supporting_field_id' => $id_key, ); } /** * Peforms saving of `file` attachement's ID * * @since 1.1.0 * * @param mixed $file_id_key ID key to use. * @return mixed */ public function _save_file_id_value( $file_id_key ) { $id_field = $this->_new_supporting_field( $file_id_key ); // Check standard data_to_save data. $id_val = isset( $this->field->data_to_save[ $file_id_key ] ) ? $this->field->data_to_save[ $file_id_key ] : null; // If there is no ID saved yet, try to get it from the url. if ( $this->value && ! $id_val ) { $id_val = CMB2_Utils::image_id_from_url( $this->value ); // If there is an ID but user emptied the input value, remove the ID. } elseif ( ! $this->value && $id_val ) { $id_val = null; } return $id_field->save_field( $id_val ); } /** * Peforms saving of `text_datetime_timestamp_timezone` utc timestamp * * @since 2.2.0 * * @param mixed $utc_key UTC key. * @param mixed $utc_stamp UTC timestamp. * @return mixed */ public function _save_utc_value( $utc_key, $utc_stamp ) { return $this->_new_supporting_field( $utc_key )->save_field( $utc_stamp ); } /** * Returns a new, supporting, CMB2_Field object based on a new field id. * * @since 2.2.0 * * @param mixed $new_field_id New field ID. * @return CMB2_Field */ public function _new_supporting_field( $new_field_id ) { return $this->field->get_field_clone( array( 'id' => $new_field_id, 'sanitization_cb' => false, ) ); } /** * If repeating, loop through and re-apply sanitization method * * @since 1.1.0 * @param string $method Class method. * @param bool $repeat Whether repeating or not. * @return mixed Sanitized value */ public function _check_repeat( $method, $repeat ) { if ( $repeat || ! $this->field->args( 'repeatable' ) ) { return false; } $values_array = $this->value; $new_value = array(); foreach ( $values_array as $iterator => $this->value ) { if ( $this->value ) { $val = $this->$method( true ); if ( ! empty( $val ) ) { $new_value[] = $val; } } } $this->value = $new_value; return empty( $this->value ) ? null : $this->value; } /** * Determine if passed value is an empty array * * @since 2.0.6 * @param mixed $to_check Value to check. * @return boolean Whether value is an array that's empty */ public function _is_empty_array( $to_check ) { if ( is_array( $to_check ) ) { $cleaned_up = array_filter( $to_check ); return empty( $cleaned_up ); } return false; } /** * Sanitize a URL. Make the default scheme HTTPS. * * @since 2.10.0 * @param string $value Unescaped URL. * @param array $protocols Allowed protocols for URL. * @param string $default Default value if no URL found. * @return string escaped URL. */ public static function sanitize_and_secure_url( $url, $protocols = null, $default = null ) { if ( empty( $url ) ) { return $default; } $orig_scheme = parse_url( $url, PHP_URL_SCHEME ); $url = esc_url_raw( $url, $protocols ); // If original url has no scheme... if ( null === $orig_scheme ) { // Let's make sure the added scheme is https. $url = set_url_scheme( $url, 'https' ); } return $url; } /** * Check if the current field's value is empty. * * @since 2.9.1 * * @return boolean Wether value is empty. */ public function is_empty_value() { if ( empty( $this->value ) ) { return true; } if ( is_array( $this->value ) ) { $test = array_filter( $this->value ); if ( empty( $test ) ) { return true; } } return false; } /** * Check if the current field's value is a valid date value. * * @since 2.9.1 * * @return boolean Wether value is a valid date value. */ public function is_valid_date_value() { return is_scalar( $this->value ) && CMB2_Utils::is_valid_date( $this->value ); } } cmb2/cmb2/includes/CMB2_Base.php 0000644 00000036134 15151523433 0012157 0 ustar 00 <?php /** * CMB2 Base - Base object functionality. * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io * * @property-read $args The objects array of properties/arguments. * @property-read $meta_box The objects array of properties/arguments. * @property-read $properties The objects array of properties/arguments. * @property-read $cmb_id Current CMB2 instance ID * @property-read $object_id Object ID * @property-read $object_type Type of object being handled. (e.g., post, user, comment, or term) */ abstract class CMB2_Base { /** * Current CMB2 instance ID * * @var string * @since 2.2.3 */ protected $cmb_id = ''; /** * The object properties name. * * @var string * @since 2.2.3 */ protected $properties_name = 'meta_box'; /** * Object ID * * @var mixed * @since 2.2.3 */ protected $object_id = 0; /** * Type of object being handled. (e.g., post, user, comment, or term) * * @var string * @since 2.2.3 */ protected $object_type = ''; /** * Array of key => value data for saving. Likely $_POST data. * * @var array * @since 2.2.3 */ public $data_to_save = array(); /** * Array of field param callback results * * @var array * @since 2.0.0 */ protected $callback_results = array(); /** * The deprecated_param method deprecated param message signature. */ const DEPRECATED_PARAM = 1; /** * The deprecated_param method deprecated callback param message signature. */ const DEPRECATED_CB_PARAM = 2; /** * Get started * * @since 2.2.3 * @param array $args Object properties array. */ public function __construct( $args = array() ) { if ( ! empty( $args ) ) { foreach ( array( 'cmb_id', 'properties_name', 'object_id', 'object_type', 'data_to_save', ) as $object_prop ) { if ( isset( $args[ $object_prop ] ) ) { $this->{$object_prop} = $args[ $object_prop ]; } } } } /** * Returns the object ID * * @since 2.2.3 * @param integer $object_id Object ID. * @return integer Object ID */ public function object_id( $object_id = 0 ) { if ( $object_id ) { $this->object_id = $object_id; } return $this->object_id; } /** * Returns the object type * * @since 2.2.3 * @param string $object_type Object Type. * @return string Object type */ public function object_type( $object_type = '' ) { if ( $object_type ) { $this->object_type = $object_type; } return $this->object_type; } /** * Get the object type for the current page, based on the $pagenow global. * * @since 2.2.2 * @return string Page object type name. */ public function current_object_type() { global $pagenow; $type = 'post'; if ( in_array( $pagenow, array( 'user-edit.php', 'profile.php', 'user-new.php' ), true ) ) { $type = 'user'; } if ( in_array( $pagenow, array( 'edit-comments.php', 'comment.php' ), true ) ) { $type = 'comment'; } if ( in_array( $pagenow, array( 'edit-tags.php', 'term.php' ), true ) ) { $type = 'term'; } return $type; } /** * Set object property. * * @since 2.2.2 * @param string $property Metabox config property to retrieve. * @param mixed $value Value to set if no value found. * @return mixed Metabox config property value or false. */ public function set_prop( $property, $value ) { $this->{$this->properties_name}[ $property ] = $value; return $this->prop( $property ); } /** * Get object property and optionally set a fallback * * @since 2.0.0 * @param string $property Metabox config property to retrieve. * @param mixed $fallback Fallback value to set if no value found. * @return mixed Metabox config property value or false */ public function prop( $property, $fallback = null ) { if ( array_key_exists( $property, $this->{$this->properties_name} ) ) { return $this->{$this->properties_name}[ $property ]; } elseif ( $fallback ) { return $this->{$this->properties_name}[ $property ] = $fallback; } } /** * Get default field arguments specific to this CMB2 object. * * @since 2.2.0 * @param array $field_args Metabox field config array. * @param CMB2_Field $field_group (optional) CMB2_Field object (group parent). * @return array Array of field arguments. */ protected function get_default_args( $field_args, $field_group = null ) { if ( $field_group ) { $args = array( 'field_args' => $field_args, 'group_field' => $field_group, ); } else { $args = array( 'field_args' => $field_args, 'object_type' => $this->object_type(), 'object_id' => $this->object_id(), 'cmb_id' => $this->cmb_id, ); } return $args; } /** * Get a new field object specific to this CMB2 object. * * @since 2.2.0 * @param array $field_args Metabox field config array. * @param CMB2_Field $field_group (optional) CMB2_Field object (group parent). * @return CMB2_Field CMB2_Field object */ protected function get_new_field( $field_args, $field_group = null ) { return new CMB2_Field( $this->get_default_args( $field_args, $field_group ) ); } /** * Determine whether this cmb object should show, based on the 'show_on_cb' callback. * * @since 2.0.9 * * @return bool Whether this cmb should be shown. */ public function should_show() { // Default to showing this cmb $show = true; // Use the callback to determine showing the cmb, if it exists. if ( is_callable( $this->prop( 'show_on_cb' ) ) ) { $show = (bool) call_user_func( $this->prop( 'show_on_cb' ), $this ); } return $show; } /** * Displays the results of the param callbacks. * * @since 2.0.0 * @param string $param Field parameter. */ public function peform_param_callback( $param ) { echo $this->get_param_callback_result( $param ); } /** * Store results of the param callbacks for continual access * * @since 2.0.0 * @param string $param Field parameter. * @return mixed Results of param/param callback */ public function get_param_callback_result( $param ) { // If we've already retrieved this param's value. if ( array_key_exists( $param, $this->callback_results ) ) { // Send it back. return $this->callback_results[ $param ]; } // Check if parameter has registered a callback. if ( $cb = $this->maybe_callback( $param ) ) { // Ok, callback is good, let's run it and store the result. ob_start(); $returned = $this->do_callback( $cb ); // Grab the result from the output buffer and store it. $echoed = ob_get_clean(); // This checks if the user returned or echoed their callback. // Defaults to using the echoed value. $this->callback_results[ $param ] = $echoed ? $echoed : $returned; } else { // Otherwise just get whatever is there. $this->callback_results[ $param ] = isset( $this->{$this->properties_name}[ $param ] ) ? $this->{$this->properties_name}[ $param ] : false; } return $this->callback_results[ $param ]; } /** * Unset the cached results of the param callback. * * @since 2.2.6 * @param string $param Field parameter. * @return CMB2_Base */ public function unset_param_callback_cache( $param ) { if ( isset( $this->callback_results[ $param ] ) ) { unset( $this->callback_results[ $param ] ); } return $this; } /** * Handles the parameter callbacks, and passes this object as parameter. * * @since 2.2.3 * @param callable $cb The callback method/function/closure. * @param mixed $additional_params Any additoinal parameters which should be passed to the callback. * @return mixed Return of the callback function. */ protected function do_callback( $cb, $additional_params = null ) { return call_user_func( $cb, $this->{$this->properties_name}, $this, $additional_params ); } /** * Checks if field has a callback value * * @since 1.0.1 * @param string $cb Callback string. * @return mixed NULL, false for NO validation, or $cb string if it exists. */ public function maybe_callback( $cb ) { $args = $this->{$this->properties_name}; if ( ! isset( $args[ $cb ] ) ) { return null; } // Check if requesting explicitly false. $cb = false !== $args[ $cb ] && 'false' !== $args[ $cb ] ? $args[ $cb ] : false; // If requesting NO validation, return false. if ( ! $cb ) { return false; } if ( is_callable( $cb ) ) { return $cb; } return null; } /** * Checks if this object has parameter corresponding to the given filter * which is callable. If so, it registers the callback, and if not, * converts the maybe-modified $val to a boolean for return. * * The registered handlers will have a parameter name which matches the filter, except: * - The 'cmb2_api' prefix will be removed * - A '_cb' suffix will be added (to stay inline with other '*_cb' parameters). * * @since 2.2.3 * * @param string $hook_name The hook name. * @param bool $val The default value. * @param string $hook_function The hook function. Default: 'add_filter'. * * @return null|bool Null if hook is registered, or bool for value. */ public function maybe_hook_parameter( $hook_name, $val = null, $hook_function = 'add_filter' ) { // Remove filter prefix, add param suffix. $parameter = substr( $hook_name, strlen( 'cmb2_api_' ) ) . '_cb'; return self::maybe_hook( $this->prop( $parameter, $val ), $hook_name, $hook_function ); } /** * Checks if given value is callable, and registers the callback. * If is non-callable, converts the $val to a boolean for return. * * @since 2.2.3 * * @param bool $val The default value. * @param string $hook_name The hook name. * @param string $hook_function The hook function. * * @return null|bool Null if hook is registered, or bool for value. */ public static function maybe_hook( $val, $hook_name, $hook_function ) { if ( is_callable( $val ) ) { call_user_func( $hook_function, $hook_name, $val, 10, 2 ); return null; } // Cast to bool. return ! ! $val; } /** * Mark a param as deprecated and inform when it has been used. * * There is a default WordPress hook deprecated_argument_run that will be called * that can be used to get the backtrace up to what file and function used the * deprecated argument. * * The current behavior is to trigger a user error if WP_DEBUG is true. * * @since 2.2.3 * * @param string $function The function that was called. * @param string $version The version of CMB2 that deprecated the argument used. * @param string $message Optional. A message regarding the change, or numeric * key to generate message from additional arguments. * Default null. */ protected function deprecated_param( $function, $version, $message = null ) { $args = func_get_args(); if ( is_numeric( $message ) ) { switch ( $message ) { case self::DEPRECATED_PARAM: $message = sprintf( __( 'The "%1$s" field parameter has been deprecated in favor of the "%2$s" parameter.', 'cmb2' ), $args[3], $args[4] ); break; case self::DEPRECATED_CB_PARAM: $message = sprintf( __( 'Using the "%1$s" field parameter as a callback has been deprecated in favor of the "%2$s" parameter.', 'cmb2' ), $args[3], $args[4] ); break; default: $message = null; break; } } /** * Fires when a deprecated argument is called. This is a WP core action. * * @since 2.2.3 * * @param string $function The function that was called. * @param string $message A message regarding the change. * @param string $version The version of CMB2 that deprecated the argument used. */ do_action( 'deprecated_argument_run', $function, $message, $version ); /** * Filters whether to trigger an error for deprecated arguments. This is a WP core filter. * * @since 2.2.3 * * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true. */ if ( defined( 'WP_DEBUG' ) && WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) { if ( function_exists( '__' ) ) { if ( ! is_null( $message ) ) { trigger_error( sprintf( __( '%1$s was called with a parameter that is <strong>deprecated</strong> since version %2$s! %3$s', 'cmb2' ), $function, $version, $message ) ); } else { trigger_error( sprintf( __( '%1$s was called with a parameter that is <strong>deprecated</strong> since version %2$s with no alternative available.', 'cmb2' ), $function, $version ) ); } } else { if ( ! is_null( $message ) ) { trigger_error( sprintf( '%1$s was called with a parameter that is <strong>deprecated</strong> since version %2$s! %3$s', $function, $version, $message ) ); } else { trigger_error( sprintf( '%1$s was called with a parameter that is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) ); } } } } /** * Magic getter for our object. * * @param string $field Requested property. * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __get( $field ) { switch ( $field ) { case 'args': case 'meta_box': if ( $field === $this->properties_name ) { return $this->{$this->properties_name}; } case 'properties': return $this->{$this->properties_name}; case 'cmb_id': case 'object_id': case 'object_type': return $this->{$field}; default: throw new Exception( sprintf( esc_html__( 'Invalid %1$s property: %2$s', 'cmb2' ), __CLASS__, $field ) ); } } /** * Allows overloading the object with methods... Whooaaa oooh it's magic, y'knoooow. * * @since 1.0.0 * @throws Exception Invalid method exception. * * @param string $method Non-existent method. * @param array $args All arguments passed to the method. * @return mixed */ public function __call( $method, $args ) { $object_class = strtolower( get_class( $this ) ); if ( ! has_filter( "{$object_class}_inherit_{$method}" ) ) { throw new Exception( sprintf( esc_html__( 'Invalid %1$s method: %2$s', 'cmb2' ), get_class( $this ), $method ) ); } array_unshift( $args, $this ); /** * Allows overloading the object (CMB2 or CMB2_Field) with additional capabilities * by registering hook callbacks. * * The first dynamic portion of the hook name, $object_class, refers to the object class, * either cmb2 or cmb2_field. * * The second dynamic portion of the hook name, $method, is the non-existent method being * called on the object. To avoid possible future methods encroaching on your hooks, * use a unique method (aka, $cmb->prefix_my_method()). * * When registering your callback, you will need to ensure that you register the correct * number of `$accepted_args`, accounting for this object instance being the first argument. * * @param array $args The arguments to be passed to the hook. * The first argument will always be this object instance. */ return apply_filters_ref_array( "{$object_class}_inherit_{$method}", $args ); } } cmb2/cmb2/includes/CMB2_Options_Hookup.php 0000644 00000026011 15151523433 0014256 0 ustar 00 <?php /** * Handles hooking CMB2 forms/metaboxes into the post/attachement/user screens * and handles hooking in and saving those fields. * * @since 2.0.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Options_Hookup extends CMB2_Hookup { /** * The object type we are performing the hookup for * * @var string * @since 2.0.9 */ protected $object_type = 'options-page'; /** * Options page key. * * @var string * @since 2.2.5 */ protected $option_key = ''; /** * Constructor * * @since 2.0.0 * @param CMB2 $cmb The CMB2 object to hookup. * @param string $option_key Option key to use. */ public function __construct( CMB2 $cmb, $option_key ) { $this->cmb = $cmb; $this->option_key = $option_key; } public function hooks() { if ( empty( $this->option_key ) ) { return; } if ( ! $this->cmb->prop( 'autoload', true ) ) { // Disable option autoload if requested. add_filter( "cmb2_should_autoload_{$this->option_key}", '__return_false' ); } /** * For WP < 4.7. Ensure the register_setting function exists. */ if ( ! CMB2_Utils::wp_at_least( '4.7' ) && ! function_exists( 'register_setting' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } // Register setting to cmb2 group. register_setting( 'cmb2', $this->option_key ); // Handle saving the data. add_action( 'admin_post_' . $this->option_key, array( $this, 'save_options' ) ); // Optionally network_admin_menu. $hook = $this->cmb->prop( 'admin_menu_hook' ); // Hook in to add our menu. add_action( $hook, array( $this, 'options_page_menu_hooks' ), $this->get_priority() ); // If in the network admin, need to use get/update_site_option. if ( 'network_admin_menu' === $hook ) { // Override CMB's getter. add_filter( "cmb2_override_option_get_{$this->option_key}", array( $this, 'network_get_override' ), 10, 2 ); // Override CMB's setter. add_filter( "cmb2_override_option_save_{$this->option_key}", array( $this, 'network_update_override' ), 10, 2 ); } } /** * Hook up our admin menu item and admin page. * * @since 2.2.5 * * @return void */ public function options_page_menu_hooks() { $parent_slug = $this->cmb->prop( 'parent_slug' ); $title = $this->cmb->prop( 'title' ); $menu_title = $this->cmb->prop( 'menu_title', $title ); $capability = $this->cmb->prop( 'capability' ); $callback = array( $this, 'options_page_output' ); if ( $parent_slug ) { $page_hook = add_submenu_page( $parent_slug, $title, $menu_title, $capability, $this->option_key, $callback ); } else { $page_hook = add_menu_page( $title, $menu_title, $capability, $this->option_key, $callback, $this->cmb->prop( 'icon_url' ), $this->cmb->prop( 'position' ) ); } if ( $this->cmb->prop( 'cmb_styles' ) ) { // Include CMB CSS in the head to avoid FOUC. add_action( "admin_print_styles-{$page_hook}", array( 'CMB2_Hookup', 'enqueue_cmb_css' ) ); } $this->maybe_register_message(); } /** * If there is a message callback, let it determine how to register the message, * else add a settings message if on this settings page. * * @since 2.2.6 * * @return void */ public function maybe_register_message() { $is_options_page = self::is_page( $this->option_key ); $should_notify = ! $this->cmb->prop( 'disable_settings_errors' ) && isset( $_GET['settings-updated'] ) && $is_options_page; $is_updated = $should_notify && 'true' === $_GET['settings-updated']; $setting = "{$this->option_key}-notices"; $code = ''; $message = __( 'Nothing to update.', 'cmb2' ); $type = 'notice-warning'; if ( $is_updated ) { $message = __( 'Settings updated.', 'cmb2' ); $type = 'updated'; } // Check if parameter has registered a callback. if ( $cb = $this->cmb->maybe_callback( 'message_cb' ) ) { /** * The 'message_cb' callback will receive the following parameters. * Unless there are other reasons for notifications, the callback should only * `add_settings_error()` if `$args['should_notify']` is truthy. * * @param CMB2 $cmb The CMB2 object. * @param array $args { * An array of message arguments * * @type bool $is_options_page Whether current page is this options page. * @type bool $should_notify Whether options were saved and we should be notified. * @type bool $is_updated Whether options were updated with save (or stayed the same). * @type string $setting For add_settings_error(), Slug title of the setting to which * this error applies. * @type string $code For add_settings_error(), Slug-name to identify the error. * Used as part of 'id' attribute in HTML output. * @type string $message For add_settings_error(), The formatted message text to display * to the user (will be shown inside styled `<div>` and `<p>` tags). * Will be 'Settings updated.' if $is_updated is true, else 'Nothing to update.' * @type string $type For add_settings_error(), Message type, controls HTML class. * Accepts 'error', 'updated', '', 'notice-warning', etc. * Will be 'updated' if $is_updated is true, else 'notice-warning'. * } */ $args = compact( 'is_options_page', 'should_notify', 'is_updated', 'setting', 'code', 'message', 'type' ); $this->cmb->do_callback( $cb, $args ); } elseif ( $should_notify ) { add_settings_error( $setting, $code, $message, $type ); } } /** * Display options-page output. To override, set 'display_cb' box property. * * @since 2.2.5 */ public function options_page_output() { $this->maybe_output_settings_notices(); $callback = $this->cmb->prop( 'display_cb' ); if ( is_callable( $callback ) ) { return call_user_func( $callback, $this ); } ?> <div class="wrap cmb2-options-page option-<?php echo esc_attr( sanitize_html_class( $this->option_key ) ); ?>"> <?php if ( $this->cmb->prop( 'title' ) ) : ?> <h2><?php echo wp_kses_post( $this->cmb->prop( 'title' ) ); ?></h2> <?php endif; ?> <?php $this->options_page_tab_nav_output(); ?> <form class="cmb-form" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="POST" id="<?php echo $this->cmb->cmb_id; ?>" enctype="multipart/form-data" encoding="multipart/form-data"> <input type="hidden" name="action" value="<?php echo esc_attr( $this->option_key ); ?>"> <?php $this->options_page_metabox(); ?> <?php submit_button( esc_attr( $this->cmb->prop( 'save_button' ) ), 'primary', 'submit-cmb' ); ?> </form> </div> <?php } /** * Display options-page Tab Navigation output. * * @since 2.9.0 */ public function options_page_tab_nav_output() { $tabs = $this->get_tab_group_tabs(); if ( empty( $tabs ) ) { return; } ?> <h2 class="nav-tab-wrapper"> <?php foreach ( $tabs as $option_key => $tab_title ) : ?> <a class="nav-tab<?php if ( self::is_page( $option_key ) ) : ?> nav-tab-active<?php endif; ?>" href="<?php menu_page_url( $option_key ); ?>"><?php echo wp_kses_post( $tab_title ); ?></a> <?php endforeach; ?> </h2> <?php } /** * Outputs the settings notices if a) not a sub-page of 'options-general.php' * (because settings_errors() already called in wp-admin/options-head.php), * and b) the 'disable_settings_errors' prop is not set or truthy. * * @since 2.2.5 * @return void */ public function maybe_output_settings_notices() { global $parent_file; // The settings sub-pages will already have settings_errors() called in wp-admin/options-head.php. if ( 'options-general.php' !== $parent_file ) { settings_errors( "{$this->option_key}-notices" ); } } /** * Gets navigation tabs array for CMB2 options pages which share the * same tab_group property. * * @since 2.4.0 * @return array Array of tab information ($option_key => $tab_title) */ public function get_tab_group_tabs() { $tab_group = $this->cmb->prop( 'tab_group' ); $tabs = array(); if ( $tab_group ) { $boxes = CMB2_Boxes::get_by( 'tab_group', $tab_group ); foreach ( $boxes as $cmb_id => $cmb ) { $option_key = $cmb->options_page_keys(); // Must have an option key, must be an options page box. if ( ! isset( $option_key[0] ) || 'options-page' !== $cmb->mb_object_type() ) { continue; } $tabs[ $option_key[0] ] = $cmb->prop( 'tab_title', $cmb->prop( 'title' ) ); } } return apply_filters( 'cmb2_tab_group_tabs', $tabs, $tab_group ); } /** * Display metaboxes for an options-page object. * * @since 2.2.5 */ public function options_page_metabox() { $this->show_form_for_type( 'options-page' ); } /** * Save data from options page, then redirects back. * * @since 2.2.5 * @return void */ public function save_options() { $url = wp_get_referer(); if ( ! $url ) { $url = admin_url(); } if ( $this->can_save( 'options-page' ) // check params. && isset( $_POST['submit-cmb'], $_POST['action'] ) && $this->option_key === $_POST['action'] ) { $updated = $this->cmb ->save_fields( $this->option_key, $this->cmb->object_type(), $_POST ) ->was_updated(); // Will be false if no values were changed/updated. $url = add_query_arg( 'settings-updated', $updated ? 'true' : 'false', $url ); } wp_safe_redirect( esc_url_raw( $url ), 303 /* WP_Http::SEE_OTHER */ ); exit; } /** * Replaces get_option with get_site_option. * * @since 2.2.5 * * @param mixed $test Not used. * @param mixed $default Default value to use. * @return mixed Value set for the network option. */ public function network_get_override( $test, $default = false ) { return get_site_option( $this->option_key, $default ); } /** * Replaces update_option with update_site_option. * * @since 2.2.5 * * @param mixed $test Not used. * @param mixed $option_value Value to use. * @return bool Success/Failure */ public function network_update_override( $test, $option_value ) { return update_site_option( $this->option_key, $option_value ); } /** * Determines if given page slug matches the 'page' GET query variable. * * @since 2.4.0 * * @param string $page Page slug. * @return boolean */ public static function is_page( $page ) { return isset( $_GET['page'] ) && $page === $_GET['page']; } /** * Magic getter for our object. * * @param string $field Property to retrieve. * * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __get( $field ) { switch ( $field ) { case 'object_type': case 'option_key': case 'cmb': return $this->{$field}; default: throw new Exception( sprintf( esc_html__( 'Invalid %1$s property: %2$s', 'cmb2' ), __CLASS__, $field ) ); } } } cmb2/cmb2/includes/index.php 0000644 00000000033 15151523433 0011636 0 ustar 00 <?php // Silence is golden cmb2/cmb2/includes/CMB2_Show_Filters.php 0000644 00000010572 15151523433 0013713 0 ustar 00 <?php /** * Show On Filters * Use the 'cmb2_show_on' filter to further refine the conditions * under which a metabox is displayed. * Below you can limit it by ID and page template * * All methods in this class are automatically filtered * * @since 1.0.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Show_Filters { /** * Get Show_on key. backwards compatible w/ 'key' indexes * * @since 2.0.0 * * @param array $meta_box_args Metabox config array. * * @return mixed show_on key or false */ private static function get_show_on_key( $meta_box_args ) { $show_on = isset( $meta_box_args['show_on'] ) ? (array) $meta_box_args['show_on'] : false; if ( $show_on && is_array( $show_on ) ) { if ( array_key_exists( 'key', $show_on ) ) { return $show_on['key']; } $keys = array_keys( $show_on ); return $keys[0]; } return false; } /** * Get Show_on value. backwards compatible w/ 'value' indexes * * @since 2.0.0 * * @param array $meta_box_args Metabox config array. * * @return mixed show_on value or false */ private static function get_show_on_value( $meta_box_args ) { $show_on = isset( $meta_box_args['show_on'] ) ? (array) $meta_box_args['show_on'] : false; if ( $show_on && is_array( $show_on ) ) { if ( array_key_exists( 'value', $show_on ) ) { return $show_on['value']; } $keys = array_keys( $show_on ); return $show_on[ $keys[0] ]; } return array(); } /** * Add metaboxes for an specific ID * * @since 1.0.0 * @param bool $display To display or not. * @param array $meta_box_args Metabox config array. * @param CMB2 $cmb The CMB2 instance. * @return bool Whether to display this metabox on the current page. */ public static function check_id( $display, $meta_box_args, $cmb ) { $key = self::get_show_on_key( $meta_box_args ); if ( ! $key || 'id' !== $key ) { return $display; } $object_id = is_admin() ? $cmb->object_id() : get_the_ID(); if ( ! $object_id ) { return false; } // If current page id is in the included array, display the metabox. return in_array( $object_id, (array) self::get_show_on_value( $meta_box_args ) ); } /** * Add metaboxes for an specific Page Template * * @since 1.0.0 * @param bool $display To display or not. * @param array $meta_box_args Metabox config array. * @param CMB2 $cmb CMB2 object. * @return bool Whether to display this metabox on the current page. */ public static function check_page_template( $display, $meta_box_args, $cmb ) { $key = self::get_show_on_key( $meta_box_args ); if ( ! $key || 'page-template' !== $key ) { return $display; } $object_id = $cmb->object_id(); if ( ! $object_id || 'post' !== $cmb->object_type() ) { return false; } // Get current template. $current_template = get_post_meta( $object_id, '_wp_page_template', true ); // See if there's a match. if ( $current_template && in_array( $current_template, (array) self::get_show_on_value( $meta_box_args ) ) ) { return true; } return false; } /** * Only show options-page metaboxes on their options page (but only enforce on the admin side) * * @since 1.0.0 * @param bool $display To display or not. * @param array $meta_box_args Metabox config array. * @return bool Whether to display this metabox on the current page. */ public static function check_admin_page( $display, $meta_box_args ) { $key = self::get_show_on_key( $meta_box_args ); // check if this is a 'options-page' metabox. if ( ! $key || 'options-page' !== $key ) { return $display; } // Enforce 'show_on' filter in the admin. if ( is_admin() ) { // If there is no 'page' query var, our filter isn't applicable. if ( ! isset( $_GET['page'] ) ) { return $display; } $show_on = self::get_show_on_value( $meta_box_args ); if ( empty( $show_on ) ) { return false; } if ( is_array( $show_on ) ) { foreach ( $show_on as $page ) { if ( $_GET['page'] == $page ) { return true; } } } else { if ( $_GET['page'] == $show_on ) { return true; } } return false; } // Allow options-page metaboxes to be displayed anywhere on the front-end. return true; } } cmb2/cmb2/includes/CMB2_Hookup_Field.php 0000644 00000013400 15151523433 0013644 0 ustar 00 <?php /** * CMB2 Hookup Field * * Adds necessary hooks for certain field types. * * @since 2.11.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Hookup_Field { /** * Field id. * * @var string * @since 2.11.0 */ protected $field_id; /** * CMB2 object id. * * @var string * @since 2.11.0 */ protected $cmb_id; /** * The object type we are performing the hookup for * * @var string * @since 2.11.0 */ protected $object_type = 'post'; /** * Initialize all hooks for the given field. * * @since 2.11.0 * @param array $field The field arguments array. * @param CMB2 $cmb The CMB2 object. * @return array The field arguments array. */ public static function init( $field, CMB2 $cmb ) { switch ( $field['type'] ) { case 'file': case 'file_list': // Initiate attachment JS hooks. add_filter( 'wp_prepare_attachment_for_js', array( 'CMB2_Type_File_Base', 'prepare_image_sizes_for_js' ), 10, 3 ); break; case 'oembed': // Initiate oembed Ajax hooks. cmb2_ajax(); break; case 'group': if ( empty( $field['render_row_cb'] ) ) { $field['render_row_cb'] = array( $cmb, 'render_group_callback' ); } break; case 'colorpicker': // https://github.com/JayWood/CMB2_RGBa_Picker // Dequeue the rgba_colorpicker custom field script if it is used, // since we now enqueue our own more current version. add_action( 'admin_enqueue_scripts', array( 'CMB2_Type_Colorpicker', 'dequeue_rgba_colorpicker_script' ), 99 ); break; case 'text_datetime_timestamp_timezone': foreach ( $cmb->box_types() as $object_type ) { if ( ! $cmb->is_supported_core_object_type( $object_type ) ) { // Ignore post-types... continue; } if ( empty( $field['field_hookup_instance'][ $object_type ] ) ) { $instance = new self( $field, $object_type, $cmb ); $method = 'options-page' === $object_type ? 'text_datetime_timestamp_timezone_option_back_compat' : 'text_datetime_timestamp_timezone_back_compat'; $field['field_hookup_instance'][ $object_type ] = array( $instance, $method ); } if ( false === $field['field_hookup_instance'][ $object_type ] ) { // If set to false, no need to filter. // This can be set if you have updated your use of the field type value to // assume the JSON value. continue; } if ( 'options-page' === $object_type ) { $option_name = $cmb->object_id(); add_filter( "pre_option_{$option_name}", $field['field_hookup_instance'][ $object_type ], 10, 3 ); continue; } add_filter( "get_{$object_type}_metadata", $field['field_hookup_instance'][ $object_type ], 10, 5 ); } break; } return $field; } /** * Constructor * * @since 2.11.0 * @param CMB2 $cmb The CMB2 object to hookup. */ public function __construct( $field, $object_type, CMB2 $cmb ) { $this->field_id = $field['id']; $this->object_type = $object_type; $this->cmb_id = $cmb->cmb_id; } /** * Adds a back-compat shim for text_datetime_timestamp_timezone field type values. * * Handles old serialized DateTime values, as well as the new JSON formatted values. * * @since 2.11.0 * * @param mixed $value The value of the metadata. * @param int $object_id ID of the object metadata is for. * @param string $meta_key Meta key. * @param bool $single Whether to return a single value. * @param string $meta_type Type of object metadata is for. * @return mixed Maybe reserialized value. */ public function text_datetime_timestamp_timezone_back_compat( $value, $object_id, $meta_key, $single, $meta_type ) { if ( $meta_key === $this->field_id ) { remove_filter( "get_{$meta_type}_metadata", [ $this, __FUNCTION__ ], 10, 5 ); $value = get_metadata( $meta_type, $object_id, $meta_key, $single ); add_filter( "get_{$meta_type}_metadata", [ $this, __FUNCTION__ ], 10, 5 ); $value = $this->reserialize_safe_value( $value ); } return $value; } /** * Adds a back-compat shim for text_datetime_timestamp_timezone field type values on options pages. * * Handles old serialized DateTime values, as well as the new JSON formatted values. * * @since 2.11.0 * * @param mixed $value The value of the option. * @param string $option Option name. * @param mixed $default_value Default value. * @return mixed The updated value. */ public function text_datetime_timestamp_timezone_option_back_compat( $value, $option, $default_value ) { remove_filter( "pre_option_{$option}", [ $this, __FUNCTION__ ], 10, 3 ); $value = get_option( $option, $default_value ); add_filter( "pre_option_{$option}", [ $this, __FUNCTION__ ], 10, 3 ); if ( ! empty( $value ) && is_array( $value ) ) { // Loop fields and update values for all text_datetime_timestamp_timezone fields. foreach ( CMB2_Boxes::get( $this->cmb_id )->prop( 'fields' ) as $field ) { if ( 'text_datetime_timestamp_timezone' === $field['type'] && ! empty( $value[ $field['id'] ] ) ) { $value[ $field['id'] ] = $this->reserialize_safe_value( $value[ $field['id'] ] ); } } } return $value; } /** * Reserialize a value to a safe serialized DateTime value. * * @since 2.11.0 * * @param mixed $value The value to check. * @return mixed The value, possibly reserialized. */ protected function reserialize_safe_value( $value ) { if ( is_array( $value ) ) { return array_map( [ $this, 'reserialize_safe_value' ], $value ); } $updated_val = CMB2_Utils::get_datetime_from_value( $value ); $value = $updated_val ? serialize( $updated_val ) : ''; return $value; } } cmb2/cmb2/includes/CMB2_Options.php 0000644 00000014060 15151523433 0012732 0 ustar 00 <?php /** * CMB2 Utility classes for handling multi-dimensional array data for options * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ /** * Retrieves an instance of CMB2_Option based on the option key * * @package CMB2 * @author CMB2 team */ class CMB2_Options { /** * Array of all CMB2_Option instances * * @var array * @since 1.0.0 */ protected static $option_sets = array(); public static function get( $option_key ) { if ( empty( self::$option_sets ) || empty( self::$option_sets[ $option_key ] ) ) { self::$option_sets[ $option_key ] = new CMB2_Option( $option_key ); } return self::$option_sets[ $option_key ]; } } /** * Handles getting/setting of values to an option array * for a specific option key * * @package CMB2 * @author CMB2 team */ class CMB2_Option { /** * Options array * * @var array */ protected $options = array(); /** * Current option key * * @var string */ protected $key = ''; /** * Initiate option object * * @param string $option_key Option key where data will be saved. * Leave empty for temporary data store. * @since 2.0.0 */ public function __construct( $option_key = '' ) { $this->key = ! empty( $option_key ) ? $option_key : ''; } /** * Delete the option from the db * * @since 2.0.0 * @return mixed Delete success or failure */ public function delete_option() { $deleted = $this->key ? delete_option( $this->key ) : true; $this->options = $deleted ? array() : $this->options; return $this->options; } /** * Removes an option from an option array * * @since 1.0.1 * @param string $field_id Option array field key. * @param bool $resave Whether or not to resave. * @return array Modified options */ public function remove( $field_id, $resave = false ) { $this->get_options(); if ( isset( $this->options[ $field_id ] ) ) { unset( $this->options[ $field_id ] ); } if ( $resave ) { $this->set(); } return $this->options; } /** * Retrieves an option from an option array * * @since 1.0.1 * @param string $field_id Option array field key. * @param mixed $default Fallback value for the option. * @return array Requested field or default */ public function get( $field_id, $default = false ) { $opts = $this->get_options(); if ( 'all' == $field_id ) { return $opts; } elseif ( array_key_exists( $field_id, $opts ) ) { return false !== $opts[ $field_id ] ? $opts[ $field_id ] : $default; } return $default; } /** * Updates Option data * * @since 1.0.1 * @param string $field_id Option array field key. * @param mixed $value Value to update data with. * @param bool $resave Whether to re-save the data. * @param bool $single Whether data should not be an array. * @return boolean Return status of update. */ public function update( $field_id, $value = '', $resave = false, $single = true ) { $this->get_options(); if ( true !== $field_id ) { if ( ! $single ) { // If multiple, add to array. $this->options[ $field_id ][] = $value; } else { $this->options[ $field_id ] = $value; } } if ( $resave || true === $field_id ) { return $this->set(); } return true; } /** * Saves the option array * Needs to be run after finished using remove/update_option * * @uses apply_filters() Calls 'cmb2_override_option_save_{$this->key}' hook * to allow overwriting the option value to be stored. * * @since 1.0.1 * @param array $options Optional options to override. * @return bool Success/Failure */ public function set( $options = array() ) { if ( ! empty( $options ) || empty( $options ) && empty( $this->key ) ) { $this->options = $options; } $this->options = wp_unslash( $this->options ); // get rid of those evil magic quotes. if ( empty( $this->key ) ) { return false; } $test_save = apply_filters( "cmb2_override_option_save_{$this->key}", 'cmb2_no_override_option_save', $this->options, $this ); if ( 'cmb2_no_override_option_save' !== $test_save ) { // If override, do not proceed to update the option, just return result. return $test_save; } /** * Whether to auto-load the option when WordPress starts up. * * The dynamic portion of the hook name, $this->key, refers to the option key. * * @since 2.4.0 * * @param bool $autoload Whether to load the option when WordPress starts up. * @param CMB2_Option $cmb_option This object. */ $autoload = apply_filters( "cmb2_should_autoload_{$this->key}", true, $this ); return update_option( $this->key, $this->options, ! $autoload || 'no' === $autoload ? false : true ); } /** * Retrieve option value based on name of option. * * @uses apply_filters() Calls 'cmb2_override_option_get_{$this->key}' hook to allow * overwriting the option value to be retrieved. * * @since 1.0.1 * @param mixed $default Optional. Default value to return if the option does not exist. * @return mixed Value set for the option. */ public function get_options( $default = null ) { if ( empty( $this->options ) && ! empty( $this->key ) ) { $test_get = apply_filters( "cmb2_override_option_get_{$this->key}", 'cmb2_no_override_option_get', $default, $this ); if ( 'cmb2_no_override_option_get' !== $test_get ) { $this->options = $test_get; } else { // If no override, get the option. $this->options = get_option( $this->key, $default ); } } $this->options = (array) $this->options; return $this->options; } /** * Magic getter for our object. * * @since 2.6.0 * * @param string $field Requested property. * @throws Exception Throws an exception if the field is invalid. * @return mixed */ public function __get( $field ) { switch ( $field ) { case 'options': case 'key': return $this->{$field}; default: throw new Exception( sprintf( esc_html__( 'Invalid %1$s property: %2$s', 'cmb2' ), __CLASS__, $field ) ); } } } cmb2/cmb2/includes/CMB2_Hookup.php 0000644 00000066703 15151523433 0012557 0 ustar 00 <?php /** * Handles hooking CMB2 forms/metaboxes into the post/attachement/user screens * and handles hooking in and saving those fields. * * @since 2.0.0 * * @category WordPress_Plugin * @package CMB2 * @author CMB2 team * @license GPL-2.0+ * @link https://cmb2.io */ class CMB2_Hookup extends CMB2_Hookup_Base { /** * Only allow JS registration once * * @var bool * @since 2.0.7 */ protected static $js_registration_done = false; /** * Only allow CSS registration once * * @var bool * @since 2.0.7 */ protected static $css_registration_done = false; /** * CMB taxonomies array for term meta * * @var array * @since 2.2.0 */ protected $taxonomies = array(); /** * Custom field columns. * * @var array * @since 2.2.2 */ protected $columns = array(); /** * Array of CMB2_Options_Hookup instances if options page metabox. * * @var CMB2_Options_Hookup[]|null * @since 2.2.5 */ protected $options_hookup = null; /** * A functionalized constructor, used for the hookup action callbacks. * * @since 2.2.6 * * @param CMB2 $cmb The CMB2 object to hookup. * * @return CMB2_Hookup_Base $hookup The hookup object. */ public static function maybe_init_and_hookup( CMB2 $cmb ) { if ( $cmb->prop( 'hookup' ) ) { $hookup = new self( $cmb ); // Hook in the hookup... how meta. return $hookup->universal_hooks(); } return false; } public function universal_hooks() { foreach ( get_class_methods( 'CMB2_Show_Filters' ) as $filter ) { add_filter( 'cmb2_show_on', array( 'CMB2_Show_Filters', $filter ), 10, 3 ); } if ( is_admin() ) { // Register our scripts and styles for cmb. $this->once( 'admin_enqueue_scripts', array( __CLASS__, 'register_scripts' ), 8 ); $this->once( 'admin_enqueue_scripts', array( $this, 'do_scripts' ) ); $this->maybe_enqueue_column_display_styles(); switch ( $this->object_type ) { case 'post': return $this->post_hooks(); case 'comment': return $this->comment_hooks(); case 'user': return $this->user_hooks(); case 'term': return $this->term_hooks(); case 'options-page': return $this->options_page_hooks(); } } do_action( 'cmb2_init_hooks', $this ); return $this; } public function post_hooks() { // Fetch the context we set in our call. $context = $this->cmb->prop( 'context' ) ? $this->cmb->prop( 'context' ) : 'normal'; // Call the proper hook based on the context provided. switch ( $context ) { case 'form_top': add_action( 'edit_form_top', array( $this, 'add_context_metaboxes' ) ); break; case 'before_permalink': add_action( 'edit_form_before_permalink', array( $this, 'add_context_metaboxes' ) ); break; case 'after_title': add_action( 'edit_form_after_title', array( $this, 'add_context_metaboxes' ) ); break; case 'after_editor': add_action( 'edit_form_after_editor', array( $this, 'add_context_metaboxes' ) ); break; default: add_action( 'add_meta_boxes', array( $this, 'add_metaboxes' ) ); } add_action( 'add_meta_boxes', array( $this, 'remove_default_tax_metaboxes' ) ); add_action( 'add_attachment', array( $this, 'save_post' ) ); add_action( 'edit_attachment', array( $this, 'save_post' ) ); add_action( 'save_post', array( $this, 'save_post' ), 10, 2 ); if ( $this->cmb->has_columns ) { foreach ( $this->cmb->box_types() as $post_type ) { add_filter( "manage_{$post_type}_posts_columns", array( $this, 'register_column_headers' ) ); add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'column_display' ), 10, 2 ); add_filter( "manage_edit-{$post_type}_sortable_columns", array( $this, 'columns_sortable' ) ); add_action( 'pre_get_posts', array( $this, 'columns_sortable_orderby' ) ); } } return $this; } public function comment_hooks() { add_action( 'add_meta_boxes_comment', array( $this, 'add_metaboxes' ) ); add_action( 'edit_comment', array( $this, 'save_comment' ) ); if ( $this->cmb->has_columns ) { add_filter( 'manage_edit-comments_columns', array( $this, 'register_column_headers' ) ); add_action( 'manage_comments_custom_column', array( $this, 'column_display' ), 10, 3 ); add_filter( 'manage_edit-comments_sortable_columns', array( $this, 'columns_sortable' ) ); add_action( 'pre_get_posts', array( $this, 'columns_sortable_orderby' ) ); } return $this; } public function user_hooks() { $priority = $this->get_priority(); add_action( 'show_user_profile', array( $this, 'user_metabox' ), $priority ); add_action( 'edit_user_profile', array( $this, 'user_metabox' ), $priority ); add_action( 'user_new_form', array( $this, 'user_new_metabox' ), $priority ); add_action( 'personal_options_update', array( $this, 'save_user' ) ); add_action( 'edit_user_profile_update', array( $this, 'save_user' ) ); add_action( 'user_register', array( $this, 'save_user' ) ); if ( $this->cmb->has_columns ) { add_filter( 'manage_users_columns', array( $this, 'register_column_headers' ) ); add_filter( 'manage_users_custom_column', array( $this, 'return_column_display' ), 10, 3 ); add_filter( 'manage_users_sortable_columns', array( $this, 'columns_sortable' ) ); add_action( 'pre_get_posts', array( $this, 'columns_sortable_orderby' ) ); } return $this; } public function term_hooks() { if ( ! function_exists( 'get_term_meta' ) ) { wp_die( esc_html__( 'Term Metadata is a WordPress 4.4+ feature. Please upgrade your WordPress install.', 'cmb2' ) ); } if ( ! $this->cmb->prop( 'taxonomies' ) ) { wp_die( esc_html__( 'Term metaboxes configuration requires a "taxonomies" parameter.', 'cmb2' ) ); } $this->taxonomies = (array) $this->cmb->prop( 'taxonomies' ); $show_on_term_add = $this->cmb->prop( 'new_term_section' ); $priority = $this->get_priority( 8 ); foreach ( $this->taxonomies as $taxonomy ) { // Display our form data. add_action( "{$taxonomy}_edit_form", array( $this, 'term_metabox' ), $priority, 2 ); $show_on_add = is_array( $show_on_term_add ) ? in_array( $taxonomy, $show_on_term_add ) : (bool) $show_on_term_add; /** * Filter to determine if the term's fields should show in the "Add term" section. * * The dynamic portion of the hook name, $cmb_id, is the metabox id. * * @param bool $show_on_add Default is the value of the new_term_section cmb parameter. * @param object $cmb The CMB2 instance */ $show_on_add = apply_filters( "cmb2_show_on_term_add_form_{$this->cmb->cmb_id}", $show_on_add, $this->cmb ); // Display form in add-new section (unless specified not to). if ( $show_on_add ) { add_action( "{$taxonomy}_add_form_fields", array( $this, 'term_metabox' ), $priority, 2 ); } if ( $this->cmb->has_columns ) { add_filter( "manage_edit-{$taxonomy}_columns", array( $this, 'register_column_headers' ) ); add_filter( "manage_{$taxonomy}_custom_column", array( $this, 'return_column_display' ), 10, 3 ); add_filter( "manage_edit-{$taxonomy}_sortable_columns", array( $this, 'columns_sortable' ) ); add_action( 'pre_get_posts', array( $this, 'columns_sortable_orderby' ) ); } } add_action( 'created_term', array( $this, 'save_term' ), 10, 3 ); add_action( 'edited_terms', array( $this, 'save_term' ), 10, 2 ); add_action( 'delete_term', array( $this, 'delete_term' ), 10, 3 ); return $this; } public function options_page_hooks() { $option_keys = $this->cmb->options_page_keys(); if ( ! empty( $option_keys ) ) { foreach ( $option_keys as $option_key ) { $this->options_hookup[ $option_key ] = new CMB2_Options_Hookup( $this->cmb, $option_key ); $this->options_hookup[ $option_key ]->hooks(); } } return $this; } /** * Registers styles for CMB2 * * @since 2.0.7 */ protected static function register_styles() { if ( self::$css_registration_done ) { return; } // Only use minified files if SCRIPT_DEBUG is off. $min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; $front = is_admin() ? '' : '-front'; $rtl = is_rtl() ? '-rtl' : ''; /** * Filters the registered style dependencies for the cmb2 stylesheet. * * @param array $dependencies The registered style dependencies for the cmb2 stylesheet. */ $dependencies = apply_filters( 'cmb2_style_dependencies', array() ); wp_register_style( 'cmb2-styles', CMB2_Utils::url( "css/cmb2{$front}{$rtl}{$min}.css" ), $dependencies ); wp_register_style( 'cmb2-display-styles', CMB2_Utils::url( "css/cmb2-display{$rtl}{$min}.css" ), $dependencies ); self::$css_registration_done = true; } /** * Registers scripts for CMB2 * * @since 2.0.7 */ protected static function register_js() { if ( self::$js_registration_done ) { return; } $hook = is_admin() ? 'admin_footer' : 'wp_footer'; add_action( $hook, array( 'CMB2_JS', 'enqueue' ), 8 ); self::$js_registration_done = true; } /** * Registers scripts and styles for CMB2 * * @since 1.0.0 */ public static function register_scripts() { self::register_styles(); self::register_js(); } /** * Enqueues scripts and styles for CMB2 in admin_head. * * @since 1.0.0 * * @param string $hook Current hook for the admin page. */ public function do_scripts( $hook ) { $should_pre_enqueue = in_array( $hook, array( 'post.php', 'post-new.php', 'page-new.php', 'page.php', 'comment.php', 'edit-tags.php', 'term.php', 'user-new.php', 'profile.php', 'user-edit.php', ), true ); /** * Filter to determine if CMB2 should be pre-enqueued on the current page. * * `show_form_for_type` will have us covered if we miss something here, but may be a * flash of unstyled content. * * @param bool $should_pre_enqueue Whether CMB2 should be pre-enqueued on the current page. * @param string $hook The current hook for the admin page. * @param object $cmb The CMB2 object. */ $should_pre_enqueue = apply_filters( 'cmb2_should_pre_enqueue', $should_pre_enqueue, $hook, $this ); // only pre-enqueue our scripts/styles on the proper pages // show_form_for_type will have us covered if we miss something here. if ( $should_pre_enqueue ) { if ( $this->cmb->prop( 'cmb_styles' ) ) { self::enqueue_cmb_css(); } if ( $this->cmb->prop( 'enqueue_js' ) ) { self::enqueue_cmb_js(); } } } /** * Register the CMB2 field column headers. * * @since 2.2.2 * * @param array $columns Array of columns available for the admin page. */ public function register_column_headers( $columns ) { foreach ( $this->cmb->prop( 'fields' ) as $field ) { if ( empty( $field['column'] ) ) { continue; } $column = $field['column']; if ( false === $column['position'] ) { $columns[ $field['id'] ] = $column['name']; } else { $before = array_slice( $columns, 0, absint( $column['position'] ) ); $before[ $field['id'] ] = $column['name']; $columns = $before + $columns; } $column['field'] = $field; $this->columns[ $field['id'] ] = $column; } return $columns; } /** * The CMB2 field column display output. * * @since 2.2.2 * * @param string $column_name Current column name. * @param mixed $object_id Current object ID. */ public function column_display( $column_name, $object_id ) { if ( isset( $this->columns[ $column_name ] ) ) { $field = new CMB2_Field( array( 'field_args' => $this->columns[ $column_name ]['field'], 'object_type' => $this->object_type, 'object_id' => $this->cmb->object_id( $object_id ), 'cmb_id' => $this->cmb->cmb_id, ) ); $this->cmb->get_field( $field )->render_column(); } } /** * Returns the columns sortable array. * * @since 2.6.1 * * @param array $columns An array of sortable columns. * * @return array $columns An array of sortable columns with CMB2 columns. */ public function columns_sortable( $columns ) { foreach ( $this->cmb->prop( 'fields' ) as $field ) { if ( ! empty( $field['column'] ) && empty( $field['column']['disable_sortable'] ) ) { $columns[ $field['id'] ] = $field['id']; } } return $columns; } /** * Return the query object to order by custom columns if selected * * @since 2.6.1 * * @param object $query Object query from WordPress * * @return void */ public function columns_sortable_orderby( $query ) { if ( ! is_admin() ) { return; } $orderby = $query->get( 'orderby' ); foreach ( $this->cmb->prop( 'fields' ) as $field ) { if ( empty( $field['column'] ) || ! empty( $field['column']['disable_sortable'] ) || $field['id'] !== $orderby ) { continue; } $query->set( 'meta_key', $field['id'] ); $type = $field['type']; if ( ! empty( $field['attributes']['type'] ) ) { switch ( $field['attributes']['type'] ) { case 'number': case 'date': $type = $field['attributes']['type']; break; case 'range': $type = 'number'; break; } } switch ( $type ) { case 'number': case 'text_date_timestamp': case 'text_datetime_timestamp': case 'text_money': $query->set( 'orderby', 'meta_value_num' ); break; case 'text_time': $query->set( 'orderby', 'meta_value_time' ); break; case 'text_date': $query->set( 'orderby', 'meta_value_date' ); break; default: $query->set( 'orderby', 'meta_value' ); break; } } } /** * Returns the column display. * * @since 2.2.2 */ public function return_column_display( $empty, $custom_column, $object_id ) { ob_start(); $this->column_display( $custom_column, $object_id ); $column = ob_get_clean(); return $column ? $column : $empty; } /** * Output the CMB2 box/fields in an alternate context (not in a standard metabox area). * * @since 2.2.4 */ public function add_context_metaboxes() { if ( ! $this->show_on() ) { return; } $page = get_current_screen()->id; foreach ( $this->cmb->box_types() as $object_type ) { $screen = convert_to_screen( $object_type ); // If we're on the right post-type/object... if ( isset( $screen->id ) && $screen->id === $page ) { // Show the box. $this->output_context_metabox(); } } } /** * Output the CMB2 box/fields in an alternate context (not in a standard metabox area). * * @since 2.2.4 */ public function output_context_metabox() { $title = $this->cmb->prop( 'title' ); /* * To keep from outputting the open/close markup, do not include * a 'title' property in your metabox registration array. * * To output the fields 'naked' (without a postbox wrapper/style), then * add a `'remove_box_wrap' => true` to your metabox registration array. */ $add_wrap = ! empty( $title ) || ! $this->cmb->prop( 'remove_box_wrap' ); $add_handle = $add_wrap && ! empty( $title ); // Open the context-box wrap. $this->context_box_title_markup_open( $add_handle ); // Show the form fields. $this->cmb->show_form(); // Close the context-box wrap. $this->context_box_title_markup_close( $add_handle ); } /** * Output the opening markup for a context box. * * @since 2.2.4 * @param bool $add_handle Whether to add the metabox handle and opening div for .inside. */ public function context_box_title_markup_open( $add_handle = true ) { $cmb_id = $this->cmb->cmb_id; $title = $this->cmb->prop( 'title' ); $screen = get_current_screen(); $page = $screen->id; $is_55 = CMB2_Utils::wp_at_least( '5.5' ); add_filter( "postbox_classes_{$page}_{$cmb_id}", array( $this, 'postbox_classes' ) ); $hidden_class = ''; if ( $is_55 ) { // get_hidden_meta_boxes() doesn't apply in the block editor. $is_hidden = ! $screen->is_block_editor() && in_array( $cmb_id, get_hidden_meta_boxes( $screen ), true ); $hidden_class = $is_hidden ? ' hide-if-js' : ''; } $toggle_button = sprintf( '<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">%s</span><span class="toggle-indicator" aria-hidden="true"></span></button>', /* translators: %s: name of CMB2 box (panel) */ sprintf( __( 'Toggle panel: %s' ), $title ) ); $title_tag = '<h2 class="hndle"><span>' . esc_attr( $title ) . '</span></h2>' . "\n"; echo '<div id="' . $cmb_id . '" class="' . postbox_classes( $cmb_id, $page ) . $hidden_class . '">' . "\n"; if ( $add_handle ) { if ( $is_55 ) { echo '<div class="postbox-header">'; echo $title_tag; echo '<div class="handle-actions hide-if-no-js">'; echo $toggle_button; echo '</div>'; echo '</div>' . "\n"; } else { echo $toggle_button; echo $title_tag; } echo '<div class="inside">' . "\n"; } } /** * Output the closing markup for a context box. * * @since 2.2.4 * @param bool $add_inside_close Whether to add closing div for .inside. */ public function context_box_title_markup_close( $add_inside_close = true ) { // Load the closing divs for a title box. if ( $add_inside_close ) { echo '</div>' . "\n"; // .inside } echo '</div>' . "\n"; // .context-box } /** * Add metaboxes (to 'post' or 'comment' object types) * * @since 1.0.0 */ public function add_metaboxes() { if ( ! $this->show_on() ) { return; } /* * To keep from registering an actual post-screen metabox, * omit the 'title' property from the metabox registration array. * * (WordPress will not display metaboxes without titles anyway) * * This is a good solution if you want to handle outputting your * metaboxes/fields elsewhere in the post-screen. */ if ( ! $this->cmb->prop( 'title' ) ) { return; } $page = get_current_screen()->id; add_filter( "postbox_classes_{$page}_{$this->cmb->cmb_id}", array( $this, 'postbox_classes' ) ); foreach ( $this->cmb->box_types() as $object_type ) { add_meta_box( $this->cmb->cmb_id, $this->cmb->prop( 'title' ), array( $this, 'metabox_callback' ), $object_type, $this->cmb->prop( 'context' ), $this->cmb->prop( 'priority' ), $this->cmb->prop( 'mb_callback_args' ) ); } } /** * Remove the specified default taxonomy metaboxes for a post-type. * * @since 2.2.3 * */ public function remove_default_tax_metaboxes() { $to_remove = array_filter( (array) $this->cmb->tax_metaboxes_to_remove, 'taxonomy_exists' ); if ( empty( $to_remove ) ) { return; } foreach ( $this->cmb->box_types() as $post_type ) { foreach ( $to_remove as $taxonomy ) { $mb_id = is_taxonomy_hierarchical( $taxonomy ) ? "{$taxonomy}div" : "tagsdiv-{$taxonomy}"; remove_meta_box( $mb_id, $post_type, 'side' ); } } } /** * Modify metabox postbox classes. * * @since 2.2.4 * @param array $classes Array of classes. * @return array Modified array of classes */ public function postbox_classes( $classes ) { if ( $this->cmb->prop( 'closed' ) && ! in_array( 'closed', $classes ) ) { $classes[] = 'closed'; } if ( $this->cmb->is_alternate_context_box() ) { $classes = $this->alternate_context_postbox_classes( $classes ); } else { $classes[] = 'cmb2-postbox'; } return $classes; } /** * Modify metabox altnernate context postbox classes. * * @since 2.2.4 * @param array $classes Array of classes. * @return array Modified array of classes */ protected function alternate_context_postbox_classes( $classes ) { $classes[] = 'context-box'; $classes[] = 'context-' . $this->cmb->prop( 'context' ) . '-box'; if ( in_array( $this->cmb->cmb_id, get_hidden_meta_boxes( get_current_screen() ) ) ) { $classes[] = 'hide-if-js'; } $add_wrap = $this->cmb->prop( 'title' ) || ! $this->cmb->prop( 'remove_box_wrap' ); if ( $add_wrap ) { $classes[] = 'cmb2-postbox postbox'; } else { $classes[] = 'cmb2-no-box-wrap'; } return $classes; } /** * Display metaboxes for a post or comment object. * * @since 1.0.0 */ public function metabox_callback() { $object_id = 'comment' === $this->object_type ? get_comment_ID() : get_the_ID(); $this->cmb->show_form( $object_id, $this->object_type ); } /** * Display metaboxes for new user page. * * @since 1.0.0 * * @param mixed $section User section metabox. */ public function user_new_metabox( $section ) { if ( $section === $this->cmb->prop( 'new_user_section' ) ) { $object_id = $this->cmb->object_id(); $this->cmb->object_id( isset( $_REQUEST['user_id'] ) ? $_REQUEST['user_id'] : $object_id ); $this->user_metabox(); } } /** * Display metaboxes for a user object. * * @since 1.0.0 */ public function user_metabox() { $this->show_form_for_type( 'user' ); } /** * Display metaboxes for a taxonomy term object. * * @since 2.2.0 */ public function term_metabox() { $this->show_form_for_type( 'term' ); } /** * Display metaboxes for an object type. * * @since 2.2.0 * @param string $type Object type. * @return void */ public function show_form_for_type( $type ) { if ( $type != $this->object_type ) { return; } if ( ! $this->show_on() ) { return; } if ( $this->cmb->prop( 'cmb_styles' ) ) { self::enqueue_cmb_css(); } if ( $this->cmb->prop( 'enqueue_js' ) ) { self::enqueue_cmb_js(); } $this->cmb->show_form( 0, $type ); } /** * Determines if metabox should be shown in current context. * * @since 2.0.0 * @return bool Whether metabox should be added/shown. */ public function show_on() { // If metabox is requesting to be conditionally shown. $show = $this->cmb->should_show(); /** * Filter to determine if metabox should show. Default is true. * * @param array $show Default is true, show the metabox. * @param mixed $meta_box_args Array of the metabox arguments. * @param mixed $cmb The CMB2 instance. */ $show = (bool) apply_filters( 'cmb2_show_on', $show, $this->cmb->meta_box, $this->cmb ); return $show; } /** * Get the CMB priority property set to numeric hook priority. * * @since 2.2.0 * * @param integer $default Default display hook priority. * @return integer Hook priority. */ public function get_priority( $default = 10 ) { $priority = $this->cmb->prop( 'priority' ); if ( ! is_numeric( $priority ) ) { switch ( $priority ) { case 'high': $priority = 5; break; case 'low': $priority = 20; break; default: $priority = $default; break; } } return $priority; } /** * Save data from post metabox * * @since 1.0.0 * @param int $post_id Post ID. * @param mixed $post Post object. * @return void */ public function save_post( $post_id, $post = false ) { $post_type = $post ? $post->post_type : get_post_type( $post_id ); $do_not_pass_go = ( ! $this->can_save( $post_type ) // Check user editing permissions. || ( 'page' === $post_type && ! current_user_can( 'edit_page', $post_id ) ) || ! current_user_can( 'edit_post', $post_id ) ); if ( $do_not_pass_go ) { return; } $this->cmb->save_fields( $post_id, 'post', $_POST ); } /** * Save data from comment metabox. * * @since 2.0.9 * @param int $comment_id Comment ID. * @return void */ public function save_comment( $comment_id ) { $can_edit = current_user_can( 'moderate_comments', $comment_id ); if ( $this->can_save( get_comment_type( $comment_id ) ) && $can_edit ) { $this->cmb->save_fields( $comment_id, 'comment', $_POST ); } } /** * Save data from user fields. * * @since 1.0.x * @param int $user_id User ID. * @return void */ public function save_user( $user_id ) { // check permissions. if ( $this->can_save( 'user' ) ) { $this->cmb->save_fields( $user_id, 'user', $_POST ); } } /** * Save data from term fields * * @since 2.2.0 * @param int $term_id Term ID. * @param int $tt_id Term Taxonomy ID. * @param string $taxonomy Taxonomy. * @return void */ public function save_term( $term_id, $tt_id, $taxonomy = '' ) { $taxonomy = $taxonomy ? $taxonomy : $tt_id; // check permissions. if ( $this->taxonomy_can_save( $taxonomy ) && $this->can_save( 'term' ) ) { $this->cmb->save_fields( $term_id, 'term', $_POST ); } } /** * Delete term meta when a term is deleted. * * @since 2.2.0 * @param int $term_id Term ID. * @param int $tt_id Term Taxonomy ID. * @param string $taxonomy Taxonomy. * @return void */ public function delete_term( $term_id, $tt_id, $taxonomy = '' ) { if ( $this->taxonomy_can_save( $taxonomy ) ) { $data_to_delete = array(); foreach ( $this->cmb->prop( 'fields' ) as $field ) { $data_to_delete[ $field['id'] ] = ''; } $this->cmb->save_fields( $term_id, 'term', $data_to_delete ); } } /** * Determines if the current object is able to be saved. * * @since 2.0.9 * @param string $type Current object type. * @return bool Whether object can be saved. */ public function can_save( $type = '' ) { $can_save = ( $this->cmb->prop( 'save_fields' ) // check nonce. && isset( $_POST[ $this->cmb->nonce() ] ) && wp_verify_nonce( $_POST[ $this->cmb->nonce() ], $this->cmb->nonce() ) // check if autosave. && ! ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) // get the metabox types & compare it to this type. && ( $type && in_array( $type, $this->cmb->box_types() ) ) // Don't do updates during a switch-to-blog instance. && ! ( is_multisite() && ms_is_switched() ) ); /** * Filter to determine if metabox is allowed to save. * * @param bool $can_save Whether the current metabox can save. * @param object $cmb The CMB2 instance. */ return apply_filters( 'cmb2_can_save', $can_save, $this->cmb ); } /** * Determine if taxonomy of term being modified is cmb2-editable. * * @since 2.2.0 * * @param string $taxonomy Taxonomy of term being modified. * @return bool Whether taxonomy is editable. */ public function taxonomy_can_save( $taxonomy ) { if ( empty( $this->taxonomies ) || ! in_array( $taxonomy, $this->taxonomies ) ) { return false; } $taxonomy_object = get_taxonomy( $taxonomy ); // Can the user edit this term? if ( ! isset( $taxonomy_object->cap ) || ! current_user_can( $taxonomy_object->cap->edit_terms ) ) { return false; } return true; } /** * Enqueues the 'cmb2-display-styles' if the conditions match (has columns, on the right page, etc). * * @since 2.2.2.1 */ protected function maybe_enqueue_column_display_styles() { global $pagenow; if ( $pagenow && $this->cmb->has_columns && $this->cmb->prop( 'cmb_styles' ) && in_array( $pagenow, array( 'edit.php', 'users.php', 'edit-comments.php', 'edit-tags.php' ), 1 ) ) { self::enqueue_cmb_css( 'cmb2-display-styles' ); } } /** * Includes CMB2 styles. * * @since 2.0.0 * * @param string $handle CSS handle. * @return mixed */ public static function enqueue_cmb_css( $handle = 'cmb2-styles' ) { /** * Filter to determine if CMB2'S css should be enqueued. * * @param bool $enqueue_css Default is true. */ if ( ! apply_filters( 'cmb2_enqueue_css', true ) ) { return false; } self::register_styles(); /* * White list the options as this method can be used as a hook callback * and have a different argument passed. */ return wp_enqueue_style( 'cmb2-display-styles' === $handle ? $handle : 'cmb2-styles' ); } /** * Includes CMB2 JS. * * @since 2.0.0 */ public static function enqueue_cmb_js() { /** * Filter to determine if CMB2'S JS should be enqueued. * * @param bool $enqueue_js Default is true. */ if ( ! apply_filters( 'cmb2_enqueue_js', true ) ) { return false; } self::register_js(); return true; } } cmb2/cmb2/index.php 0000644 00000000034 15151523433 0010031 0 ustar 00 <?php // Silence is golden. cmb2/cmb2/bootstrap.php 0000644 00000003573 15151523433 0010752 0 ustar 00 <?php /** * Bootstraps the CMB2 process * * @category WordPress_Plugin * @package CMB2 * @author CMB2 * @license GPL-2.0+ * @link https://cmb2.io */ /** * Function to encapsulate the CMB2 bootstrap process. * * @since 2.2.0 * @return void */ function cmb2_bootstrap() { if ( is_admin() ) { /** * Fires on the admin side when CMB2 is included/loaded. * * In most cases, this should be used to add metaboxes. See example-functions.php */ do_action( 'cmb2_admin_init' ); } /** * Fires when CMB2 is included/loaded * * Can be used to add metaboxes if needed on the front-end or WP-API (or the front and backend). */ do_action( 'cmb2_init' ); /** * For back-compat. Does the dirty-work of instantiating all the * CMB2 instances for the cmb2_meta_boxes filter * * @since 2.0.2 */ $cmb_config_arrays = apply_filters( 'cmb2_meta_boxes', array() ); foreach ( (array) $cmb_config_arrays as $cmb_config ) { new CMB2( $cmb_config ); } /** * Fires after all CMB2 instances are created */ do_action( 'cmb2_init_before_hookup' ); /** * Get all created metaboxes, and instantiate CMB2_Hookup * on metaboxes which require it. * * @since 2.0.2 */ foreach ( CMB2_Boxes::get_all() as $cmb ) { /** * Initiates the box "hookup" into WordPress. * * Unless the 'hookup' box property is `false`, the box will be hooked in as * a post/user/comment/option/term box. * * And if the 'show_in_rest' box property is set, the box will be hooked * into the CMB2 REST API. * * The dynamic portion of the hook name, $cmb->cmb_id, is the box id. * * @since 2.2.6 * * @param array $cmb The CMB2 object to hookup. */ do_action( "cmb2_init_hookup_{$cmb->cmb_id}", $cmb ); } /** * Fires after CMB2 initiation process has been completed */ do_action( 'cmb2_after_init' ); } /* End. That's it, folks! */ woocommerce/action-scheduler/classes/schedules/ActionScheduler_SimpleSchedule.php 0000644 00000004477 15151523433 0024521 0 ustar 00 <?php /** * Class ActionScheduler_SimpleSchedule */ class ActionScheduler_SimpleSchedule extends ActionScheduler_Abstract_Schedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null|DateTime */ private $timestamp = null; /** * Calculate when this schedule should start after a given date & time using * the number of seconds between recurrences. * * @param DateTime $after Timestamp. * * @return DateTime|null */ public function calculate_next( DateTime $after ) { return null; } /** * Schedule is not recurring. * * @return bool */ public function is_recurring() { return false; } /** * Serialize schedule with data required prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To guard against the * scheduled date for single actions always being seen as "now" if downgrading to * Action Scheduler < 3.0.0, we need to also store the data with the old property names * so if it's unserialized in AS < 3.0, the schedule doesn't end up with a null recurrence. * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->timestamp = $this->scheduled_timestamp; return array_merge( $sleep_params, array( 'timestamp', ) ); } /** * Unserialize recurring schedules serialized/stored prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To maintain backward * compatibility with schedules serialized and stored prior to 3.0, we need to correctly * map the old property names with matching visibility. */ public function __wakeup() { if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->timestamp ) ) { $this->scheduled_timestamp = $this->timestamp; unset( $this->timestamp ); } parent::__wakeup(); } } woocommerce/action-scheduler/classes/schedules/ActionScheduler_NullSchedule.php 0000644 00000001305 15151523433 0024165 0 ustar 00 <?php /** * Class ActionScheduler_NullSchedule */ class ActionScheduler_NullSchedule extends ActionScheduler_SimpleSchedule { /** * DateTime instance. * * @var DateTime|null */ protected $scheduled_date; /** * Make the $date param optional and default to null. * * @param null|DateTime $date The date & time to run the action. */ public function __construct( ?DateTime $date = null ) { $this->scheduled_date = null; } /** * This schedule has no scheduled DateTime, so we need to override the parent __sleep(). * * @return array */ public function __sleep() { return array(); } /** * Wakeup. */ public function __wakeup() { $this->scheduled_date = null; } } woocommerce/action-scheduler/classes/schedules/ActionScheduler_CanceledSchedule.php 0000644 00000003157 15151523433 0024760 0 ustar 00 <?php /** * Class ActionScheduler_SimpleSchedule */ class ActionScheduler_CanceledSchedule extends ActionScheduler_SimpleSchedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $timestamp = null; /** * Calculate when the next instance of this schedule would run based on a given date & time. * * @param DateTime $after Timestamp. * * @return DateTime|null */ public function calculate_next( DateTime $after ) { return null; } /** * Cancelled actions should never have a next schedule, even if get_next() * is called with $after < $this->scheduled_date. * * @param DateTime $after Timestamp. * @return DateTime|null */ public function get_next( DateTime $after ) { return null; } /** * Action is not recurring. * * @return bool */ public function is_recurring() { return false; } /** * Unserialize recurring schedules serialized/stored prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To maintain backward * compatibility with schedules serialized and stored prior to 3.0, we need to correctly * map the old property names with matching visibility. */ public function __wakeup() { if ( ! is_null( $this->timestamp ) ) { $this->scheduled_timestamp = $this->timestamp; unset( $this->timestamp ); } parent::__wakeup(); } } woocommerce/action-scheduler/classes/schedules/ActionScheduler_CronSchedule.php 0000644 00000007367 15151523433 0024172 0 ustar 00 <?php /** * Class ActionScheduler_CronSchedule */ class ActionScheduler_CronSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $start_timestamp = null; /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $cron = null; /** * Wrapper for parent constructor to accept a cron expression string and map it to a CronExpression for this * objects $recurrence property. * * @param DateTime $start The date & time to run the action at or after. If $start aligns with the CronSchedule passed via $recurrence, it will be used. If it does not align, the first matching date after it will be used. * @param CronExpression|string $recurrence The CronExpression used to calculate the schedule's next instance. * @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance. */ public function __construct( DateTime $start, $recurrence, ?DateTime $first = null ) { if ( ! is_a( $recurrence, 'CronExpression' ) ) { $recurrence = CronExpression::factory( $recurrence ); } // For backward compatibility, we need to make sure the date is set to the first matching cron date, not whatever date is passed in. Importantly, by passing true as the 3rd param, if $start matches the cron expression, then it will be used. This was previously handled in the now deprecated next() method. $date = $recurrence->getNextRunDate( $start, 0, true ); // parent::__construct() will set this to $date by default, but that may be different to $start now. $first = empty( $first ) ? $start : $first; parent::__construct( $date, $recurrence, $first ); } /** * Calculate when an instance of this schedule would start based on a given * date & time using its the CronExpression. * * @param DateTime $after Timestamp. * @return DateTime */ protected function calculate_next( DateTime $after ) { return $this->recurrence->getNextRunDate( $after, 0, false ); } /** * Get the schedule's recurrence. * * @return string */ public function get_recurrence() { return strval( $this->recurrence ); } /** * Serialize cron schedules with data required prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, recurring schedules used different property names to * refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To guard against the * possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to * also store the data with the old property names so if it's unserialized in AS < 3.0, * the schedule doesn't end up with a null recurrence. * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->start_timestamp = $this->scheduled_timestamp; $this->cron = $this->recurrence; return array_merge( $sleep_params, array( 'start_timestamp', 'cron', ) ); } /** * Unserialize cron schedules serialized/stored prior to AS 3.0.0 * * For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup(). */ public function __wakeup() { if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) { $this->scheduled_timestamp = $this->start_timestamp; unset( $this->start_timestamp ); } if ( is_null( $this->recurrence ) && ! is_null( $this->cron ) ) { $this->recurrence = $this->cron; unset( $this->cron ); } parent::__wakeup(); } } woocommerce/action-scheduler/classes/schedules/ActionScheduler_Schedule.php 0000644 00000000710 15151523433 0023331 0 ustar 00 <?php /** * Class ActionScheduler_Schedule */ interface ActionScheduler_Schedule { /** * Get the date & time this schedule was created to run, or calculate when it should be run * after a given date & time. * * @param null|DateTime $after Timestamp. * @return DateTime|null */ public function next( ?DateTime $after = null ); /** * Identify the schedule as (not) recurring. * * @return bool */ public function is_recurring(); } woocommerce/action-scheduler/classes/schedules/ActionScheduler_IntervalSchedule.php 0000644 00000005111 15151523433 0025036 0 ustar 00 <?php /** * Class ActionScheduler_IntervalSchedule */ class ActionScheduler_IntervalSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule { /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $start_timestamp = null; /** * Deprecated property @see $this->__wakeup() for details. * * @var null */ private $interval_in_seconds = null; /** * Calculate when this schedule should start after a given date & time using * the number of seconds between recurrences. * * @param DateTime $after Timestamp. * @return DateTime */ protected function calculate_next( DateTime $after ) { $after->modify( '+' . (int) $this->get_recurrence() . ' seconds' ); return $after; } /** * Schedule interval in seconds. * * @return int */ public function interval_in_seconds() { _deprecated_function( __METHOD__, '3.0.0', '(int)ActionScheduler_Abstract_RecurringSchedule::get_recurrence()' ); return (int) $this->get_recurrence(); } /** * Serialize interval schedules with data required prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, recurring schedules used different property names to * refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0 * aligned properties and property names for better inheritance. To guard against the * possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to * also store the data with the old property names so if it's unserialized in AS < 3.0, * the schedule doesn't end up with a null/false/0 recurrence. * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->start_timestamp = $this->scheduled_timestamp; $this->interval_in_seconds = $this->recurrence; return array_merge( $sleep_params, array( 'start_timestamp', 'interval_in_seconds', ) ); } /** * Unserialize interval schedules serialized/stored prior to AS 3.0.0 * * For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup(). */ public function __wakeup() { if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) { $this->scheduled_timestamp = $this->start_timestamp; unset( $this->start_timestamp ); } if ( is_null( $this->recurrence ) && ! is_null( $this->interval_in_seconds ) ) { $this->recurrence = $this->interval_in_seconds; unset( $this->interval_in_seconds ); } parent::__wakeup(); } } woocommerce/action-scheduler/classes/ActionScheduler_QueueCleaner.php 0000644 00000017607 15151523433 0022211 0 ustar 00 <?php /** * Class ActionScheduler_QueueCleaner */ class ActionScheduler_QueueCleaner { /** * The batch size. * * @var int */ protected $batch_size; /** * ActionScheduler_Store instance. * * @var ActionScheduler_Store */ private $store = null; /** * 31 days in seconds. * * @var int */ private $month_in_seconds = 2678400; /** * Default list of statuses purged by the cleaner process. * * @var string[] */ private $default_statuses_to_purge = array( ActionScheduler_Store::STATUS_COMPLETE, ActionScheduler_Store::STATUS_CANCELED, ); /** * ActionScheduler_QueueCleaner constructor. * * @param ActionScheduler_Store|null $store The store instance. * @param int $batch_size The batch size. */ public function __construct( ?ActionScheduler_Store $store = null, $batch_size = 20 ) { $this->store = $store ? $store : ActionScheduler_Store::instance(); $this->batch_size = $batch_size; } /** * Default queue cleaner process used by queue runner. * * @return array */ public function delete_old_actions() { /** * Filter the minimum scheduled date age for action deletion. * * @param int $retention_period Minimum scheduled age in seconds of the actions to be deleted. */ $lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds ); try { $cutoff = as_get_datetime_object( $lifespan . ' seconds ago' ); } catch ( Exception $e ) { _doing_it_wrong( __METHOD__, sprintf( /* Translators: %s is the exception message. */ esc_html__( 'It was not possible to determine a valid cut-off time: %s.', 'action-scheduler' ), esc_html( $e->getMessage() ) ), '3.5.5' ); return array(); } /** * Filter the statuses when cleaning the queue. * * @param string[] $default_statuses_to_purge Action statuses to clean. */ $statuses_to_purge = (array) apply_filters( 'action_scheduler_default_cleaner_statuses', $this->default_statuses_to_purge ); return $this->clean_actions( $statuses_to_purge, $cutoff, $this->get_batch_size() ); } /** * Delete selected actions limited by status and date. * * @param string[] $statuses_to_purge List of action statuses to purge. Defaults to canceled, complete. * @param DateTime $cutoff_date Date limit for selecting actions. Defaults to 31 days ago. * @param int|null $batch_size Maximum number of actions per status to delete. Defaults to 20. * @param string $context Calling process context. Defaults to `old`. * @return array Actions deleted. */ public function clean_actions( array $statuses_to_purge, DateTime $cutoff_date, $batch_size = null, $context = 'old' ) { $batch_size = ! is_null( $batch_size ) ? $batch_size : $this->batch_size; $cutoff = ! is_null( $cutoff_date ) ? $cutoff_date : as_get_datetime_object( $this->month_in_seconds . ' seconds ago' ); $lifespan = time() - $cutoff->getTimestamp(); if ( empty( $statuses_to_purge ) ) { $statuses_to_purge = $this->default_statuses_to_purge; } $deleted_actions = array(); foreach ( $statuses_to_purge as $status ) { $actions_to_delete = $this->store->query_actions( array( 'status' => $status, 'modified' => $cutoff, 'modified_compare' => '<=', 'per_page' => $batch_size, 'orderby' => 'none', ) ); $deleted_actions = array_merge( $deleted_actions, $this->delete_actions( $actions_to_delete, $lifespan, $context ) ); } return $deleted_actions; } /** * Delete actions. * * @param int[] $actions_to_delete List of action IDs to delete. * @param int $lifespan Minimum scheduled age in seconds of the actions being deleted. * @param string $context Context of the delete request. * @return array Deleted action IDs. */ private function delete_actions( array $actions_to_delete, $lifespan = null, $context = 'old' ) { $deleted_actions = array(); if ( is_null( $lifespan ) ) { $lifespan = $this->month_in_seconds; } foreach ( $actions_to_delete as $action_id ) { try { $this->store->delete_action( $action_id ); $deleted_actions[] = $action_id; } catch ( Exception $e ) { /** * Notify 3rd party code of exceptions when deleting a completed action older than the retention period * * This hook provides a way for 3rd party code to log or otherwise handle exceptions relating to their * actions. * * @param int $action_id The scheduled actions ID in the data store * @param Exception $e The exception thrown when attempting to delete the action from the data store * @param int $lifespan The retention period, in seconds, for old actions * @param int $count_of_actions_to_delete The number of old actions being deleted in this batch * @since 2.0.0 */ do_action( "action_scheduler_failed_{$context}_action_deletion", $action_id, $e, $lifespan, count( $actions_to_delete ) ); } } return $deleted_actions; } /** * Unclaim pending actions that have not been run within a given time limit. * * When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed * as a parameter is 10x the time limit used for queue processing. * * @param int $time_limit The number of seconds to allow a queue to run before unclaiming its pending actions. Default 300 (5 minutes). */ public function reset_timeouts( $time_limit = 300 ) { $timeout = apply_filters( 'action_scheduler_timeout_period', $time_limit ); if ( $timeout < 0 ) { return; } $cutoff = as_get_datetime_object( $timeout . ' seconds ago' ); $actions_to_reset = $this->store->query_actions( array( 'status' => ActionScheduler_Store::STATUS_PENDING, 'modified' => $cutoff, 'modified_compare' => '<=', 'claimed' => true, 'per_page' => $this->get_batch_size(), 'orderby' => 'none', ) ); foreach ( $actions_to_reset as $action_id ) { $this->store->unclaim_action( $action_id ); do_action( 'action_scheduler_reset_action', $action_id ); } } /** * Mark actions that have been running for more than a given time limit as failed, based on * the assumption some uncatchable and unloggable fatal error occurred during processing. * * When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed * as a parameter is 10x the time limit used for queue processing. * * @param int $time_limit The number of seconds to allow an action to run before it is considered to have failed. Default 300 (5 minutes). */ public function mark_failures( $time_limit = 300 ) { $timeout = apply_filters( 'action_scheduler_failure_period', $time_limit ); if ( $timeout < 0 ) { return; } $cutoff = as_get_datetime_object( $timeout . ' seconds ago' ); $actions_to_reset = $this->store->query_actions( array( 'status' => ActionScheduler_Store::STATUS_RUNNING, 'modified' => $cutoff, 'modified_compare' => '<=', 'per_page' => $this->get_batch_size(), 'orderby' => 'none', ) ); foreach ( $actions_to_reset as $action_id ) { $this->store->mark_failure( $action_id ); do_action( 'action_scheduler_failed_action', $action_id, $timeout ); } } /** * Do all of the cleaning actions. * * @param int $time_limit The number of seconds to use as the timeout and failure period. Default 300 (5 minutes). */ public function clean( $time_limit = 300 ) { $this->delete_old_actions(); $this->reset_timeouts( $time_limit ); $this->mark_failures( $time_limit ); } /** * Get the batch size for cleaning the queue. * * @return int */ protected function get_batch_size() { /** * Filter the batch size when cleaning the queue. * * @param int $batch_size The number of actions to clean in one batch. */ return absint( apply_filters( 'action_scheduler_cleanup_batch_size', $this->batch_size ) ); } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php 0000644 00000001372 15151523433 0030143 0 ustar 00 <?php /** * Class ActionScheduler_wpPostStore_TaxonomyRegistrar * * @codeCoverageIgnore */ class ActionScheduler_wpPostStore_TaxonomyRegistrar { /** * Registrar. */ public function register() { register_taxonomy( ActionScheduler_wpPostStore::GROUP_TAXONOMY, ActionScheduler_wpPostStore::POST_TYPE, $this->taxonomy_args() ); } /** * Get taxonomy arguments. */ protected function taxonomy_args() { $args = array( 'label' => __( 'Action Group', 'action-scheduler' ), 'public' => false, 'hierarchical' => false, 'show_admin_column' => true, 'query_var' => false, 'rewrite' => false, ); $args = apply_filters( 'action_scheduler_taxonomy_args', $args ); return $args; } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_HybridStore.php 0000644 00000030606 15151523433 0024311 0 ustar 00 <?php use ActionScheduler_Store as Store; use Action_Scheduler\Migration\Runner; use Action_Scheduler\Migration\Config; use Action_Scheduler\Migration\Controller; /** * Class ActionScheduler_HybridStore * * A wrapper around multiple stores that fetches data from both. * * @since 3.0.0 */ class ActionScheduler_HybridStore extends Store { const DEMARKATION_OPTION = 'action_scheduler_hybrid_store_demarkation'; /** * Primary store instance. * * @var ActionScheduler_Store */ private $primary_store; /** * Secondary store instance. * * @var ActionScheduler_Store */ private $secondary_store; /** * Runner instance. * * @var Action_Scheduler\Migration\Runner */ private $migration_runner; /** * The dividing line between IDs of actions created * by the primary and secondary stores. * * @var int * * Methods that accept an action ID will compare the ID against * this to determine which store will contain that ID. In almost * all cases, the ID should come from the primary store, but if * client code is bypassing the API functions and fetching IDs * from elsewhere, then there is a chance that an unmigrated ID * might be requested. */ private $demarkation_id = 0; /** * ActionScheduler_HybridStore constructor. * * @param Config|null $config Migration config object. */ public function __construct( ?Config $config = null ) { $this->demarkation_id = (int) get_option( self::DEMARKATION_OPTION, 0 ); if ( empty( $config ) ) { $config = Controller::instance()->get_migration_config_object(); } $this->primary_store = $config->get_destination_store(); $this->secondary_store = $config->get_source_store(); $this->migration_runner = new Runner( $config ); } /** * Initialize the table data store tables. * * @codeCoverageIgnore */ public function init() { add_action( 'action_scheduler/created_table', array( $this, 'set_autoincrement' ), 10, 2 ); $this->primary_store->init(); $this->secondary_store->init(); remove_action( 'action_scheduler/created_table', array( $this, 'set_autoincrement' ), 10 ); } /** * When the actions table is created, set its autoincrement * value to be one higher than the posts table to ensure that * there are no ID collisions. * * @param string $table_name Table name. * @param string $table_suffix Suffix of table name. * * @return void * @codeCoverageIgnore */ public function set_autoincrement( $table_name, $table_suffix ) { if ( ActionScheduler_StoreSchema::ACTIONS_TABLE === $table_suffix ) { if ( empty( $this->demarkation_id ) ) { $this->demarkation_id = $this->set_demarkation_id(); } /** * Global. * * @var \wpdb $wpdb */ global $wpdb; /** * A default date of '0000-00-00 00:00:00' is invalid in MySQL 5.7 when configured with * sql_mode including both STRICT_TRANS_TABLES and NO_ZERO_DATE. */ $default_date = new DateTime( 'tomorrow' ); $null_action = new ActionScheduler_NullAction(); $date_gmt = $this->get_scheduled_date_string( $null_action, $default_date ); $date_local = $this->get_scheduled_date_string_local( $null_action, $default_date ); $row_count = $wpdb->insert( $wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE}, array( 'action_id' => $this->demarkation_id, 'hook' => '', 'status' => '', 'scheduled_date_gmt' => $date_gmt, 'scheduled_date_local' => $date_local, 'last_attempt_gmt' => $date_gmt, 'last_attempt_local' => $date_local, ) ); if ( $row_count > 0 ) { $wpdb->delete( $wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE}, array( 'action_id' => $this->demarkation_id ) ); } } } /** * Store the demarkation id in WP options. * * @param int $id The ID to set as the demarkation point between the two stores * Leave null to use the next ID from the WP posts table. * * @return int The new ID. * * @codeCoverageIgnore */ private function set_demarkation_id( $id = null ) { if ( empty( $id ) ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $id = (int) $wpdb->get_var( "SELECT MAX(ID) FROM $wpdb->posts" ); $id++; } update_option( self::DEMARKATION_OPTION, $id ); return $id; } /** * Find the first matching action from the secondary store. * If it exists, migrate it to the primary store immediately. * After it migrates, the secondary store will logically contain * the next matching action, so return the result thence. * * @param string $hook Action's hook. * @param array $params Action's arguments. * * @return string */ public function find_action( $hook, $params = array() ) { $found_unmigrated_action = $this->secondary_store->find_action( $hook, $params ); if ( ! empty( $found_unmigrated_action ) ) { $this->migrate( array( $found_unmigrated_action ) ); } return $this->primary_store->find_action( $hook, $params ); } /** * Find actions matching the query in the secondary source first. * If any are found, migrate them immediately. Then the secondary * store will contain the canonical results. * * @param array $query Query arguments. * @param string $query_type Whether to select or count the results. Default, select. * * @return int[] */ public function query_actions( $query = array(), $query_type = 'select' ) { $found_unmigrated_actions = $this->secondary_store->query_actions( $query, 'select' ); if ( ! empty( $found_unmigrated_actions ) ) { $this->migrate( $found_unmigrated_actions ); } return $this->primary_store->query_actions( $query, $query_type ); } /** * Get a count of all actions in the store, grouped by status * * @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status. */ public function action_counts() { $unmigrated_actions_count = $this->secondary_store->action_counts(); $migrated_actions_count = $this->primary_store->action_counts(); $actions_count_by_status = array(); foreach ( $this->get_status_labels() as $status_key => $status_label ) { $count = 0; if ( isset( $unmigrated_actions_count[ $status_key ] ) ) { $count += $unmigrated_actions_count[ $status_key ]; } if ( isset( $migrated_actions_count[ $status_key ] ) ) { $count += $migrated_actions_count[ $status_key ]; } $actions_count_by_status[ $status_key ] = $count; } $actions_count_by_status = array_filter( $actions_count_by_status ); return $actions_count_by_status; } /** * If any actions would have been claimed by the secondary store, * migrate them immediately, then ask the primary store for the * canonical claim. * * @param int $max_actions Maximum number of actions to claim. * @param null|DateTime $before_date Latest timestamp of actions to claim. * @param string[] $hooks Hook of actions to claim. * @param string $group Group of actions to claim. * * @return ActionScheduler_ActionClaim */ public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ) { $claim = $this->secondary_store->stake_claim( $max_actions, $before_date, $hooks, $group ); $claimed_actions = $claim->get_actions(); if ( ! empty( $claimed_actions ) ) { $this->migrate( $claimed_actions ); } $this->secondary_store->release_claim( $claim ); return $this->primary_store->stake_claim( $max_actions, $before_date, $hooks, $group ); } /** * Migrate a list of actions to the table data store. * * @param array $action_ids List of action IDs. */ private function migrate( $action_ids ) { $this->migration_runner->migrate_actions( $action_ids ); } /** * Save an action to the primary store. * * @param ActionScheduler_Action $action Action object to be saved. * @param DateTime|null $date Optional. Schedule date. Default null. * * @return int The action ID */ public function save_action( ActionScheduler_Action $action, ?DateTime $date = null ) { return $this->primary_store->save_action( $action, $date ); } /** * Retrieve an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function fetch_action( $action_id ) { $store = $this->get_store_from_action_id( $action_id, true ); if ( $store ) { return $store->fetch_action( $action_id ); } else { return new ActionScheduler_NullAction(); } } /** * Cancel an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function cancel_action( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->cancel_action( $action_id ); } } /** * Delete an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function delete_action( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->delete_action( $action_id ); } } /** * Get the schedule date an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function get_date( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { return $store->get_date( $action_id ); } else { return null; } } /** * Mark an existing action as failed whether migrated or not. * * @param int $action_id Action ID. */ public function mark_failure( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->mark_failure( $action_id ); } } /** * Log the execution of an existing action whether migrated or not. * * @param int $action_id Action ID. */ public function log_execution( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->log_execution( $action_id ); } } /** * Mark an existing action complete whether migrated or not. * * @param int $action_id Action ID. */ public function mark_complete( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { $store->mark_complete( $action_id ); } } /** * Get an existing action status whether migrated or not. * * @param int $action_id Action ID. */ public function get_status( $action_id ) { $store = $this->get_store_from_action_id( $action_id ); if ( $store ) { return $store->get_status( $action_id ); } return null; } /** * Return which store an action is stored in. * * @param int $action_id ID of the action. * @param bool $primary_first Optional flag indicating search the primary store first. * @return ActionScheduler_Store */ protected function get_store_from_action_id( $action_id, $primary_first = false ) { if ( $primary_first ) { $stores = array( $this->primary_store, $this->secondary_store, ); } elseif ( $action_id < $this->demarkation_id ) { $stores = array( $this->secondary_store, $this->primary_store, ); } else { $stores = array( $this->primary_store, ); } foreach ( $stores as $store ) { $action = $store->fetch_action( $action_id ); if ( ! is_a( $action, 'ActionScheduler_NullAction' ) ) { return $store; } } return null; } /** * * * * * * * * * * * * * * * * * * * * * * * * * * * * All claim-related functions should operate solely * on the primary store. * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get the claim count from the table data store. */ public function get_claim_count() { return $this->primary_store->get_claim_count(); } /** * Retrieve the claim ID for an action from the table data store. * * @param int $action_id Action ID. */ public function get_claim_id( $action_id ) { return $this->primary_store->get_claim_id( $action_id ); } /** * Release a claim in the table data store on any pending actions. * * @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 ); } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore.php 0000644 00000107413 15151523433 0024365 0 ustar 00 <?php /** * Class ActionScheduler_wpPostStore */ class ActionScheduler_wpPostStore extends ActionScheduler_Store { const POST_TYPE = 'scheduled-action'; const GROUP_TAXONOMY = 'action-group'; const SCHEDULE_META_KEY = '_action_manager_schedule'; const DEPENDENCIES_MET = 'as-post-store-dependencies-met'; /** * Used to share information about the before_date property of claims internally. * * This is used in preference to passing the same information as a method param * for backwards-compatibility reasons. * * @var DateTime|null */ private $claim_before_date = null; /** * Local Timezone. * * @var DateTimeZone */ protected $local_timezone = null; /** * Save action. * * @param ActionScheduler_Action $action Scheduled Action. * @param DateTime|null $scheduled_date Scheduled Date. * * @throws RuntimeException Throws an exception if the action could not be saved. * @return int */ public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) { try { $this->validate_action( $action ); $post_array = $this->create_post_array( $action, $scheduled_date ); $post_id = $this->save_post_array( $post_array ); $this->save_post_schedule( $post_id, $action->get_schedule() ); $this->save_action_group( $post_id, $action->get_group() ); do_action( 'action_scheduler_stored_action', $post_id ); return $post_id; } catch ( Exception $e ) { /* translators: %s: action error message */ throw new RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 ); } } /** * Create post array. * * @param ActionScheduler_Action $action Scheduled Action. * @param DateTime|null $scheduled_date Scheduled Date. * * @return array Returns an array of post data. */ protected function create_post_array( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) { $post = array( 'post_type' => self::POST_TYPE, 'post_title' => $action->get_hook(), 'post_content' => wp_json_encode( $action->get_args() ), 'post_status' => ( $action->is_finished() ? 'publish' : 'pending' ), 'post_date_gmt' => $this->get_scheduled_date_string( $action, $scheduled_date ), 'post_date' => $this->get_scheduled_date_string_local( $action, $scheduled_date ), ); return $post; } /** * Save post array. * * @param array $post_array Post array. * @return int Returns the post ID. * @throws RuntimeException Throws an exception if the action could not be saved. */ protected function save_post_array( $post_array ) { add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 ); $has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ); if ( $has_kses ) { // Prevent KSES from corrupting JSON in post_content. kses_remove_filters(); } $post_id = wp_insert_post( $post_array ); if ( $has_kses ) { kses_init_filters(); } remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 ); remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 ); if ( is_wp_error( $post_id ) || empty( $post_id ) ) { throw new RuntimeException( __( 'Unable to save action.', 'action-scheduler' ) ); } return $post_id; } /** * Filter insert post data. * * @param array $postdata Post data to filter. * * @return array */ public function filter_insert_post_data( $postdata ) { if ( self::POST_TYPE === $postdata['post_type'] ) { $postdata['post_author'] = 0; if ( 'future' === $postdata['post_status'] ) { $postdata['post_status'] = 'publish'; } } return $postdata; } /** * Create a (probably unique) post name for scheduled actions in a more performant manner than wp_unique_post_slug(). * * When an action's post status is transitioned to something other than 'draft', 'pending' or 'auto-draft, like 'publish' * or 'failed' or 'trash', WordPress will find a unique slug (stored in post_name column) using the wp_unique_post_slug() * function. This is done to ensure URL uniqueness. The approach taken by wp_unique_post_slug() is to iterate over existing * post_name values that match, and append a number 1 greater than the largest. This makes sense when manually creating a * post from the Edit Post screen. It becomes a bottleneck when automatically processing thousands of actions, with a * database containing thousands of related post_name values. * * WordPress 5.1 introduces the 'pre_wp_unique_post_slug' filter for plugins to address this issue. * * We can short-circuit WordPress's wp_unique_post_slug() approach using the 'pre_wp_unique_post_slug' filter. This * method is available to be used as a callback on that filter. It provides a more scalable approach to generating a * post_name/slug that is probably unique. Because Action Scheduler never actually uses the post_name field, or an * action's slug, being probably unique is good enough. * * For more backstory on this issue, see: * - https://github.com/woocommerce/action-scheduler/issues/44 and * - https://core.trac.wordpress.org/ticket/21112 * * @param string $override_slug Short-circuit return value. * @param string $slug The desired slug (post_name). * @param int $post_ID Post ID. * @param string $post_status The post status. * @param string $post_type Post type. * @return string */ public function set_unique_post_slug( $override_slug, $slug, $post_ID, $post_status, $post_type ) { if ( self::POST_TYPE === $post_type ) { $override_slug = uniqid( self::POST_TYPE . '-', true ) . '-' . wp_generate_password( 32, false ); } return $override_slug; } /** * Save post schedule. * * @param int $post_id Post ID of the scheduled action. * @param string $schedule Schedule to save. * * @return void */ protected function save_post_schedule( $post_id, $schedule ) { update_post_meta( $post_id, self::SCHEDULE_META_KEY, $schedule ); } /** * Save action group. * * @param int $post_id Post ID. * @param string $group Group to save. * @return void */ protected function save_action_group( $post_id, $group ) { if ( empty( $group ) ) { wp_set_object_terms( $post_id, array(), self::GROUP_TAXONOMY, false ); } else { wp_set_object_terms( $post_id, array( $group ), self::GROUP_TAXONOMY, false ); } } /** * Fetch actions. * * @param int $action_id Action ID. * @return object */ public function fetch_action( $action_id ) { $post = $this->get_post( $action_id ); if ( empty( $post ) || self::POST_TYPE !== $post->post_type ) { return $this->get_null_action(); } try { $action = $this->make_action_from_post( $post ); } catch ( ActionScheduler_InvalidActionException $exception ) { do_action( 'action_scheduler_failed_fetch_action', $post->ID, $exception ); return $this->get_null_action(); } return $action; } /** * Get post. * * @param string $action_id - Action ID. * @return WP_Post|null */ protected function get_post( $action_id ) { if ( empty( $action_id ) ) { return null; } return get_post( $action_id ); } /** * Get NULL action. * * @return ActionScheduler_NullAction */ protected function get_null_action() { return new ActionScheduler_NullAction(); } /** * Make action from post. * * @param WP_Post $post Post object. * @return WP_Post */ protected function make_action_from_post( $post ) { $hook = $post->post_title; $args = json_decode( $post->post_content, true ); $this->validate_args( $args, $post->ID ); $schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true ); $this->validate_schedule( $schedule, $post->ID ); $group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array( 'fields' => 'names' ) ); $group = empty( $group ) ? '' : reset( $group ); return ActionScheduler::factory()->get_stored_action( $this->get_action_status_by_post_status( $post->post_status ), $hook, $args, $schedule, $group ); } /** * Get action status by post status. * * @param string $post_status Post status. * * @throws InvalidArgumentException Throw InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels(). * @return string */ protected function get_action_status_by_post_status( $post_status ) { switch ( $post_status ) { case 'publish': $action_status = self::STATUS_COMPLETE; break; case 'trash': $action_status = self::STATUS_CANCELED; break; default: if ( ! array_key_exists( $post_status, $this->get_status_labels() ) ) { throw new InvalidArgumentException( sprintf( 'Invalid post status: "%s". No matching action status available.', $post_status ) ); } $action_status = $post_status; break; } return $action_status; } /** * Get post status by action status. * * @param string $action_status Action status. * * @throws InvalidArgumentException Throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels(). * @return string */ protected function get_post_status_by_action_status( $action_status ) { switch ( $action_status ) { case self::STATUS_COMPLETE: $post_status = 'publish'; break; case self::STATUS_CANCELED: $post_status = 'trash'; break; default: if ( ! array_key_exists( $action_status, $this->get_status_labels() ) ) { throw new InvalidArgumentException( sprintf( 'Invalid action status: "%s".', $action_status ) ); } $post_status = $action_status; break; } return $post_status; } /** * Returns the SQL statement to query (or count) actions. * * @param array $query - Filtering options. * @param string $select_or_count - Whether the SQL should select and return the IDs or just the row count. * * @throws InvalidArgumentException - Throw InvalidArgumentException if $select_or_count not count or select. * @return string SQL statement. The returned SQL is already properly escaped. */ protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) { if ( ! in_array( $select_or_count, array( 'select', 'count' ), true ) ) { throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) ); } $query = wp_parse_args( $query, array( 'hook' => '', 'args' => null, 'date' => null, 'date_compare' => '<=', 'modified' => null, 'modified_compare' => '<=', 'group' => '', 'status' => '', 'claimed' => null, 'per_page' => 5, 'offset' => 0, 'orderby' => 'date', 'order' => 'ASC', 'search' => '', ) ); /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; $sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID '; $sql .= "FROM {$wpdb->posts} p"; $sql_params = array(); if ( empty( $query['group'] ) && 'group' === $query['orderby'] ) { $sql .= " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID"; $sql .= " LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id"; $sql .= " LEFT JOIN {$wpdb->terms} t ON tt.term_id=t.term_id"; } elseif ( ! empty( $query['group'] ) ) { $sql .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID"; $sql .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id"; $sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id"; $sql .= ' AND t.slug=%s'; $sql_params[] = $query['group']; } $sql .= ' WHERE post_type=%s'; $sql_params[] = self::POST_TYPE; if ( $query['hook'] ) { $sql .= ' AND p.post_title=%s'; $sql_params[] = $query['hook']; } if ( ! is_null( $query['args'] ) ) { $sql .= ' AND p.post_content=%s'; $sql_params[] = wp_json_encode( $query['args'] ); } if ( $query['status'] ) { $post_statuses = array_map( array( $this, 'get_post_status_by_action_status' ), (array) $query['status'] ); $placeholders = array_fill( 0, count( $post_statuses ), '%s' ); $sql .= ' AND p.post_status IN (' . join( ', ', $placeholders ) . ')'; $sql_params = array_merge( $sql_params, array_values( $post_statuses ) ); } if ( $query['date'] instanceof DateTime ) { $date = clone $query['date']; $date->setTimezone( new DateTimeZone( 'UTC' ) ); $date_string = $date->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['date_compare'] ); $sql .= " AND p.post_date_gmt $comparator %s"; $sql_params[] = $date_string; } if ( $query['modified'] instanceof DateTime ) { $modified = clone $query['modified']; $modified->setTimezone( new DateTimeZone( 'UTC' ) ); $date_string = $modified->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['modified_compare'] ); $sql .= " AND p.post_modified_gmt $comparator %s"; $sql_params[] = $date_string; } if ( true === $query['claimed'] ) { $sql .= " AND p.post_password != ''"; } elseif ( false === $query['claimed'] ) { $sql .= " AND p.post_password = ''"; } elseif ( ! is_null( $query['claimed'] ) ) { $sql .= ' AND p.post_password = %s'; $sql_params[] = $query['claimed']; } if ( ! empty( $query['search'] ) ) { $sql .= ' AND (p.post_title LIKE %s OR p.post_content LIKE %s OR p.post_password LIKE %s)'; for ( $i = 0; $i < 3; $i++ ) { $sql_params[] = sprintf( '%%%s%%', $query['search'] ); } } if ( 'select' === $select_or_count ) { switch ( $query['orderby'] ) { case 'hook': $orderby = 'p.post_title'; break; case 'group': $orderby = 't.name'; break; case 'status': $orderby = 'p.post_status'; break; case 'modified': $orderby = 'p.post_modified'; break; case 'claim_id': $orderby = 'p.post_password'; break; case 'schedule': case 'date': default: $orderby = 'p.post_date_gmt'; break; } if ( 'ASC' === strtoupper( $query['order'] ) ) { $order = 'ASC'; } else { $order = 'DESC'; } $sql .= " ORDER BY $orderby $order"; if ( $query['per_page'] > 0 ) { $sql .= ' LIMIT %d, %d'; $sql_params[] = $query['offset']; $sql_params[] = $query['per_page']; } } return $wpdb->prepare( $sql, $sql_params ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Query for action count or list of action IDs. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @see ActionScheduler_Store::query_actions for $query arg usage. * * @param array $query Query filtering options. * @param string $query_type Whether to select or count the results. Defaults to select. * * @return string|array|null The IDs of actions matching the query. Null on failure. */ public function query_actions( $query = array(), $query_type = 'select' ) { /** * Global $wpdb object. * * @var wpdb $wpdb */ global $wpdb; $sql = $this->get_query_actions_sql( $query, $query_type ); return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared } /** * Get a count of all actions in the store, grouped by status * * @return array */ public function action_counts() { $action_counts_by_status = array(); $action_stati_and_labels = $this->get_status_labels(); $posts_count_by_status = (array) wp_count_posts( self::POST_TYPE, 'readable' ); foreach ( $posts_count_by_status as $post_status_name => $count ) { try { $action_status_name = $this->get_action_status_by_post_status( $post_status_name ); } catch ( Exception $e ) { // Ignore any post statuses that aren't for actions. continue; } if ( array_key_exists( $action_status_name, $action_stati_and_labels ) ) { $action_counts_by_status[ $action_status_name ] = $count; } } return $action_counts_by_status; } /** * Cancel action. * * @param int $action_id Action ID. * * @throws InvalidArgumentException If $action_id is not identified. */ public function cancel_action( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to cancel this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_canceled_action', $action_id ); add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 ); wp_trash_post( $action_id ); remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 ); } /** * Delete action. * * @param int $action_id Action ID. * @return void * @throws InvalidArgumentException If action is not identified. */ public function delete_action( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to delete this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_deleted_action', $action_id ); wp_delete_post( $action_id, true ); } /** * Get date for claim id. * * @param int $action_id Action ID. * @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran. */ public function get_date( $action_id ) { $next = $this->get_date_gmt( $action_id ); return ActionScheduler_TimezoneHelper::set_local_timezone( $next ); } /** * Get Date GMT. * * @param int $action_id Action ID. * * @throws InvalidArgumentException If $action_id is not identified. * @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran. */ public function get_date_gmt( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to determine the date of this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } if ( 'publish' === $post->post_status ) { return as_get_datetime_object( $post->post_modified_gmt ); } else { return as_get_datetime_object( $post->post_date_gmt ); } } /** * Stake claim. * * @param int $max_actions Maximum number of actions. * @param DateTime|null $before_date Jobs must be schedule before this date. Defaults to now. * @param array $hooks Claim only actions with a hook or hooks. * @param string $group Claim only actions in the given group. * * @return ActionScheduler_ActionClaim * @throws RuntimeException When there is an error staking a claim. * @throws InvalidArgumentException When the given group is not valid. */ public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ) { $this->claim_before_date = $before_date; $claim_id = $this->generate_claim_id(); $this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group ); $action_ids = $this->find_actions_by_claim_id( $claim_id ); $this->claim_before_date = null; return new ActionScheduler_ActionClaim( $claim_id, $action_ids ); } /** * Get claim count. * * @return int */ public function get_claim_count() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(DISTINCT post_password) FROM {$wpdb->posts} WHERE post_password != '' AND post_type = %s AND post_status IN ('in-progress','pending')", array( self::POST_TYPE ) ) ); } /** * Generate claim id. * * @return string */ protected function generate_claim_id() { $claim_id = md5( microtime( true ) . wp_rand( 0, 1000 ) ); return substr( $claim_id, 0, 20 ); // to fit in db field with 20 char limit. } /** * Claim actions. * * @param string $claim_id Claim ID. * @param int $limit Limit. * @param DateTime|null $before_date Should use UTC timezone. * @param array $hooks Claim only actions with a hook or hooks. * @param string $group Claim only actions in the given group. * * @return int The number of actions that were claimed. * @throws RuntimeException When there is a database error. */ protected function claim_actions( $claim_id, $limit, ?DateTime $before_date = null, $hooks = array(), $group = '' ) { // Set up initial variables. $date = null === $before_date ? as_get_datetime_object() : clone $before_date; $limit_ids = ! empty( $group ); $ids = $limit_ids ? $this->get_actions_by_group( $group, $limit, $date ) : array(); // If limiting by IDs and no posts found, then return early since we have nothing to update. if ( $limit_ids && 0 === count( $ids ) ) { return 0; } /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; /* * Build up custom query to update the affected posts. Parameters are built as a separate array * to make it easier to identify where they are in the query. * * We can't use $wpdb->update() here because of the "ID IN ..." clause. */ $update = "UPDATE {$wpdb->posts} SET post_password = %s, post_modified_gmt = %s, post_modified = %s"; $params = array( $claim_id, current_time( 'mysql', true ), current_time( 'mysql' ), ); // Build initial WHERE clause. $where = "WHERE post_type = %s AND post_status = %s AND post_password = ''"; $params[] = self::POST_TYPE; $params[] = ActionScheduler_Store::STATUS_PENDING; if ( ! empty( $hooks ) ) { $placeholders = array_fill( 0, count( $hooks ), '%s' ); $where .= ' AND post_title IN (' . join( ', ', $placeholders ) . ')'; $params = array_merge( $params, array_values( $hooks ) ); } /* * Add the IDs to the WHERE clause. IDs not escaped because they came directly from a prior DB query. * * If we're not limiting by IDs, then include the post_date_gmt clause. */ if ( $limit_ids ) { $where .= ' AND ID IN (' . join( ',', $ids ) . ')'; } else { $where .= ' AND post_date_gmt <= %s'; $params[] = $date->format( 'Y-m-d H:i:s' ); } // Add the ORDER BY clause and,ms limit. $order = 'ORDER BY menu_order ASC, post_date_gmt ASC, ID ASC LIMIT %d'; $params[] = $limit; // Run the query and gather results. $rows_affected = $wpdb->query( $wpdb->prepare( "{$update} {$where} {$order}", $params ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare if ( false === $rows_affected ) { throw new RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) ); } return (int) $rows_affected; } /** * Get IDs of actions within a certain group and up to a certain date/time. * * @param string $group The group to use in finding actions. * @param int $limit The number of actions to retrieve. * @param DateTime $date DateTime object representing cutoff time for actions. Actions retrieved will be * up to and including this DateTime. * * @return array IDs of actions in the appropriate group and before the appropriate time. * @throws InvalidArgumentException When the group does not exist. */ protected function get_actions_by_group( $group, $limit, DateTime $date ) { // Ensure the group exists before continuing. if ( ! term_exists( $group, self::GROUP_TAXONOMY ) ) { /* translators: %s is the group name */ throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) ); } // Set up a query for post IDs to use later. $query = new WP_Query(); $query_args = array( 'fields' => 'ids', 'post_type' => self::POST_TYPE, 'post_status' => ActionScheduler_Store::STATUS_PENDING, 'has_password' => false, 'posts_per_page' => $limit * 3, 'suppress_filters' => true, // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters 'no_found_rows' => true, 'orderby' => array( 'menu_order' => 'ASC', 'date' => 'ASC', 'ID' => 'ASC', ), 'date_query' => array( 'column' => 'post_date_gmt', 'before' => $date->format( 'Y-m-d H:i' ), 'inclusive' => true, ), 'tax_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery array( 'taxonomy' => self::GROUP_TAXONOMY, 'field' => 'slug', 'terms' => $group, 'include_children' => false, ), ), ); return $query->query( $query_args ); } /** * Find actions by claim ID. * * @param string $claim_id Claim ID. * @return array */ public function find_actions_by_claim_id( $claim_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; $action_ids = array(); $before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object(); $cut_off = $before_date->format( 'Y-m-d H:i:s' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s", array( self::POST_TYPE, $claim_id, ) ) ); // Verify that the scheduled date for each action is within the expected bounds (in some unusual // cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify). foreach ( $results as $claimed_action ) { if ( $claimed_action->post_date_gmt <= $cut_off ) { $action_ids[] = absint( $claimed_action->ID ); } } return $action_ids; } /** * Release pending actions from a 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 ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; $claim_id = $claim->get_id(); if ( trim( $claim_id ) === '' ) { // Verify that the claim_id is valid before attempting to release it. return; } // Only attempt to release pending actions to be claimed again. Running and complete actions are no longer relevant outside of admin/analytics. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $action_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s AND post_status = %s", self::POST_TYPE, $claim_id, self::STATUS_PENDING ) ); if ( empty( $action_ids ) ) { return; // nothing to do. } $action_id_string = implode( ',', array_map( 'intval', $action_ids ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID IN ($action_id_string) AND post_password = %s", //phpcs:ignore array( $claim->get_id(), ) ) ); if ( false === $result ) { /* translators: %s: claim ID */ throw new RuntimeException( sprintf( __( 'Unable to unlock claim %s. Database error.', 'action-scheduler' ), $claim->get_id() ) ); } } /** * Unclaim action. * * @param string $action_id Action ID. * @throws RuntimeException When unable to unlock claim on action ID. */ public function unclaim_action( $action_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID = %d AND post_type = %s", $action_id, self::POST_TYPE ) ); if ( false === $result ) { /* translators: %s: action ID */ throw new RuntimeException( sprintf( __( 'Unable to unlock claim on action %s. Database error.', 'action-scheduler' ), $action_id ) ); } } /** * Mark failure on action. * * @param int $action_id Action ID. * * @return void * @throws RuntimeException When unable to mark failure on action ID. */ public function mark_failure( $action_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $result = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type = %s", self::STATUS_FAILED, $action_id, self::POST_TYPE ) ); if ( false === $result ) { /* translators: %s: action ID */ throw new RuntimeException( sprintf( __( 'Unable to mark failure on action %s. Database error.', 'action-scheduler' ), $action_id ) ); } } /** * Return an action's claim ID, as stored in the post password column * * @param int $action_id Action ID. * @return mixed */ public function get_claim_id( $action_id ) { return $this->get_post_column( $action_id, 'post_password' ); } /** * Return an action's status, as stored in the post status column * * @param int $action_id Action ID. * * @return mixed * @throws InvalidArgumentException When the action ID is invalid. */ public function get_status( $action_id ) { $status = $this->get_post_column( $action_id, 'post_status' ); if ( null === $status ) { throw new InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) ); } return $this->get_action_status_by_post_status( $status ); } /** * Get post column * * @param string $action_id Action ID. * @param string $column_name Column Name. * * @return string|null */ private function get_post_column( $action_id, $column_name ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return $wpdb->get_var( $wpdb->prepare( "SELECT {$column_name} FROM {$wpdb->posts} WHERE ID=%d AND post_type=%s", // phpcs:ignore $action_id, self::POST_TYPE ) ); } /** * Log Execution. * * @throws Exception If the action status cannot be updated to self::STATUS_RUNNING ('in-progress'). * * @param string $action_id Action ID. */ public function log_execution( $action_id ) { /** * Global wpdb object. * * @var wpdb $wpdb */ global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $status_updated = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET menu_order = menu_order+1, post_status=%s, post_modified_gmt = %s, post_modified = %s WHERE ID = %d AND post_type = %s", self::STATUS_RUNNING, current_time( 'mysql', true ), current_time( 'mysql' ), $action_id, self::POST_TYPE ) ); if ( ! $status_updated ) { throw new Exception( sprintf( /* translators: 1: action ID. 2: status slug. */ __( 'Unable to update the status of action %1$d to %2$s.', 'action-scheduler' ), $action_id, self::STATUS_RUNNING ) ); } } /** * Record that an action was completed. * * @param string $action_id ID of the completed action. * * @throws InvalidArgumentException When the action ID is invalid. * @throws RuntimeException When there was an error executing the action. */ public function mark_complete( $action_id ) { $post = get_post( $action_id ); if ( empty( $post ) || ( self::POST_TYPE !== $post->post_type ) ) { /* translators: %s is the action ID */ throw new InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having completed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 ); $result = wp_update_post( array( 'ID' => $action_id, 'post_status' => 'publish', ), true ); remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 ); remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 ); if ( is_wp_error( $result ) ) { throw new RuntimeException( $result->get_error_message() ); } /** * Fires after a scheduled action has been completed. * * @since 3.4.2 * * @param int $action_id Action ID. */ do_action( 'action_scheduler_completed_action', $action_id ); } /** * Mark action as migrated when there is an error deleting the action. * * @param int $action_id Action ID. */ public function mark_migrated( $action_id ) { wp_update_post( array( 'ID' => $action_id, 'post_status' => 'migrated', ) ); } /** * Determine whether the post store can be migrated. * * @param [type] $setting - Setting value. * @return bool */ public function migration_dependencies_met( $setting ) { global $wpdb; $dependencies_met = get_transient( self::DEPENDENCIES_MET ); if ( empty( $dependencies_met ) ) { $maximum_args_length = apply_filters( 'action_scheduler_maximum_args_length', 191 ); $found_action = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND CHAR_LENGTH(post_content) > %d LIMIT 1", $maximum_args_length, self::POST_TYPE ) ); $dependencies_met = $found_action ? 'no' : 'yes'; set_transient( self::DEPENDENCIES_MET, $dependencies_met, DAY_IN_SECONDS ); } return 'yes' === $dependencies_met ? $setting : false; } /** * InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4. * * Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However, * as we prepare to move to custom tables, and can use an indexed VARCHAR column instead, we want to warn * developers of this impending requirement. * * @param ActionScheduler_Action $action Action object. */ protected function validate_action( ActionScheduler_Action $action ) { try { parent::validate_action( $action ); } catch ( Exception $e ) { /* translators: %s is the error message */ $message = sprintf( __( '%s Support for strings longer than this will be removed in a future version.', 'action-scheduler' ), $e->getMessage() ); _doing_it_wrong( 'ActionScheduler_Action::$args', esc_html( $message ), '2.1.0' ); } } /** * (@codeCoverageIgnore) */ public function init() { add_filter( 'action_scheduler_migration_dependencies_met', array( $this, 'migration_dependencies_met' ) ); $post_type_registrar = new ActionScheduler_wpPostStore_PostTypeRegistrar(); $post_type_registrar->register(); $post_status_registrar = new ActionScheduler_wpPostStore_PostStatusRegistrar(); $post_status_registrar->register(); $taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar(); $taxonomy_registrar->register(); } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_DBLogger.php 0000644 00000010620 15151523433 0023472 0 ustar 00 <?php /** * Class ActionScheduler_DBLogger * * Action logs data table data store. * * @since 3.0.0 */ class ActionScheduler_DBLogger extends ActionScheduler_Logger { /** * Add a record to an action log. * * @param int $action_id Action ID. * @param string $message Message to be saved in the log entry. * @param DateTime|null $date Timestamp of the log entry. * * @return int The log entry ID. */ public function log( $action_id, $message, ?DateTime $date = null ) { if ( empty( $date ) ) { $date = as_get_datetime_object(); } else { $date = clone $date; } $date_gmt = $date->format( 'Y-m-d H:i:s' ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); $date_local = $date->format( 'Y-m-d H:i:s' ); /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $wpdb->insert( $wpdb->actionscheduler_logs, array( 'action_id' => $action_id, 'message' => $message, 'log_date_gmt' => $date_gmt, 'log_date_local' => $date_local, ), array( '%d', '%s', '%s', '%s' ) ); return $wpdb->insert_id; } /** * Retrieve an action log entry. * * @param int $entry_id Log entry ID. * * @return ActionScheduler_LogEntry */ public function get_entry( $entry_id ) { /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $entry = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE log_id=%d", $entry_id ) ); return $this->create_entry_from_db_record( $entry ); } /** * Create an action log entry from a database record. * * @param object $record Log entry database record object. * * @return ActionScheduler_LogEntry */ private function create_entry_from_db_record( $record ) { if ( empty( $record ) ) { return new ActionScheduler_NullLogEntry(); } if ( is_null( $record->log_date_gmt ) ) { $date = as_get_datetime_object( ActionScheduler_StoreSchema::DEFAULT_DATE ); } else { $date = as_get_datetime_object( $record->log_date_gmt ); } return new ActionScheduler_LogEntry( $record->action_id, $record->message, $date ); } /** * Retrieve an action's log entries from the database. * * @param int $action_id Action ID. * * @return ActionScheduler_LogEntry[] */ public function get_logs( $action_id ) { /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $records = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE action_id=%d", $action_id ) ); return array_map( array( $this, 'create_entry_from_db_record' ), $records ); } /** * Initialize the data store. * * @codeCoverageIgnore */ public function init() { $table_maker = new ActionScheduler_LoggerSchema(); $table_maker->init(); $table_maker->register_tables(); parent::init(); add_action( 'action_scheduler_deleted_action', array( $this, 'clear_deleted_action_logs' ), 10, 1 ); } /** * Delete the action logs for an action. * * @param int $action_id Action ID. */ public function clear_deleted_action_logs( $action_id ) { /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $wpdb->delete( $wpdb->actionscheduler_logs, array( 'action_id' => $action_id ), array( '%d' ) ); } /** * Bulk add cancel action log entries. * * @param array $action_ids List of action ID. */ public function bulk_log_cancel_actions( $action_ids ) { if ( empty( $action_ids ) ) { return; } /** @var \wpdb $wpdb */ //phpcs:ignore Generic.Commenting.DocComment.MissingShort global $wpdb; $date = as_get_datetime_object(); $date_gmt = $date->format( 'Y-m-d H:i:s' ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); $date_local = $date->format( 'Y-m-d H:i:s' ); $message = __( 'action canceled', 'action-scheduler' ); $format = '(%d, ' . $wpdb->prepare( '%s, %s, %s', $message, $date_gmt, $date_local ) . ')'; $sql_query = "INSERT {$wpdb->actionscheduler_logs} (action_id, message, log_date_gmt, log_date_local) VALUES "; $value_rows = array(); foreach ( $action_ids as $action_id ) { $value_rows[] = $wpdb->prepare( $format, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } $sql_query .= implode( ',', $value_rows ); $wpdb->query( $sql_query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php 0000644 00000017033 15151523433 0025163 0 ustar 00 <?php /** * Class ActionScheduler_wpCommentLogger */ class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger { const AGENT = 'ActionScheduler'; const TYPE = 'action_log'; /** * Create log entry. * * @param string $action_id Action ID. * @param string $message Action log's message. * @param DateTime|null $date Action log's timestamp. * * @return string The log entry ID */ public function log( $action_id, $message, ?DateTime $date = null ) { if ( empty( $date ) ) { $date = as_get_datetime_object(); } else { $date = as_get_datetime_object( clone $date ); } $comment_id = $this->create_wp_comment( $action_id, $message, $date ); return $comment_id; } /** * Create comment. * * @param int $action_id Action ID. * @param string $message Action log's message. * @param DateTime $date Action log entry's timestamp. */ protected function create_wp_comment( $action_id, $message, DateTime $date ) { $comment_date_gmt = $date->format( 'Y-m-d H:i:s' ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); $comment_data = array( 'comment_post_ID' => $action_id, 'comment_date' => $date->format( 'Y-m-d H:i:s' ), 'comment_date_gmt' => $comment_date_gmt, 'comment_author' => self::AGENT, 'comment_content' => $message, 'comment_agent' => self::AGENT, 'comment_type' => self::TYPE, ); return wp_insert_comment( $comment_data ); } /** * Get single log entry for action. * * @param string $entry_id Entry ID. * * @return ActionScheduler_LogEntry */ public function get_entry( $entry_id ) { $comment = $this->get_comment( $entry_id ); if ( empty( $comment ) || self::TYPE !== $comment->comment_type ) { return new ActionScheduler_NullLogEntry(); } $date = as_get_datetime_object( $comment->comment_date_gmt ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $date ); } /** * Get action's logs. * * @param string $action_id Action ID. * * @return ActionScheduler_LogEntry[] */ public function get_logs( $action_id ) { $status = 'all'; $logs = array(); if ( get_post_status( $action_id ) === 'trash' ) { $status = 'post-trashed'; } $comments = get_comments( array( 'post_id' => $action_id, 'orderby' => 'comment_date_gmt', 'order' => 'ASC', 'type' => self::TYPE, 'status' => $status, ) ); foreach ( $comments as $c ) { $entry = $this->get_entry( $c ); if ( ! empty( $entry ) ) { $logs[] = $entry; } } return $logs; } /** * Get comment. * * @param int $comment_id Comment ID. */ protected function get_comment( $comment_id ) { return get_comment( $comment_id ); } /** * Filter comment queries. * * @param WP_Comment_Query $query Comment query object. */ public function filter_comment_queries( $query ) { foreach ( array( 'ID', 'parent', 'post_author', 'post_name', 'post_parent', 'type', 'post_type', 'post_id', 'post_ID' ) as $key ) { if ( ! empty( $query->query_vars[ $key ] ) ) { return; // don't slow down queries that wouldn't include action_log comments anyway. } } $query->query_vars['action_log_filter'] = true; add_filter( 'comments_clauses', array( $this, 'filter_comment_query_clauses' ), 10, 2 ); } /** * Filter comment queries. * * @param array $clauses Query's clauses. * @param WP_Comment_Query $query Query object. * * @return array */ public function filter_comment_query_clauses( $clauses, $query ) { if ( ! empty( $query->query_vars['action_log_filter'] ) ) { $clauses['where'] .= $this->get_where_clause(); } return $clauses; } /** * Make sure Action Scheduler logs are excluded from comment feeds, which use WP_Query, not * the WP_Comment_Query class handled by @see self::filter_comment_queries(). * * @param string $where Query's `where` clause. * @param WP_Query $query Query object. * * @return string */ public function filter_comment_feed( $where, $query ) { if ( is_comment_feed() ) { $where .= $this->get_where_clause(); } return $where; } /** * Return a SQL clause to exclude Action Scheduler comments. * * @return string */ protected function get_where_clause() { global $wpdb; return sprintf( " AND {$wpdb->comments}.comment_type != '%s'", self::TYPE ); } /** * Remove action log entries from wp_count_comments() * * @param array $stats Comment count. * @param int $post_id Post ID. * * @return object */ public function filter_comment_count( $stats, $post_id ) { global $wpdb; if ( 0 === $post_id ) { $stats = $this->get_comment_count(); } return $stats; } /** * Retrieve the comment counts from our cache, or the database if the cached version isn't set. * * @return object */ protected function get_comment_count() { global $wpdb; $stats = get_transient( 'as_comment_count' ); if ( ! $stats ) { $stats = array(); $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} WHERE comment_type NOT IN('order_note','action_log') GROUP BY comment_approved", ARRAY_A ); $total = 0; $stats = array(); $approved = array( '0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed', ); foreach ( (array) $count as $row ) { // Don't count post-trashed toward totals. if ( 'post-trashed' !== $row['comment_approved'] && 'trash' !== $row['comment_approved'] ) { $total += $row['num_comments']; } if ( isset( $approved[ $row['comment_approved'] ] ) ) { $stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments']; } } $stats['total_comments'] = $total; $stats['all'] = $total; foreach ( $approved as $key ) { if ( empty( $stats[ $key ] ) ) { $stats[ $key ] = 0; } } $stats = (object) $stats; set_transient( 'as_comment_count', $stats ); } return $stats; } /** * Delete comment count cache whenever there is new comment or the status of a comment changes. Cache * will be regenerated next time ActionScheduler_wpCommentLogger::filter_comment_count() is called. */ public function delete_comment_count_cache() { delete_transient( 'as_comment_count' ); } /** * Initialize. * * @codeCoverageIgnore */ public function init() { add_action( 'action_scheduler_before_process_queue', array( $this, 'disable_comment_counting' ), 10, 0 ); add_action( 'action_scheduler_after_process_queue', array( $this, 'enable_comment_counting' ), 10, 0 ); parent::init(); add_action( 'pre_get_comments', array( $this, 'filter_comment_queries' ), 10, 1 ); add_action( 'wp_count_comments', array( $this, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs. add_action( 'comment_feed_where', array( $this, 'filter_comment_feed' ), 10, 2 ); // Delete comments count cache whenever there is a new comment or a comment status changes. add_action( 'wp_insert_comment', array( $this, 'delete_comment_count_cache' ) ); add_action( 'wp_set_comment_status', array( $this, 'delete_comment_count_cache' ) ); } /** * Defer comment counting. */ public function disable_comment_counting() { wp_defer_comment_counting( true ); } /** * Enable comment counting. */ public function enable_comment_counting() { wp_defer_comment_counting( false ); } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_DBStore.php 0000644 00000120321 15151523433 0023347 0 ustar 00 <?php /** * Class ActionScheduler_DBStore * * Action data table data store. * * @since 3.0.0 */ class ActionScheduler_DBStore extends ActionScheduler_Store { /** * Used to share information about the before_date property of claims internally. * * This is used in preference to passing the same information as a method param * for backwards-compatibility reasons. * * @var DateTime|null */ private $claim_before_date = null; /** * Maximum length of args. * * @var int */ protected static $max_args_length = 8000; /** * Maximum length of index. * * @var int */ protected static $max_index_length = 191; /** * List of claim filters. * * @var array */ protected $claim_filters = array( 'group' => '', 'hooks' => '', 'exclude-groups' => '', ); /** * Initialize the data store * * @codeCoverageIgnore */ public function init() { $table_maker = new ActionScheduler_StoreSchema(); $table_maker->init(); $table_maker->register_tables(); } /** * Save an action, checks if this is a unique action before actually saving. * * @param ActionScheduler_Action $action Action object. * @param DateTime|null $scheduled_date Optional schedule date. Default null. * * @return int Action ID. * @throws RuntimeException Throws exception when saving the action fails. */ public function save_unique_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) { return $this->save_action_to_db( $action, $scheduled_date, true ); } /** * Save an action. Can save duplicate action as well, prefer using `save_unique_action` instead. * * @param ActionScheduler_Action $action Action object. * @param DateTime|null $scheduled_date Optional schedule date. Default null. * * @return int Action ID. * @throws RuntimeException Throws exception when saving the action fails. */ public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) { return $this->save_action_to_db( $action, $scheduled_date, false ); } /** * Save an action. * * @param ActionScheduler_Action $action Action object. * @param ?DateTime $date Optional schedule date. Default null. * @param bool $unique Whether the action should be unique. * * @return int Action ID. * @throws \RuntimeException Throws exception when saving the action fails. */ private function save_action_to_db( ActionScheduler_Action $action, ?DateTime $date = null, $unique = false ) { global $wpdb; try { $this->validate_action( $action ); $data = array( 'hook' => $action->get_hook(), 'status' => ( $action->is_finished() ? self::STATUS_COMPLETE : self::STATUS_PENDING ), 'scheduled_date_gmt' => $this->get_scheduled_date_string( $action, $date ), 'scheduled_date_local' => $this->get_scheduled_date_string_local( $action, $date ), 'schedule' => serialize( $action->get_schedule() ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize 'group_id' => current( $this->get_group_ids( $action->get_group() ) ), 'priority' => $action->get_priority(), ); $args = wp_json_encode( $action->get_args() ); if ( strlen( $args ) <= static::$max_index_length ) { $data['args'] = $args; } else { $data['args'] = $this->hash_args( $args ); $data['extended_args'] = $args; } $insert_sql = $this->build_insert_sql( $data, $unique ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $insert_sql should be already prepared. $wpdb->query( $insert_sql ); $action_id = $wpdb->insert_id; if ( is_wp_error( $action_id ) ) { throw new \RuntimeException( $action_id->get_error_message() ); } elseif ( empty( $action_id ) ) { if ( $unique ) { return 0; } throw new \RuntimeException( $wpdb->last_error ? $wpdb->last_error : __( 'Database error.', 'action-scheduler' ) ); } do_action( 'action_scheduler_stored_action', $action_id ); return $action_id; } catch ( \Exception $e ) { /* translators: %s: error message */ throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 ); } } /** * Helper function to build insert query. * * @param array $data Row data for action. * @param bool $unique Whether the action should be unique. * * @return string Insert query. */ private function build_insert_sql( array $data, $unique ) { global $wpdb; $columns = array_keys( $data ); $values = array_values( $data ); $placeholders = array_map( array( $this, 'get_placeholder_for_column' ), $columns ); $table_name = ! empty( $wpdb->actionscheduler_actions ) ? $wpdb->actionscheduler_actions : $wpdb->prefix . 'actionscheduler_actions'; $column_sql = '`' . implode( '`, `', $columns ) . '`'; $placeholder_sql = implode( ', ', $placeholders ); $where_clause = $this->build_where_clause_for_insert( $data, $table_name, $unique ); // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $column_sql and $where_clause are already prepared. $placeholder_sql is hardcoded. $insert_query = $wpdb->prepare( " INSERT INTO $table_name ( $column_sql ) SELECT $placeholder_sql FROM DUAL WHERE ( $where_clause ) IS NULL", $values ); // phpcs:enable return $insert_query; } /** * Helper method to build where clause for action insert statement. * * @param array $data Row data for action. * @param string $table_name Action table name. * @param bool $unique Where action should be unique. * * @return string Where clause to be used with insert. */ private function build_where_clause_for_insert( $data, $table_name, $unique ) { global $wpdb; if ( ! $unique ) { return 'SELECT NULL FROM DUAL'; } $pending_statuses = array( ActionScheduler_Store::STATUS_PENDING, ActionScheduler_Store::STATUS_RUNNING, ); $pending_status_placeholders = implode( ', ', array_fill( 0, count( $pending_statuses ), '%s' ) ); // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $pending_status_placeholders is hardcoded. $where_clause = $wpdb->prepare( " SELECT action_id FROM $table_name WHERE status IN ( $pending_status_placeholders ) AND hook = %s AND `group_id` = %d ", array_merge( $pending_statuses, array( $data['hook'], $data['group_id'], ) ) ); // phpcs:enable return "$where_clause" . ' LIMIT 1'; } /** * Helper method to get $wpdb->prepare placeholder for a given column name. * * @param string $column_name Name of column in actions table. * * @return string Placeholder to use for given column. */ private function get_placeholder_for_column( $column_name ) { $string_columns = array( 'hook', 'status', 'scheduled_date_gmt', 'scheduled_date_local', 'args', 'schedule', 'last_attempt_gmt', 'last_attempt_local', 'extended_args', ); return in_array( $column_name, $string_columns, true ) ? '%s' : '%d'; } /** * Generate a hash from json_encoded $args using MD5 as this isn't for security. * * @param string $args JSON encoded action args. * @return string */ protected function hash_args( $args ) { return md5( $args ); } /** * Get action args query param value from action args. * * @param array $args Action args. * @return string */ protected function get_args_for_query( $args ) { $encoded = wp_json_encode( $args ); if ( strlen( $encoded ) <= static::$max_index_length ) { return $encoded; } return $this->hash_args( $encoded ); } /** * Get a group's ID based on its name/slug. * * @param string|array $slugs The string name of a group, or names for several groups. * @param bool $create_if_not_exists Whether to create the group if it does not already exist. Default, true - create the group. * * @return array The group IDs, if they exist or were successfully created. May be empty. */ protected function get_group_ids( $slugs, $create_if_not_exists = true ) { $slugs = (array) $slugs; $group_ids = array(); if ( empty( $slugs ) ) { return array(); } /** * Global. * * @var \wpdb $wpdb */ global $wpdb; foreach ( $slugs as $slug ) { $group_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT group_id FROM {$wpdb->actionscheduler_groups} WHERE slug=%s", $slug ) ); if ( empty( $group_id ) && $create_if_not_exists ) { $group_id = $this->create_group( $slug ); } if ( $group_id ) { $group_ids[] = $group_id; } } return $group_ids; } /** * Create an action group. * * @param string $slug Group slug. * * @return int Group ID. */ protected function create_group( $slug ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $wpdb->insert( $wpdb->actionscheduler_groups, array( 'slug' => $slug ) ); return (int) $wpdb->insert_id; } /** * Retrieve an action. * * @param int $action_id Action ID. * * @return ActionScheduler_Action */ public function fetch_action( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $data = $wpdb->get_row( $wpdb->prepare( "SELECT a.*, g.slug AS `group` FROM {$wpdb->actionscheduler_actions} a LEFT JOIN {$wpdb->actionscheduler_groups} g ON a.group_id=g.group_id WHERE a.action_id=%d", $action_id ) ); if ( empty( $data ) ) { return $this->get_null_action(); } if ( ! empty( $data->extended_args ) ) { $data->args = $data->extended_args; unset( $data->extended_args ); } // Convert NULL dates to zero dates. $date_fields = array( 'scheduled_date_gmt', 'scheduled_date_local', 'last_attempt_gmt', 'last_attempt_gmt', ); foreach ( $date_fields as $date_field ) { if ( is_null( $data->$date_field ) ) { $data->$date_field = ActionScheduler_StoreSchema::DEFAULT_DATE; } } try { $action = $this->make_action_from_db_record( $data ); } catch ( ActionScheduler_InvalidActionException $exception ) { do_action( 'action_scheduler_failed_fetch_action', $action_id, $exception ); return $this->get_null_action(); } return $action; } /** * Create a null action. * * @return ActionScheduler_NullAction */ protected function get_null_action() { return new ActionScheduler_NullAction(); } /** * Create an action from a database record. * * @param object $data Action database record. * * @return ActionScheduler_Action|ActionScheduler_CanceledAction|ActionScheduler_FinishedAction */ protected function make_action_from_db_record( $data ) { $hook = $data->hook; $args = json_decode( $data->args, true ); $schedule = unserialize( $data->schedule ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize $this->validate_args( $args, $data->action_id ); $this->validate_schedule( $schedule, $data->action_id ); if ( empty( $schedule ) ) { $schedule = new ActionScheduler_NullSchedule(); } $group = $data->group ? $data->group : ''; return ActionScheduler::factory()->get_stored_action( $data->status, $data->hook, $args, $schedule, $group, $data->priority ); } /** * Returns the SQL statement to query (or count) actions. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @param array $query Filtering options. * @param string $select_or_count Whether the SQL should select and return the IDs or just the row count. * * @return string SQL statement already properly escaped. * @throws \InvalidArgumentException If the query is invalid. * @throws \RuntimeException When "unknown partial args matching value". */ protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) { if ( ! in_array( $select_or_count, array( 'select', 'count' ), true ) ) { throw new InvalidArgumentException( __( 'Invalid value for select or count parameter. Cannot query actions.', 'action-scheduler' ) ); } $query = wp_parse_args( $query, array( 'hook' => '', 'args' => null, 'partial_args_matching' => 'off', // can be 'like' or 'json'. 'date' => null, 'date_compare' => '<=', 'modified' => null, 'modified_compare' => '<=', 'group' => '', 'status' => '', 'claimed' => null, 'per_page' => 5, 'offset' => 0, 'orderby' => 'date', 'order' => 'ASC', ) ); /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $db_server_info = is_callable( array( $wpdb, 'db_server_info' ) ) ? $wpdb->db_server_info() : $wpdb->db_version(); if ( false !== strpos( $db_server_info, 'MariaDB' ) ) { $supports_json = version_compare( PHP_VERSION_ID >= 80016 ? $wpdb->db_version() : preg_replace( '/[^0-9.].*/', '', str_replace( '5.5.5-', '', $db_server_info ) ), '10.2', '>=' ); } else { $supports_json = version_compare( $wpdb->db_version(), '5.7', '>=' ); } $sql = ( 'count' === $select_or_count ) ? 'SELECT count(a.action_id)' : 'SELECT a.action_id'; $sql .= " FROM {$wpdb->actionscheduler_actions} a"; $sql_params = array(); if ( ! empty( $query['group'] ) || 'group' === $query['orderby'] ) { $sql .= " LEFT JOIN {$wpdb->actionscheduler_groups} g ON g.group_id=a.group_id"; } $sql .= ' WHERE 1=1'; if ( ! empty( $query['group'] ) ) { $sql .= ' AND g.slug=%s'; $sql_params[] = $query['group']; } if ( ! empty( $query['hook'] ) ) { $sql .= ' AND a.hook=%s'; $sql_params[] = $query['hook']; } if ( ! is_null( $query['args'] ) ) { switch ( $query['partial_args_matching'] ) { case 'json': if ( ! $supports_json ) { throw new \RuntimeException( __( 'JSON partial matching not supported in your environment. Please check your MySQL/MariaDB version.', 'action-scheduler' ) ); } $supported_types = array( 'integer' => '%d', 'boolean' => '%s', 'double' => '%f', 'string' => '%s', ); foreach ( $query['args'] as $key => $value ) { $value_type = gettype( $value ); if ( 'boolean' === $value_type ) { $value = $value ? 'true' : 'false'; } $placeholder = isset( $supported_types[ $value_type ] ) ? $supported_types[ $value_type ] : false; if ( ! $placeholder ) { throw new \RuntimeException( sprintf( /* translators: %s: provided value type */ __( 'The value type for the JSON partial matching is not supported. Must be either integer, boolean, double or string. %s type provided.', 'action-scheduler' ), $value_type ) ); } $sql .= ' AND JSON_EXTRACT(a.args, %s)=' . $placeholder; $sql_params[] = '$.' . $key; $sql_params[] = $value; } break; case 'like': foreach ( $query['args'] as $key => $value ) { $sql .= ' AND a.args LIKE %s'; $json_partial = $wpdb->esc_like( trim( wp_json_encode( array( $key => $value ) ), '{}' ) ); $sql_params[] = "%{$json_partial}%"; } break; case 'off': $sql .= ' AND a.args=%s'; $sql_params[] = $this->get_args_for_query( $query['args'] ); break; default: throw new \RuntimeException( __( 'Unknown partial args matching value.', 'action-scheduler' ) ); } } if ( $query['status'] ) { $statuses = (array) $query['status']; $placeholders = array_fill( 0, count( $statuses ), '%s' ); $sql .= ' AND a.status IN (' . join( ', ', $placeholders ) . ')'; $sql_params = array_merge( $sql_params, array_values( $statuses ) ); } if ( $query['date'] instanceof \DateTime ) { $date = clone $query['date']; $date->setTimezone( new \DateTimeZone( 'UTC' ) ); $date_string = $date->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['date_compare'] ); $sql .= " AND a.scheduled_date_gmt $comparator %s"; $sql_params[] = $date_string; } if ( $query['modified'] instanceof \DateTime ) { $modified = clone $query['modified']; $modified->setTimezone( new \DateTimeZone( 'UTC' ) ); $date_string = $modified->format( 'Y-m-d H:i:s' ); $comparator = $this->validate_sql_comparator( $query['modified_compare'] ); $sql .= " AND a.last_attempt_gmt $comparator %s"; $sql_params[] = $date_string; } if ( true === $query['claimed'] ) { $sql .= ' AND a.claim_id != 0'; } elseif ( false === $query['claimed'] ) { $sql .= ' AND a.claim_id = 0'; } elseif ( ! is_null( $query['claimed'] ) ) { $sql .= ' AND a.claim_id = %d'; $sql_params[] = $query['claimed']; } if ( ! empty( $query['search'] ) ) { $sql .= ' AND (a.hook LIKE %s OR (a.extended_args IS NULL AND a.args LIKE %s) OR a.extended_args LIKE %s'; for ( $i = 0; $i < 3; $i++ ) { $sql_params[] = sprintf( '%%%s%%', $query['search'] ); } $search_claim_id = (int) $query['search']; if ( $search_claim_id ) { $sql .= ' OR a.claim_id = %d'; $sql_params[] = $search_claim_id; } $sql .= ')'; } if ( 'select' === $select_or_count ) { if ( 'ASC' === strtoupper( $query['order'] ) ) { $order = 'ASC'; } else { $order = 'DESC'; } switch ( $query['orderby'] ) { case 'hook': $sql .= " ORDER BY a.hook $order"; break; case 'group': $sql .= " ORDER BY g.slug $order"; break; case 'modified': $sql .= " ORDER BY a.last_attempt_gmt $order"; break; case 'none': break; case 'action_id': $sql .= " ORDER BY a.action_id $order"; break; case 'date': default: $sql .= " ORDER BY a.scheduled_date_gmt $order"; break; } if ( $query['per_page'] > 0 ) { $sql .= ' LIMIT %d, %d'; $sql_params[] = $query['offset']; $sql_params[] = $query['per_page']; } } if ( ! empty( $sql_params ) ) { $sql = $wpdb->prepare( $sql, $sql_params ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } return $sql; } /** * Query for action count or list of action IDs. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @see ActionScheduler_Store::query_actions for $query arg usage. * * @param array $query Query filtering options. * @param string $query_type Whether to select or count the results. Defaults to select. * * @return string|array|null The IDs of actions matching the query. Null on failure. */ public function query_actions( $query = array(), $query_type = 'select' ) { /** * Global. * * @var wpdb $wpdb */ global $wpdb; $sql = $this->get_query_actions_sql( $query, $query_type ); return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.NoSql, WordPress.DB.DirectDatabaseQuery.NoCaching } /** * Get a count of all actions in the store, grouped by status. * * @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status. */ public function action_counts() { global $wpdb; $sql = "SELECT a.status, count(a.status) as 'count'"; $sql .= " FROM {$wpdb->actionscheduler_actions} a"; $sql .= ' GROUP BY a.status'; $actions_count_by_status = array(); $action_stati_and_labels = $this->get_status_labels(); foreach ( $wpdb->get_results( $sql ) as $action_data ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared // Ignore any actions with invalid status. if ( array_key_exists( $action_data->status, $action_stati_and_labels ) ) { $actions_count_by_status[ $action_data->status ] = $action_data->count; } } return $actions_count_by_status; } /** * Cancel an action. * * @param int $action_id Action ID. * * @return void * @throws \InvalidArgumentException If the action update failed. */ public function cancel_action( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $updated = $wpdb->update( $wpdb->actionscheduler_actions, array( 'status' => self::STATUS_CANCELED ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); if ( false === $updated ) { /* translators: %s: action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to cancel this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_canceled_action', $action_id ); } /** * Cancel pending actions by hook. * * @since 3.0.0 * * @param string $hook Hook name. * * @return void */ public function cancel_actions_by_hook( $hook ) { $this->bulk_cancel_actions( array( 'hook' => $hook ) ); } /** * Cancel pending actions by group. * * @param string $group Group slug. * * @return void */ public function cancel_actions_by_group( $group ) { $this->bulk_cancel_actions( array( 'group' => $group ) ); } /** * Bulk cancel actions. * * @since 3.0.0 * * @param array $query_args Query parameters. */ protected function bulk_cancel_actions( $query_args ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; if ( ! is_array( $query_args ) ) { return; } // Don't cancel actions that are already canceled. if ( isset( $query_args['status'] ) && self::STATUS_CANCELED === $query_args['status'] ) { return; } $action_ids = true; $query_args = wp_parse_args( $query_args, array( 'per_page' => 1000, 'status' => self::STATUS_PENDING, 'orderby' => 'none', ) ); while ( $action_ids ) { $action_ids = $this->query_actions( $query_args ); if ( empty( $action_ids ) ) { break; } $format = array_fill( 0, count( $action_ids ), '%d' ); $query_in = '(' . implode( ',', $format ) . ')'; $parameters = $action_ids; array_unshift( $parameters, self::STATUS_CANCELED ); $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->actionscheduler_actions} SET status = %s WHERE action_id IN {$query_in}", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $parameters ) ); do_action( 'action_scheduler_bulk_cancel_actions', $action_ids ); } } /** * Delete an action. * * @param int $action_id Action ID. * @throws \InvalidArgumentException If the action deletion failed. */ public function delete_action( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $deleted = $wpdb->delete( $wpdb->actionscheduler_actions, array( 'action_id' => $action_id ), array( '%d' ) ); if ( empty( $deleted ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to delete this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } do_action( 'action_scheduler_deleted_action', $action_id ); } /** * Get the schedule date for an action. * * @param string $action_id Action ID. * * @return \DateTime The local date the action is scheduled to run, or the date that it ran. */ public function get_date( $action_id ) { $date = $this->get_date_gmt( $action_id ); ActionScheduler_TimezoneHelper::set_local_timezone( $date ); return $date; } /** * Get the GMT schedule date for an action. * * @param int $action_id Action ID. * * @throws \InvalidArgumentException If action cannot be identified. * @return \DateTime The GMT date the action is scheduled to run, or the date that it ran. */ protected function get_date_gmt( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $record = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d", $action_id ) ); if ( empty( $record ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to determine the date of this action. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } if ( self::STATUS_PENDING === $record->status ) { return as_get_datetime_object( $record->scheduled_date_gmt ); } else { return as_get_datetime_object( $record->last_attempt_gmt ); } } /** * Stake a claim on actions. * * @param int $max_actions Maximum number of action to include in claim. * @param DateTime|null $before_date Jobs must be schedule before this date. Defaults to now. * @param array $hooks Hooks to filter for. * @param string $group Group to filter for. * * @return ActionScheduler_ActionClaim */ public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ) { $claim_id = $this->generate_claim_id(); $this->claim_before_date = $before_date; $this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group ); $action_ids = $this->find_actions_by_claim_id( $claim_id ); $this->claim_before_date = null; return new ActionScheduler_ActionClaim( $claim_id, $action_ids ); } /** * Generate a new action claim. * * @return int Claim ID. */ protected function generate_claim_id() { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $now = as_get_datetime_object(); $wpdb->insert( $wpdb->actionscheduler_claims, array( 'date_created_gmt' => $now->format( 'Y-m-d H:i:s' ) ) ); return $wpdb->insert_id; } /** * Set a claim filter. * * @param string $filter_name Claim filter name. * @param mixed $filter_values Values to filter. * @return void */ public function set_claim_filter( $filter_name, $filter_values ) { if ( isset( $this->claim_filters[ $filter_name ] ) ) { $this->claim_filters[ $filter_name ] = $filter_values; } } /** * Get the claim filter value. * * @param string $filter_name Claim filter name. * @return mixed */ public function get_claim_filter( $filter_name ) { if ( isset( $this->claim_filters[ $filter_name ] ) ) { return $this->claim_filters[ $filter_name ]; } return ''; } /** * Mark actions claimed. * * @param string $claim_id Claim Id. * @param int $limit Number of action to include in claim. * @param DateTime|null $before_date Should use UTC timezone. * @param array $hooks Hooks to filter for. * @param string $group Group to filter for. * * @return int The number of actions that were claimed. * @throws \InvalidArgumentException Throws InvalidArgumentException if group doesn't exist. * @throws \RuntimeException Throws RuntimeException if unable to claim action. */ protected function claim_actions( $claim_id, $limit, ?DateTime $before_date = null, $hooks = array(), $group = '' ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $now = as_get_datetime_object(); $date = is_null( $before_date ) ? $now : clone $before_date; // Set claim filters. if ( ! empty( $hooks ) ) { $this->set_claim_filter( 'hooks', $hooks ); } else { $hooks = $this->get_claim_filter( 'hooks' ); } if ( ! empty( $group ) ) { $this->set_claim_filter( 'group', $group ); } else { $group = $this->get_claim_filter( 'group' ); } $where = 'WHERE claim_id = 0 AND scheduled_date_gmt <= %s AND status=%s'; $where_params = array( $date->format( 'Y-m-d H:i:s' ), self::STATUS_PENDING, ); if ( ! empty( $hooks ) ) { $placeholders = array_fill( 0, count( $hooks ), '%s' ); $where .= ' AND hook IN (' . join( ', ', $placeholders ) . ')'; $where_params = array_merge( $where_params, array_values( $hooks ) ); } $group_operator = 'IN'; if ( empty( $group ) ) { $group = $this->get_claim_filter( 'exclude-groups' ); $group_operator = 'NOT IN'; } if ( ! empty( $group ) ) { $group_ids = $this->get_group_ids( $group, false ); // throw exception if no matching group(s) found, this matches ActionScheduler_wpPostStore's behaviour. if ( empty( $group_ids ) ) { throw new InvalidArgumentException( sprintf( /* translators: %s: group name(s) */ _n( 'The group "%s" does not exist.', 'The groups "%s" do not exist.', is_array( $group ) ? count( $group ) : 1, 'action-scheduler' ), $group ) ); } $id_list = implode( ',', array_map( 'intval', $group_ids ) ); $where .= " AND group_id {$group_operator} ( $id_list )"; } /** * Sets the order-by clause used in the action claim query. * * @param string $order_by_sql * @param string $claim_id Claim Id. * @param array $hooks Hooks to filter for. * * @since 3.8.3 Made $claim_id and $hooks available. * @since 3.4.0 */ $order = apply_filters( 'action_scheduler_claim_actions_order_by', 'ORDER BY priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC', $claim_id, $hooks ); $skip_locked = $this->db_supports_skip_locked() ? ' SKIP LOCKED' : ''; // Selecting the action_ids that we plan to claim, while skipping any locked rows to avoid deadlocking. $select_sql = $wpdb->prepare( "SELECT action_id from {$wpdb->actionscheduler_actions} {$where} {$order} LIMIT %d FOR UPDATE{$skip_locked}", array_merge( $where_params, array( $limit ) ) ); // Now place it into an UPDATE statement by joining the result sets, allowing for the SKIP LOCKED behavior to take effect. $update_sql = "UPDATE {$wpdb->actionscheduler_actions} t1 JOIN ( $select_sql ) t2 ON t1.action_id = t2.action_id SET claim_id=%d, last_attempt_gmt=%s, last_attempt_local=%s"; $update_params = array( $claim_id, $now->format( 'Y-m-d H:i:s' ), current_time( 'mysql' ), ); $rows_affected = $wpdb->query( $wpdb->prepare( $update_sql, $update_params ) ); if ( false === $rows_affected ) { $error = empty( $wpdb->last_error ) ? _x( 'unknown', 'database error', 'action-scheduler' ) : $wpdb->last_error; throw new \RuntimeException( sprintf( /* translators: %s database error. */ __( 'Unable to claim actions. Database error: %s.', 'action-scheduler' ), $error ) ); } return (int) $rows_affected; } /** * Determines whether the database supports using SKIP LOCKED. This logic mimicks the $wpdb::has_cap() logic. * * SKIP_LOCKED support was added to MariaDB in 10.6.0 and to MySQL in 8.0.1 * * @return bool */ private function db_supports_skip_locked() { global $wpdb; $db_version = $wpdb->db_version(); $db_server_info = $wpdb->db_server_info(); $is_mariadb = ( false !== strpos( $db_server_info, 'MariaDB' ) ); if ( $is_mariadb && '5.5.5' === $db_version && PHP_VERSION_ID < 80016 // PHP 8.0.15 or older. ) { /* * Account for MariaDB version being prefixed with '5.5.5-' on older PHP versions. */ $db_server_info = preg_replace( '/^5\.5\.5-(.*)/', '$1', $db_server_info ); $db_version = preg_replace( '/[^0-9.].*/', '', $db_server_info ); } $is_supported = ( $is_mariadb && version_compare( $db_version, '10.6.0', '>=' ) ) || ( ! $is_mariadb && version_compare( $db_version, '8.0.1', '>=' ) ); /** * Filter whether the database supports the SKIP LOCKED modifier for queries. * * @param bool $is_supported Whether SKIP LOCKED is supported. * * @since 3.9.3 */ return apply_filters( 'action_scheduler_db_supports_skip_locked', $is_supported ); } /** * Get the number of active claims. * * @return int */ public function get_claim_count() { global $wpdb; $sql = "SELECT COUNT(DISTINCT claim_id) FROM {$wpdb->actionscheduler_actions} WHERE claim_id != 0 AND status IN ( %s, %s)"; $sql = $wpdb->prepare( $sql, array( self::STATUS_PENDING, self::STATUS_RUNNING ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared return (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Return an action's claim ID, as stored in the claim_id column. * * @param string $action_id Action ID. * @return mixed */ public function get_claim_id( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $sql = "SELECT claim_id FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d"; $sql = $wpdb->prepare( $sql, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared return (int) $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Retrieve the action IDs of action in a claim. * * @param int $claim_id Claim ID. * @return int[] */ public function find_actions_by_claim_id( $claim_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $action_ids = array(); $before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object(); $cut_off = $before_date->format( 'Y-m-d H:i:s' ); $sql = $wpdb->prepare( "SELECT action_id, scheduled_date_gmt FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d ORDER BY priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC", $claim_id ); // Verify that the scheduled date for each action is within the expected bounds (in some unusual // cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify). foreach ( $wpdb->get_results( $sql ) as $claimed_action ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared if ( $claimed_action->scheduled_date_gmt <= $cut_off ) { $action_ids[] = absint( $claimed_action->action_id ); } } return $action_ids; } /** * Release pending actions from a claim and delete the claim. * * @param ActionScheduler_ActionClaim $claim Claim object. * @throws \RuntimeException When unable to release actions from claim. */ public function release_claim( ActionScheduler_ActionClaim $claim ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; if ( 0 === intval( $claim->get_id() ) ) { // Verify that the claim_id is valid before attempting to release it. return; } /** * 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. * * We only release pending actions in order for them to be claimed by another process. */ $action_ids = $wpdb->get_col( $wpdb->prepare( "SELECT action_id FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d AND status = %s", $claim->get_id(), self::STATUS_PENDING ) ); $row_updates = 0; if ( count( $action_ids ) > 0 ) { $action_id_string = implode( ',', array_map( 'absint', $action_ids ) ); $row_updates = $wpdb->query( "UPDATE {$wpdb->actionscheduler_actions} SET claim_id = 0 WHERE action_id IN ({$action_id_string})" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared } $wpdb->delete( $wpdb->actionscheduler_claims, array( 'claim_id' => $claim->get_id() ), array( '%d' ) ); if ( $row_updates < count( $action_ids ) ) { throw new RuntimeException( sprintf( // translators: %d is an id. __( 'Unable to release actions from claim id %d.', 'action-scheduler' ), $claim->get_id() ) ); } } /** * Remove the claim from an action. * * @param int $action_id Action ID. * * @return void */ public function unclaim_action( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $wpdb->update( $wpdb->actionscheduler_actions, array( 'claim_id' => 0 ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); } /** * Mark an action as failed. * * @param int $action_id Action ID. * @throws \InvalidArgumentException Throw an exception if action was not updated. */ public function mark_failure( $action_id ) { /** * Global. * @var \wpdb $wpdb */ global $wpdb; $updated = $wpdb->update( $wpdb->actionscheduler_actions, array( 'status' => self::STATUS_FAILED ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); if ( empty( $updated ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having failed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } } /** * Add execution message to action log. * * @throws Exception If the action status cannot be updated to self::STATUS_RUNNING ('in-progress'). * * @param int $action_id Action ID. * * @return void */ public function log_execution( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $sql = "UPDATE {$wpdb->actionscheduler_actions} SET attempts = attempts+1, status=%s, last_attempt_gmt = %s, last_attempt_local = %s WHERE action_id = %d"; $sql = $wpdb->prepare( $sql, self::STATUS_RUNNING, current_time( 'mysql', true ), current_time( 'mysql' ), $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $status_updated = $wpdb->query( $sql ); if ( ! $status_updated ) { throw new Exception( sprintf( /* translators: 1: action ID. 2: status slug. */ __( 'Unable to update the status of action %1$d to %2$s.', 'action-scheduler' ), $action_id, self::STATUS_RUNNING ) ); } } /** * Mark an action as complete. * * @param int $action_id Action ID. * * @return void * @throws \InvalidArgumentException Throw an exception if action was not updated. */ public function mark_complete( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $updated = $wpdb->update( $wpdb->actionscheduler_actions, array( 'status' => self::STATUS_COMPLETE, 'last_attempt_gmt' => current_time( 'mysql', true ), 'last_attempt_local' => current_time( 'mysql' ), ), array( 'action_id' => $action_id ), array( '%s' ), array( '%d' ) ); if ( empty( $updated ) ) { /* translators: %s is the action ID */ throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s: we were unable to mark this action as having completed. It may may have been deleted by another process.', 'action-scheduler' ), $action_id ) ); } /** * Fires after a scheduled action has been completed. * * @since 3.4.2 * * @param int $action_id Action ID. */ do_action( 'action_scheduler_completed_action', $action_id ); } /** * Get an action's status. * * @param int $action_id Action ID. * * @return string * @throws \InvalidArgumentException Throw an exception if not status was found for action_id. * @throws \RuntimeException Throw an exception if action status could not be retrieved. */ public function get_status( $action_id ) { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $sql = "SELECT status FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d"; $sql = $wpdb->prepare( $sql, $action_id ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $status = $wpdb->get_var( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared if ( is_null( $status ) ) { throw new \InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) ); } elseif ( empty( $status ) ) { throw new \RuntimeException( __( 'Unknown status found for action.', 'action-scheduler' ) ); } else { return $status; } } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php0000644 00000003502 15151523433 0030453 0 ustar 00 <?php /** * Class ActionScheduler_wpPostStore_PostStatusRegistrar * * @codeCoverageIgnore */ class ActionScheduler_wpPostStore_PostStatusRegistrar { /** * Registrar. */ public function register() { register_post_status( ActionScheduler_Store::STATUS_RUNNING, array_merge( $this->post_status_args(), $this->post_status_running_labels() ) ); register_post_status( ActionScheduler_Store::STATUS_FAILED, array_merge( $this->post_status_args(), $this->post_status_failed_labels() ) ); } /** * Build the args array for the post type definition * * @return array */ protected function post_status_args() { $args = array( 'public' => false, 'exclude_from_search' => false, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, ); return apply_filters( 'action_scheduler_post_status_args', $args ); } /** * Build the args array for the post type definition * * @return array */ protected function post_status_failed_labels() { $labels = array( 'label' => _x( 'Failed', 'post', 'action-scheduler' ), /* translators: %s: count */ 'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>', 'action-scheduler' ), ); return apply_filters( 'action_scheduler_post_status_failed_labels', $labels ); } /** * Build the args array for the post type definition * * @return array */ protected function post_status_running_labels() { $labels = array( 'label' => _x( 'In-Progress', 'post', 'action-scheduler' ), /* translators: %s: count */ 'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>', 'action-scheduler' ), ); return apply_filters( 'action_scheduler_post_status_running_labels', $labels ); } } woocommerce/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php 0000644 00000003711 15151523433 0030113 0 ustar 00 <?php /** * Class ActionScheduler_wpPostStore_PostTypeRegistrar * * @codeCoverageIgnore */ class ActionScheduler_wpPostStore_PostTypeRegistrar { /** * Registrar. */ public function register() { register_post_type( ActionScheduler_wpPostStore::POST_TYPE, $this->post_type_args() ); } /** * Build the args array for the post type definition * * @return array */ protected function post_type_args() { $args = array( 'label' => __( 'Scheduled Actions', 'action-scheduler' ), 'description' => __( 'Scheduled actions are hooks triggered on a certain date and time.', 'action-scheduler' ), 'public' => false, 'map_meta_cap' => true, 'hierarchical' => false, 'supports' => array( 'title', 'editor', 'comments' ), 'rewrite' => false, 'query_var' => false, 'can_export' => true, 'ep_mask' => EP_NONE, 'labels' => array( 'name' => __( 'Scheduled Actions', 'action-scheduler' ), 'singular_name' => __( 'Scheduled Action', 'action-scheduler' ), 'menu_name' => _x( 'Scheduled Actions', 'Admin menu name', 'action-scheduler' ), 'add_new' => __( 'Add', 'action-scheduler' ), 'add_new_item' => __( 'Add New Scheduled Action', 'action-scheduler' ), 'edit' => __( 'Edit', 'action-scheduler' ), 'edit_item' => __( 'Edit Scheduled Action', 'action-scheduler' ), 'new_item' => __( 'New Scheduled Action', 'action-scheduler' ), 'view' => __( 'View Action', 'action-scheduler' ), 'view_item' => __( 'View Action', 'action-scheduler' ), 'search_items' => __( 'Search Scheduled Actions', 'action-scheduler' ), 'not_found' => __( 'No actions found', 'action-scheduler' ), 'not_found_in_trash' => __( 'No actions found in trash', 'action-scheduler' ), ), ); $args = apply_filters( 'action_scheduler_post_type_args', $args ); return $args; } } woocommerce/action-scheduler/classes/ActionScheduler_AdminView.php 0000644 00000024603 15151523433 0021510 0 ustar 00 <?php /** * Class ActionScheduler_AdminView * * @codeCoverageIgnore */ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated { /** * Instance. * * @var null|self */ private static $admin_view = null; /** * Screen ID. * * @var string */ private static $screen_id = 'tools_page_action-scheduler'; /** * ActionScheduler_ListTable instance. * * @var ActionScheduler_ListTable */ protected $list_table; /** * Get instance. * * @return ActionScheduler_AdminView * @codeCoverageIgnore */ public static function instance() { if ( empty( self::$admin_view ) ) { $class = apply_filters( 'action_scheduler_admin_view_class', 'ActionScheduler_AdminView' ); self::$admin_view = new $class(); } return self::$admin_view; } /** * Initialize. * * @codeCoverageIgnore */ public function init() { if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) { if ( class_exists( 'WooCommerce' ) ) { add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) ); add_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) ); add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) ); } add_action( 'admin_menu', array( $this, 'register_menu' ) ); add_action( 'admin_notices', array( $this, 'maybe_check_pastdue_actions' ) ); add_action( 'current_screen', array( $this, 'add_help_tabs' ) ); } } /** * Print system status report. */ public function system_status_report() { $table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() ); $table->render(); } /** * Registers action-scheduler into WooCommerce > System status. * * @param array $tabs An associative array of tab key => label. * @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs */ public function register_system_status_tab( array $tabs ) { $tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' ); return $tabs; } /** * Include Action Scheduler's administration under the Tools menu. * * A menu under the Tools menu is important for backward compatibility (as that's * where it started), and also provides more convenient access than the WooCommerce * System Status page, and for sites where WooCommerce isn't active. */ public function register_menu() { $hook_suffix = add_submenu_page( 'tools.php', __( 'Scheduled Actions', 'action-scheduler' ), __( 'Scheduled Actions', 'action-scheduler' ), 'manage_options', 'action-scheduler', array( $this, 'render_admin_ui' ) ); add_action( 'load-' . $hook_suffix, array( $this, 'process_admin_ui' ) ); } /** * Triggers processing of any pending actions. */ public function process_admin_ui() { $this->get_list_table(); } /** * Renders the Admin UI */ public function render_admin_ui() { $table = $this->get_list_table(); $table->display_page(); } /** * Get the admin UI object and process any requested actions. * * @return ActionScheduler_ListTable */ protected function get_list_table() { if ( null === $this->list_table ) { $this->list_table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() ); $this->list_table->process_actions(); } return $this->list_table; } /** * Action: admin_notices * * Maybe check past-due actions, and print notice. * * @uses $this->check_pastdue_actions() */ public function maybe_check_pastdue_actions() { // Filter to prevent checking actions (ex: inappropriate user). if ( ! apply_filters( 'action_scheduler_check_pastdue_actions', current_user_can( 'manage_options' ) ) ) { return; } // Get last check transient. $last_check = get_transient( 'action_scheduler_last_pastdue_actions_check' ); // If transient exists, we're within interval, so bail. if ( ! empty( $last_check ) ) { return; } // Perform the check. $this->check_pastdue_actions(); } /** * Check past-due actions, and print notice. */ protected function check_pastdue_actions() { // Set thresholds. $threshold_seconds = (int) apply_filters( 'action_scheduler_pastdue_actions_seconds', DAY_IN_SECONDS ); $threshold_min = (int) apply_filters( 'action_scheduler_pastdue_actions_min', 1 ); // Set fallback value for past-due actions count. $num_pastdue_actions = 0; // Allow third-parties to preempt the default check logic. $check = apply_filters( 'action_scheduler_pastdue_actions_check_pre', null ); // If no third-party preempted and there are no past-due actions, return early. if ( ! is_null( $check ) ) { return; } // Scheduled actions query arguments. $query_args = array( 'date' => as_get_datetime_object( time() - $threshold_seconds ), 'status' => ActionScheduler_Store::STATUS_PENDING, 'per_page' => $threshold_min, ); // If no third-party preempted, run default check. if ( is_null( $check ) ) { $store = ActionScheduler_Store::instance(); $num_pastdue_actions = (int) $store->query_actions( $query_args, 'count' ); // Check if past-due actions count is greater than or equal to threshold. $check = ( $num_pastdue_actions >= $threshold_min ); $check = (bool) apply_filters( 'action_scheduler_pastdue_actions_check', $check, $num_pastdue_actions, $threshold_seconds, $threshold_min ); } // If check failed, set transient and abort. if ( ! boolval( $check ) ) { $interval = apply_filters( 'action_scheduler_pastdue_actions_check_interval', round( $threshold_seconds / 4 ), $threshold_seconds ); set_transient( 'action_scheduler_last_pastdue_actions_check', time(), $interval ); return; } $actions_url = add_query_arg( array( 'page' => 'action-scheduler', 'status' => 'past-due', 'order' => 'asc', ), admin_url( 'tools.php' ) ); // Print notice. echo '<div class="notice notice-warning"><p>'; printf( wp_kses( // translators: 1) is the number of affected actions, 2) is a link to an admin screen. _n( '<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due action</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation »</a>', '<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due actions</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation »</a>', $num_pastdue_actions, 'action-scheduler' ), array( 'strong' => array(), 'a' => array( 'href' => true, 'target' => true, ), ) ), absint( $num_pastdue_actions ), esc_attr( esc_url( $actions_url ) ) ); echo '</p></div>'; // Facilitate third-parties to evaluate and print notices. do_action( 'action_scheduler_pastdue_actions_extra_notices', $query_args ); } /** * Provide more information about the screen and its data in the help tab. */ public function add_help_tabs() { $screen = get_current_screen(); if ( ! $screen || self::$screen_id !== $screen->id ) { return; } $as_version = ActionScheduler_Versions::instance()->latest_version(); $as_source = ActionScheduler_SystemInformation::active_source(); $as_source_path = ActionScheduler_SystemInformation::active_source_path(); $as_source_markup = sprintf( '<code>%s</code>', esc_html( $as_source_path ) ); if ( ! empty( $as_source ) ) { $as_source_markup = sprintf( '%s: <abbr title="%s">%s</abbr>', ucfirst( $as_source['type'] ), esc_attr( $as_source_path ), esc_html( $as_source['name'] ) ); } $screen->add_help_tab( array( 'id' => 'action_scheduler_about', 'title' => __( 'About', 'action-scheduler' ), 'content' => // translators: %s is the Action Scheduler version. '<h2>' . sprintf( __( 'About Action Scheduler %s', 'action-scheduler' ), $as_version ) . '</h2>' . '<p>' . __( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) . '</p>' . '<h3>' . esc_html__( 'Source', 'action-scheduler' ) . '</h3>' . '<p>' . esc_html__( 'Action Scheduler is currently being loaded from the following location. This can be useful when debugging, or if requested by the support team.', 'action-scheduler' ) . '</p>' . '<p>' . $as_source_markup . '</p>' . '<h3>' . esc_html__( 'WP CLI', 'action-scheduler' ) . '</h3>' . '<p>' . sprintf( /* translators: %1$s is WP CLI command (not translatable) */ esc_html__( 'WP CLI commands are available: execute %1$s for a list of available commands.', 'action-scheduler' ), '<code>wp help action-scheduler</code>' ) . '</p>', ) ); $screen->add_help_tab( array( 'id' => 'action_scheduler_columns', 'title' => __( 'Columns', 'action-scheduler' ), 'content' => '<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' . '<ul>' . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) . sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) . '</ul>', ) ); } } woocommerce/action-scheduler/classes/ActionScheduler_NullLogEntry.php 0000644 00000000512 15151523433 0022214 0 ustar 00 <?php /** * Class ActionScheduler_NullLogEntry */ class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry { /** * Construct. * * @param string $action_id Action ID. * @param string $message Log entry. */ public function __construct( $action_id = '', $message = '' ) { // nothing to see here. } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Lock.php 0000644 00000003437 15151523433 0022505 0 ustar 00 <?php /** * Abstract class for setting a basic lock to throttle some action. * * Class ActionScheduler_Lock */ abstract class ActionScheduler_Lock { /** * Instance. * * @var ActionScheduler_Lock */ private static $locker = null; /** * Duration of lock. * * @var int */ protected static $lock_duration = MINUTE_IN_SECONDS; /** * Check if a lock is set for a given lock type. * * @param string $lock_type A string to identify different lock types. * @return bool */ public function is_locked( $lock_type ) { return ( $this->get_expiration( $lock_type ) >= time() ); } /** * Set a lock. * * To prevent race conditions, implementations should avoid setting the lock if the lock is already held. * * @param string $lock_type A string to identify different lock types. * @return bool */ abstract public function set( $lock_type ); /** * If a lock is set, return the timestamp it was set to expiry. * * @param string $lock_type A string to identify different lock types. * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire. */ abstract public function get_expiration( $lock_type ); /** * Get the amount of time to set for a given lock. 60 seconds by default. * * @param string $lock_type A string to identify different lock types. * @return int */ protected function get_duration( $lock_type ) { return apply_filters( 'action_scheduler_lock_duration', self::$lock_duration, $lock_type ); } /** * Get instance. * * @return ActionScheduler_Lock */ public static function instance() { if ( empty( self::$locker ) ) { $class = apply_filters( 'action_scheduler_lock_class', 'ActionScheduler_OptionLock' ); self::$locker = new $class(); } return self::$locker; } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php 0000644 00000006346 15151523433 0027057 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_RecurringSchedule */ abstract class ActionScheduler_Abstract_RecurringSchedule extends ActionScheduler_Abstract_Schedule { /** * The date & time the first instance of this schedule was setup to run (which may not be this instance). * * Schedule objects are attached to an action object. Each schedule stores the run date for that * object as the start date - @see $this->start - and logic to calculate the next run date after * that - @see $this->calculate_next(). The $first_date property also keeps a record of when the very * first instance of this chain of schedules ran. * * @var DateTime */ private $first_date = null; /** * Timestamp equivalent of @see $this->first_date * * @var int */ protected $first_timestamp = null; /** * The recurrence between each time an action is run using this schedule. * Used to calculate the start date & time. Can be a number of seconds, in the * case of ActionScheduler_IntervalSchedule, or a cron expression, as in the * case of ActionScheduler_CronSchedule. Or something else. * * @var mixed */ protected $recurrence; /** * Construct. * * @param DateTime $date The date & time to run the action. * @param mixed $recurrence The data used to determine the schedule's recurrence. * @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance. */ public function __construct( DateTime $date, $recurrence, ?DateTime $first = null ) { parent::__construct( $date ); $this->first_date = empty( $first ) ? $date : $first; $this->recurrence = $recurrence; } /** * Schedule is recurring. * * @return bool */ public function is_recurring() { return true; } /** * Get the date & time of the first schedule in this recurring series. * * @return DateTime|null */ public function get_first_date() { return clone $this->first_date; } /** * Get the schedule's recurrence. * * @return string */ public function get_recurrence() { return $this->recurrence; } /** * For PHP 5.2 compat, since DateTime objects can't be serialized * * @return array */ public function __sleep() { $sleep_params = parent::__sleep(); $this->first_timestamp = $this->first_date->getTimestamp(); return array_merge( $sleep_params, array( 'first_timestamp', 'recurrence', ) ); } /** * Unserialize recurring schedules serialized/stored prior to AS 3.0.0 * * Prior to Action Scheduler 3.0.0, schedules used different property names to refer * to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp * was the same as ActionScheduler_SimpleSchedule::timestamp. This was addressed in * Action Scheduler 3.0.0, where properties and property names were aligned for better * inheritance. To maintain backward compatibility with scheduled serialized and stored * prior to 3.0, we need to correctly map the old property names. */ public function __wakeup() { parent::__wakeup(); if ( $this->first_timestamp > 0 ) { $this->first_date = as_get_datetime_object( $this->first_timestamp ); } else { $this->first_date = $this->get_date(); } } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Store.php 0000644 00000034071 15151523433 0022707 0 ustar 00 <?php /** * Class ActionScheduler_Store * * @codeCoverageIgnore */ abstract class ActionScheduler_Store extends ActionScheduler_Store_Deprecated { const STATUS_COMPLETE = 'complete'; const STATUS_PENDING = 'pending'; const STATUS_RUNNING = 'in-progress'; const STATUS_FAILED = 'failed'; const STATUS_CANCELED = 'canceled'; const DEFAULT_CLASS = 'ActionScheduler_wpPostStore'; /** * ActionScheduler_Store instance. * * @var ActionScheduler_Store */ private static $store = null; /** * Maximum length of args. * * @var int */ protected static $max_args_length = 191; /** * Save action. * * @param ActionScheduler_Action $action Action to save. * @param null|DateTime $scheduled_date Optional Date of the first instance * to store. Otherwise uses the first date of the action's * schedule. * * @return int The action ID */ abstract public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ); /** * Get action. * * @param string $action_id Action ID. * * @return ActionScheduler_Action */ abstract public function fetch_action( $action_id ); /** * Find an action. * * Note: the query ordering changes based on the passed 'status' value. * * @param string $hook Action hook. * @param array $params Parameters of the action to find. * * @return string|null ID of the next action matching the criteria or NULL if not found. */ public function find_action( $hook, $params = array() ) { $params = wp_parse_args( $params, array( 'args' => null, 'status' => self::STATUS_PENDING, 'group' => '', ) ); // These params are fixed for this method. $params['hook'] = $hook; $params['orderby'] = 'date'; $params['per_page'] = 1; if ( ! empty( $params['status'] ) ) { if ( self::STATUS_PENDING === $params['status'] ) { $params['order'] = 'ASC'; // Find the next action that matches. } else { $params['order'] = 'DESC'; // Find the most recent action that matches. } } $results = $this->query_actions( $params ); return empty( $results ) ? null : $results[0]; } /** * Query for action count or list of action IDs. * * @since 3.3.0 $query['status'] accepts array of statuses instead of a single status. * * @param array $query { * Query filtering options. * * @type string $hook The name of the actions. Optional. * @type string|array $status The status or statuses of the actions. Optional. * @type array $args The args array of the actions. Optional. * @type DateTime $date The scheduled date of the action. Used in UTC timezone. Optional. * @type string $date_compare Operator for selecting by $date param. Accepted values are '!=', '>', '>=', '<', '<=', '='. Defaults to '<='. * @type DateTime $modified The last modified date of the action. Used in UTC timezone. Optional. * @type string $modified_compare Operator for comparing $modified param. Accepted values are '!=', '>', '>=', '<', '<=', '='. Defaults to '<='. * @type string $group The group the action belongs to. Optional. * @type bool|int $claimed TRUE to find claimed actions, FALSE to find unclaimed actions, an int to find a specific claim ID. Optional. * @type int $per_page Number of results to return. Defaults to 5. * @type int $offset The query pagination offset. Defaults to 0. * @type int $orderby Accepted values are 'hook', 'group', 'modified', 'date' or 'none'. Defaults to 'date'. * @type string $order Accepted values are 'ASC' or 'DESC'. Defaults to 'ASC'. * } * @param string $query_type Whether to select or count the results. Default, select. * * @return string|array|null The IDs of actions matching the query. Null on failure. */ abstract public function query_actions( $query = array(), $query_type = 'select' ); /** * Run query to get a single action ID. * * @since 3.3.0 * * @see ActionScheduler_Store::query_actions for $query arg usage but 'per_page' and 'offset' can't be used. * * @param array $query Query parameters. * * @return int|null */ public function query_action( $query ) { $query['per_page'] = 1; $query['offset'] = 0; $results = $this->query_actions( $query ); if ( empty( $results ) ) { return null; } else { return (int) $results[0]; } } /** * Get a count of all actions in the store, grouped by status * * @return array */ abstract public function action_counts(); /** * Get additional action counts. * * - add past-due actions * * @return array */ public function extra_action_counts() { $extra_actions = array(); $pastdue_action_counts = (int) $this->query_actions( array( 'status' => self::STATUS_PENDING, 'date' => as_get_datetime_object(), ), 'count' ); if ( $pastdue_action_counts ) { $extra_actions['past-due'] = $pastdue_action_counts; } /** * Allows 3rd party code to add extra action counts (used in filters in the list table). * * @since 3.5.0 * @param $extra_actions array Array with format action_count_identifier => action count. */ return apply_filters( 'action_scheduler_extra_action_counts', $extra_actions ); } /** * Cancel action. * * @param string $action_id Action ID. */ abstract public function cancel_action( $action_id ); /** * Delete action. * * @param string $action_id Action ID. */ abstract public function delete_action( $action_id ); /** * Get action's schedule or run timestamp. * * @param string $action_id Action ID. * * @return DateTime The date the action is schedule to run, or the date that it ran. */ abstract public function get_date( $action_id ); /** * Make a claim. * * @param int $max_actions Maximum number of actions to claim. * @param DateTime|null $before_date Claim only actions schedule before the given date. Defaults to now. * @param array $hooks Claim only actions with a hook or hooks. * @param string $group Claim only actions in the given group. * * @return ActionScheduler_ActionClaim */ abstract public function stake_claim( $max_actions = 10, ?DateTime $before_date = null, $hooks = array(), $group = '' ); /** * Get claim count. * * @return int */ abstract public function get_claim_count(); /** * Release the claim. * * @param ActionScheduler_ActionClaim $claim Claim object. */ abstract public function release_claim( ActionScheduler_ActionClaim $claim ); /** * Un-claim the action. * * @param string $action_id Action ID. */ abstract public function unclaim_action( $action_id ); /** * Mark action as failed. * * @param string $action_id Action ID. */ abstract public function mark_failure( $action_id ); /** * Log action's execution. * * @param string $action_id Actoin ID. */ abstract public function log_execution( $action_id ); /** * Mark action as complete. * * @param string $action_id Action ID. */ abstract public function mark_complete( $action_id ); /** * Get action's status. * * @param string $action_id Action ID. * @return string */ abstract public function get_status( $action_id ); /** * Get action's claim ID. * * @param string $action_id Action ID. * @return mixed */ abstract public function get_claim_id( $action_id ); /** * Find actions by claim ID. * * @param string $claim_id Claim ID. * @return array */ abstract public function find_actions_by_claim_id( $claim_id ); /** * Validate SQL operator. * * @param string $comparison_operator Operator. * @return string */ protected function validate_sql_comparator( $comparison_operator ) { if ( in_array( $comparison_operator, array( '!=', '>', '>=', '<', '<=', '=' ), true ) ) { return $comparison_operator; } return '='; } /** * Get the time MySQL formatted date/time string for an action's (next) scheduled date. * * @param ActionScheduler_Action $action Action. * @param null|DateTime $scheduled_date Action's schedule date (optional). * @return string */ protected function get_scheduled_date_string( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) { $next = is_null( $scheduled_date ) ? $action->get_schedule()->get_date() : $scheduled_date; if ( ! $next ) { $next = date_create(); } $next->setTimezone( new DateTimeZone( 'UTC' ) ); return $next->format( 'Y-m-d H:i:s' ); } /** * Get the time MySQL formatted date/time string for an action's (next) scheduled date. * * @param ActionScheduler_Action|null $action Action. * @param null|DateTime $scheduled_date Action's scheduled date (optional). * @return string */ protected function get_scheduled_date_string_local( ActionScheduler_Action $action, ?DateTime $scheduled_date = null ) { $next = is_null( $scheduled_date ) ? $action->get_schedule()->get_date() : $scheduled_date; if ( ! $next ) { $next = date_create(); } ActionScheduler_TimezoneHelper::set_local_timezone( $next ); return $next->format( 'Y-m-d H:i:s' ); } /** * Validate that we could decode action arguments. * * @param mixed $args The decoded arguments. * @param int $action_id The action ID. * * @throws ActionScheduler_InvalidActionException When the decoded arguments are invalid. */ protected function validate_args( $args, $action_id ) { // Ensure we have an array of args. if ( ! is_array( $args ) ) { throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id ); } // Validate JSON decoding if possible. if ( function_exists( 'json_last_error' ) && JSON_ERROR_NONE !== json_last_error() ) { throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id, $args ); } } /** * Validate a ActionScheduler_Schedule object. * * @param mixed $schedule The unserialized ActionScheduler_Schedule object. * @param int $action_id The action ID. * * @throws ActionScheduler_InvalidActionException When the schedule is invalid. */ protected function validate_schedule( $schedule, $action_id ) { if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) { throw ActionScheduler_InvalidActionException::from_schedule( $action_id, $schedule ); } } /** * InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4. * * Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However, * with custom tables, we use an indexed VARCHAR column instead. * * @param ActionScheduler_Action $action Action to be validated. * @throws InvalidArgumentException When json encoded args is too long. */ protected function validate_action( ActionScheduler_Action $action ) { if ( strlen( wp_json_encode( $action->get_args() ) ) > static::$max_args_length ) { // translators: %d is a number (maximum length of action arguments). throw new InvalidArgumentException( sprintf( __( 'ActionScheduler_Action::$args too long. To ensure the args column can be indexed, action args should not be more than %d characters when encoded as JSON.', 'action-scheduler' ), static::$max_args_length ) ); } } /** * Cancel pending actions by hook. * * @since 3.0.0 * * @param string $hook Hook name. * * @return void */ public function cancel_actions_by_hook( $hook ) { $action_ids = true; while ( ! empty( $action_ids ) ) { $action_ids = $this->query_actions( array( 'hook' => $hook, 'status' => self::STATUS_PENDING, 'per_page' => 1000, 'orderby' => 'none', ) ); $this->bulk_cancel_actions( $action_ids ); } } /** * Cancel pending actions by group. * * @since 3.0.0 * * @param string $group Group slug. * * @return void */ public function cancel_actions_by_group( $group ) { $action_ids = true; while ( ! empty( $action_ids ) ) { $action_ids = $this->query_actions( array( 'group' => $group, 'status' => self::STATUS_PENDING, 'per_page' => 1000, 'orderby' => 'none', ) ); $this->bulk_cancel_actions( $action_ids ); } } /** * Cancel a set of action IDs. * * @since 3.0.0 * * @param int[] $action_ids List of action IDs. * * @return void */ private function bulk_cancel_actions( $action_ids ) { foreach ( $action_ids as $action_id ) { $this->cancel_action( $action_id ); } do_action( 'action_scheduler_bulk_cancel_actions', $action_ids ); } /** * Get status labels. * * @return array<string, string> */ public function get_status_labels() { return array( self::STATUS_COMPLETE => __( 'Complete', 'action-scheduler' ), self::STATUS_PENDING => __( 'Pending', 'action-scheduler' ), self::STATUS_RUNNING => __( 'In-progress', 'action-scheduler' ), self::STATUS_FAILED => __( 'Failed', 'action-scheduler' ), self::STATUS_CANCELED => __( 'Canceled', 'action-scheduler' ), ); } /** * Check if there are any pending scheduled actions due to run. * * @return string */ public function has_pending_actions_due() { $pending_actions = $this->query_actions( array( 'per_page' => 1, 'date' => as_get_datetime_object(), 'status' => self::STATUS_PENDING, 'orderby' => 'none', ), 'count' ); return ! empty( $pending_actions ); } /** * Callable initialization function optionally overridden in derived classes. */ public function init() {} /** * Callable function to mark an action as migrated optionally overridden in derived classes. * * @param int $action_id Action ID. */ public function mark_migrated( $action_id ) {} /** * Get instance. * * @return ActionScheduler_Store */ public static function instance() { if ( empty( self::$store ) ) { $class = apply_filters( 'action_scheduler_store_class', self::DEFAULT_CLASS ); self::$store = new $class(); } return self::$store; } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler.php 0000644 00000026215 15151523433 0021534 0 ustar 00 <?php use Action_Scheduler\WP_CLI\Migration_Command; use Action_Scheduler\Migration\Controller; /** * Class ActionScheduler * * @codeCoverageIgnore */ abstract class ActionScheduler { /** * Plugin file path. * * @var string */ private static $plugin_file = ''; /** * ActionScheduler_ActionFactory instance. * * @var ActionScheduler_ActionFactory */ private static $factory = null; /** * Data store is initialized. * * @var bool */ private static $data_store_initialized = false; /** * Factory. */ public static function factory() { if ( ! isset( self::$factory ) ) { self::$factory = new ActionScheduler_ActionFactory(); } return self::$factory; } /** * Get Store instance. */ public static function store() { return ActionScheduler_Store::instance(); } /** * Get Lock instance. */ public static function lock() { return ActionScheduler_Lock::instance(); } /** * Get Logger instance. */ public static function logger() { return ActionScheduler_Logger::instance(); } /** * Get QueueRunner instance. */ public static function runner() { return ActionScheduler_QueueRunner::instance(); } /** * Get AdminView instance. */ public static function admin_view() { return ActionScheduler_AdminView::instance(); } /** * Get the absolute system path to the plugin directory, or a file therein * * @static * @param string $path Path relative to plugin directory. * @return string */ public static function plugin_path( $path ) { $base = dirname( self::$plugin_file ); if ( $path ) { return trailingslashit( $base ) . $path; } else { return untrailingslashit( $base ); } } /** * Get the absolute URL to the plugin directory, or a file therein * * @static * @param string $path Path relative to plugin directory. * @return string */ public static function plugin_url( $path ) { return plugins_url( $path, self::$plugin_file ); } /** * Autoload. * * @param string $class Class name. */ public static function autoload( $class ) { $d = DIRECTORY_SEPARATOR; $classes_dir = self::plugin_path( 'classes' . $d ); $separator = strrpos( $class, '\\' ); if ( false !== $separator ) { if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) { return; } $class = substr( $class, $separator + 1 ); } if ( 'Deprecated' === substr( $class, -10 ) ) { $dir = self::plugin_path( 'deprecated' . $d ); } elseif ( self::is_class_abstract( $class ) ) { $dir = $classes_dir . 'abstracts' . $d; } elseif ( self::is_class_migration( $class ) ) { $dir = $classes_dir . 'migration' . $d; } elseif ( 'Schedule' === substr( $class, -8 ) ) { $dir = $classes_dir . 'schedules' . $d; } elseif ( 'Action' === substr( $class, -6 ) ) { $dir = $classes_dir . 'actions' . $d; } elseif ( 'Schema' === substr( $class, -6 ) ) { $dir = $classes_dir . 'schema' . $d; } elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) { $segments = explode( '_', $class ); $type = isset( $segments[1] ) ? $segments[1] : ''; switch ( $type ) { case 'WPCLI': $dir = $classes_dir . 'WP_CLI' . $d; break; case 'DBLogger': case 'DBStore': case 'HybridStore': case 'wpPostStore': case 'wpCommentLogger': $dir = $classes_dir . 'data-stores' . $d; break; default: $dir = $classes_dir; break; } } elseif ( self::is_class_cli( $class ) ) { $dir = $classes_dir . 'WP_CLI' . $d; } elseif ( strpos( $class, 'CronExpression' ) === 0 ) { $dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d ); } elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) { $dir = self::plugin_path( 'lib' . $d ); } else { return; } if ( file_exists( $dir . "{$class}.php" ) ) { include $dir . "{$class}.php"; return; } } /** * Initialize the plugin * * @static * @param string $plugin_file Plugin file path. */ public static function init( $plugin_file ) { self::$plugin_file = $plugin_file; spl_autoload_register( array( __CLASS__, 'autoload' ) ); /** * Fires in the early stages of Action Scheduler init hook. */ do_action( 'action_scheduler_pre_init' ); require_once self::plugin_path( 'functions.php' ); ActionScheduler_DataController::init(); $store = self::store(); $logger = self::logger(); $runner = self::runner(); $admin_view = self::admin_view(); $recurring_action_scheduler = new ActionScheduler_RecurringActionScheduler(); // Ensure initialization on plugin activation. if ( ! did_action( 'init' ) ) { // phpcs:ignore Squiz.PHP.CommentedOutCode add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init(). add_action( 'init', array( $store, 'init' ), 1, 0 ); add_action( 'init', array( $logger, 'init' ), 1, 0 ); add_action( 'init', array( $runner, 'init' ), 1, 0 ); add_action( 'init', array( $recurring_action_scheduler, 'init' ), 1, 0 ); add_action( 'init', /** * Runs after the active store's init() method has been called. * * It would probably be preferable to have $store->init() (or it's parent method) set this itself, * once it has initialized, however that would cause problems in cases where a custom data store is in * use and it has not yet been updated to follow that same logic. */ function () { self::$data_store_initialized = true; /** * Fires when Action Scheduler is ready: it is safe to use the procedural API after this point. * * @since 3.5.5 */ do_action( 'action_scheduler_init' ); }, 1 ); } else { $admin_view->init(); $store->init(); $logger->init(); $runner->init(); $recurring_action_scheduler->init(); self::$data_store_initialized = true; /** * Fires when Action Scheduler is ready: it is safe to use the procedural API after this point. * * @since 3.5.5 */ do_action( 'action_scheduler_init' ); } if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) { require_once self::plugin_path( 'deprecated/functions.php' ); } if ( defined( 'WP_CLI' ) && WP_CLI ) { WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' ); WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Clean_Command' ); WP_CLI::add_command( 'action-scheduler action', '\Action_Scheduler\WP_CLI\Action_Command' ); WP_CLI::add_command( 'action-scheduler', '\Action_Scheduler\WP_CLI\System_Command' ); if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) { $command = new Migration_Command(); $command->register(); } } /** * Handle WP comment cleanup after migration. */ if ( is_a( $logger, 'ActionScheduler_DBLogger' ) && ActionScheduler_DataController::is_migration_complete() && ActionScheduler_WPCommentCleaner::has_logs() ) { ActionScheduler_WPCommentCleaner::init(); } add_action( 'action_scheduler/migration_complete', 'ActionScheduler_WPCommentCleaner::maybe_schedule_cleanup' ); } /** * Check whether the AS data store has been initialized. * * @param string $function_name The name of the function being called. Optional. Default `null`. * @return bool */ public static function is_initialized( $function_name = null ) { if ( ! self::$data_store_initialized && ! empty( $function_name ) ) { $message = sprintf( /* translators: %s function name. */ __( '%s() was called before the Action Scheduler data store was initialized', 'action-scheduler' ), esc_attr( $function_name ) ); _doing_it_wrong( esc_html( $function_name ), esc_html( $message ), '3.1.6' ); } return self::$data_store_initialized; } /** * Determine if the class is one of our abstract classes. * * @since 3.0.0 * * @param string $class The class name. * * @return bool */ protected static function is_class_abstract( $class ) { static $abstracts = array( 'ActionScheduler' => true, 'ActionScheduler_Abstract_ListTable' => true, 'ActionScheduler_Abstract_QueueRunner' => true, 'ActionScheduler_Abstract_Schedule' => true, 'ActionScheduler_Abstract_RecurringSchedule' => true, 'ActionScheduler_Lock' => true, 'ActionScheduler_Logger' => true, 'ActionScheduler_Abstract_Schema' => true, 'ActionScheduler_Store' => true, 'ActionScheduler_TimezoneHelper' => true, 'ActionScheduler_WPCLI_Command' => true, ); return isset( $abstracts[ $class ] ) && $abstracts[ $class ]; } /** * Determine if the class is one of our migration classes. * * @since 3.0.0 * * @param string $class The class name. * * @return bool */ protected static function is_class_migration( $class ) { static $migration_segments = array( 'ActionMigrator' => true, 'BatchFetcher' => true, 'DBStoreMigrator' => true, 'DryRun' => true, 'LogMigrator' => true, 'Config' => true, 'Controller' => true, 'Runner' => true, 'Scheduler' => true, ); $segments = explode( '_', $class ); $segment = isset( $segments[1] ) ? $segments[1] : $class; return isset( $migration_segments[ $segment ] ) && $migration_segments[ $segment ]; } /** * Determine if the class is one of our WP CLI classes. * * @since 3.0.0 * * @param string $class The class name. * * @return bool */ protected static function is_class_cli( $class ) { static $cli_segments = array( 'QueueRunner' => true, 'Command' => true, 'ProgressBar' => true, '\Action_Scheduler\WP_CLI\Action_Command' => true, '\Action_Scheduler\WP_CLI\System_Command' => true, ); $segments = explode( '_', $class ); $segment = isset( $segments[1] ) ? $segments[1] : $class; return isset( $cli_segments[ $segment ] ) && $cli_segments[ $segment ]; } /** * Clone. */ final public function __clone() { trigger_error( 'Singleton. No cloning allowed!', E_USER_ERROR ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error } /** * Wakeup. */ final public function __wakeup() { trigger_error( 'Singleton. No serialization allowed!', E_USER_ERROR ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error } /** * Construct. */ final private function __construct() {} /** Deprecated **/ /** * Get DateTime object. * * @param null|string $when Date/time string. * @param string $timezone Timezone string. */ public static function get_datetime_object( $when = null, $timezone = 'UTC' ) { _deprecated_function( __METHOD__, '2.0', 'wcs_add_months()' ); return as_get_datetime_object( $when, $timezone ); } /** * Issue deprecated warning if an Action Scheduler function is called in the shutdown hook. * * @param string $function_name The name of the function being called. * @deprecated 3.1.6. */ public static function check_shutdown_hook( $function_name ) { _deprecated_function( __FUNCTION__, '3.1.6' ); } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php 0000644 00000011443 15151523433 0024634 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_Schema * * @package Action_Scheduler * * @codeCoverageIgnore * * Utility class for creating/updating custom tables */ abstract class ActionScheduler_Abstract_Schema { /** * Increment this value in derived class to trigger a schema update. * * @var int */ protected $schema_version = 1; /** * Schema version stored in database. * * @var string */ protected $db_version; /** * Names of tables that will be registered by this class. * * @var array */ protected $tables = array(); /** * Can optionally be used by concrete classes to carry out additional initialization work * as needed. */ public function init() {} /** * Register tables with WordPress, and create them if needed. * * @param bool $force_update Optional. Default false. Use true to always run the schema update. * * @return void */ public function register_tables( $force_update = false ) { global $wpdb; // make WP aware of our tables. foreach ( $this->tables as $table ) { $wpdb->tables[] = $table; $name = $this->get_full_table_name( $table ); $wpdb->$table = $name; } // create the tables. if ( $this->schema_update_required() || $force_update ) { foreach ( $this->tables as $table ) { /** * Allow custom processing before updating a table schema. * * @param string $table Name of table being updated. * @param string $db_version Existing version of the table being updated. */ do_action( 'action_scheduler_before_schema_update', $table, $this->db_version ); $this->update_table( $table ); } $this->mark_schema_update_complete(); } } /** * Get table definition. * * @param string $table The name of the table. * * @return string The CREATE TABLE statement, suitable for passing to dbDelta */ abstract protected function get_table_definition( $table ); /** * Determine if the database schema is out of date * by comparing the integer found in $this->schema_version * with the option set in the WordPress options table * * @return bool */ private function schema_update_required() { $option_name = 'schema-' . static::class; $this->db_version = get_option( $option_name, 0 ); // Check for schema option stored by the Action Scheduler Custom Tables plugin in case site has migrated from that plugin with an older schema. if ( 0 === $this->db_version ) { $plugin_option_name = 'schema-'; switch ( static::class ) { case 'ActionScheduler_StoreSchema': $plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Store_Table_Maker'; break; case 'ActionScheduler_LoggerSchema': $plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Logger_Table_Maker'; break; } $this->db_version = get_option( $plugin_option_name, 0 ); delete_option( $plugin_option_name ); } return version_compare( $this->db_version, $this->schema_version, '<' ); } /** * Update the option in WordPress to indicate that * our schema is now up to date * * @return void */ private function mark_schema_update_complete() { $option_name = 'schema-' . static::class; // work around race conditions and ensure that our option updates. $value_to_save = (string) $this->schema_version . '.0.' . time(); update_option( $option_name, $value_to_save ); } /** * Update the schema for the given table * * @param string $table The name of the table to update. * * @return void */ private function update_table( $table ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $definition = $this->get_table_definition( $table ); if ( $definition ) { $updated = dbDelta( $definition ); foreach ( $updated as $updated_table => $update_description ) { if ( strpos( $update_description, 'Created table' ) === 0 ) { do_action( 'action_scheduler/created_table', $updated_table, $table ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } } } } /** * Get full table name. * * @param string $table Table name. * * @return string The full name of the table, including the * table prefix for the current blog */ protected function get_full_table_name( $table ) { return $GLOBALS['wpdb']->prefix . $table; } /** * Confirms that all of the tables registered by this schema class have been created. * * @return bool */ public function tables_exist() { global $wpdb; $tables_exist = true; foreach ( $this->tables as $table_name ) { $table_name = $wpdb->prefix . $table_name; $pattern = str_replace( '_', '\\_', $table_name ); $existing_table = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $pattern ) ); if ( $existing_table !== $table_name ) { $tables_exist = false; break; } } return $tables_exist; } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php 0000644 00000003547 15151523433 0025176 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_Schedule */ abstract class ActionScheduler_Abstract_Schedule extends ActionScheduler_Schedule_Deprecated { /** * The date & time the schedule is set to run. * * @var DateTime */ private $scheduled_date = null; /** * Timestamp equivalent of @see $this->scheduled_date * * @var int */ protected $scheduled_timestamp = null; /** * Construct. * * @param DateTime $date The date & time to run the action. */ public function __construct( DateTime $date ) { $this->scheduled_date = $date; } /** * Check if a schedule should recur. * * @return bool */ abstract public function is_recurring(); /** * Calculate when the next instance of this schedule would run based on a given date & time. * * @param DateTime $after Start timestamp. * @return DateTime */ abstract protected function calculate_next( DateTime $after ); /** * Get the next date & time when this schedule should run after a given date & time. * * @param DateTime $after Start timestamp. * @return DateTime|null */ public function get_next( DateTime $after ) { $after = clone $after; if ( $after > $this->scheduled_date ) { $after = $this->calculate_next( $after ); return $after; } return clone $this->scheduled_date; } /** * Get the date & time the schedule is set to run. * * @return DateTime|null */ public function get_date() { return $this->scheduled_date; } /** * For PHP 5.2 compat, because DateTime objects can't be serialized * * @return array */ public function __sleep() { $this->scheduled_timestamp = $this->scheduled_date->getTimestamp(); return array( 'scheduled_timestamp', ); } /** * Wakeup. */ public function __wakeup() { $this->scheduled_date = as_get_datetime_object( $this->scheduled_timestamp ); unset( $this->scheduled_timestamp ); } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Logger.php 0000644 00000017525 15151523433 0023037 0 ustar 00 <?php /** * Class ActionScheduler_Logger * * @codeCoverageIgnore */ abstract class ActionScheduler_Logger { /** * Instance. * * @var null|self */ private static $logger = null; /** * Get instance. * * @return ActionScheduler_Logger */ public static function instance() { if ( empty( self::$logger ) ) { $class = apply_filters( 'action_scheduler_logger_class', 'ActionScheduler_wpCommentLogger' ); self::$logger = new $class(); } return self::$logger; } /** * Create log entry. * * @param string $action_id Action ID. * @param string $message Log message. * @param DateTime|null $date Log date. * * @return string The log entry ID */ abstract public function log( $action_id, $message, ?DateTime $date = null ); /** * Get action's log entry. * * @param string $entry_id Entry ID. * * @return ActionScheduler_LogEntry */ abstract public function get_entry( $entry_id ); /** * Get action's logs. * * @param string $action_id Action ID. * * @return ActionScheduler_LogEntry[] */ abstract public function get_logs( $action_id ); /** * Initialize. * * @codeCoverageIgnore */ public function init() { $this->hook_stored_action(); add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 ); add_action( 'action_scheduler_begin_execute', array( $this, 'log_started_action' ), 10, 2 ); add_action( 'action_scheduler_after_execute', array( $this, 'log_completed_action' ), 10, 3 ); add_action( 'action_scheduler_failed_execution', array( $this, 'log_failed_action' ), 10, 3 ); add_action( 'action_scheduler_failed_action', array( $this, 'log_timed_out_action' ), 10, 2 ); add_action( 'action_scheduler_unexpected_shutdown', array( $this, 'log_unexpected_shutdown' ), 10, 2 ); add_action( 'action_scheduler_reset_action', array( $this, 'log_reset_action' ), 10, 1 ); add_action( 'action_scheduler_execution_ignored', array( $this, 'log_ignored_action' ), 10, 2 ); add_action( 'action_scheduler_failed_fetch_action', array( $this, 'log_failed_fetch_action' ), 10, 2 ); add_action( 'action_scheduler_failed_to_schedule_next_instance', array( $this, 'log_failed_schedule_next_instance' ), 10, 2 ); add_action( 'action_scheduler_bulk_cancel_actions', array( $this, 'bulk_log_cancel_actions' ), 10, 1 ); } /** * Register callback for storing action. */ public function hook_stored_action() { add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) ); } /** * Unhook callback for storing action. */ public function unhook_stored_action() { remove_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) ); } /** * Log action stored. * * @param int $action_id Action ID. */ public function log_stored_action( $action_id ) { $this->log( $action_id, __( 'action created', 'action-scheduler' ) ); } /** * Log action cancellation. * * @param int $action_id Action ID. */ public function log_canceled_action( $action_id ) { $this->log( $action_id, __( 'action canceled', 'action-scheduler' ) ); } /** * Log action start. * * @param int $action_id Action ID. * @param string $context Action execution context. */ public function log_started_action( $action_id, $context = '' ) { if ( ! empty( $context ) ) { /* translators: %s: context */ $message = sprintf( __( 'action started via %s', 'action-scheduler' ), $context ); } else { $message = __( 'action started', 'action-scheduler' ); } $this->log( $action_id, $message ); } /** * Log action completion. * * @param int $action_id Action ID. * @param null|ActionScheduler_Action $action Action. * @param string $context Action execution context. */ public function log_completed_action( $action_id, $action = null, $context = '' ) { if ( ! empty( $context ) ) { /* translators: %s: context */ $message = sprintf( __( 'action complete via %s', 'action-scheduler' ), $context ); } else { $message = __( 'action complete', 'action-scheduler' ); } $this->log( $action_id, $message ); } /** * Log action failure. * * @param int $action_id Action ID. * @param Exception $exception Exception. * @param string $context Action execution context. */ public function log_failed_action( $action_id, Exception $exception, $context = '' ) { if ( ! empty( $context ) ) { /* translators: 1: context 2: exception message */ $message = sprintf( __( 'action failed via %1$s: %2$s', 'action-scheduler' ), $context, $exception->getMessage() ); } else { /* translators: %s: exception message */ $message = sprintf( __( 'action failed: %s', 'action-scheduler' ), $exception->getMessage() ); } $this->log( $action_id, $message ); } /** * Log action timeout. * * @param int $action_id Action ID. * @param string $timeout Timeout. */ public function log_timed_out_action( $action_id, $timeout ) { /* translators: %s: amount of time */ $this->log( $action_id, sprintf( __( 'action marked as failed after %s seconds. Unknown error occurred. Check server, PHP and database error logs to diagnose cause.', 'action-scheduler' ), $timeout ) ); } /** * Log unexpected shutdown. * * @param int $action_id Action ID. * @param mixed[] $error Error. */ public function log_unexpected_shutdown( $action_id, $error ) { if ( ! empty( $error ) ) { /* translators: 1: error message 2: filename 3: line */ $this->log( $action_id, sprintf( __( 'unexpected shutdown: PHP Fatal error %1$s in %2$s on line %3$s', 'action-scheduler' ), $error['message'], $error['file'], $error['line'] ) ); } } /** * Log action reset. * * @param int $action_id Action ID. */ public function log_reset_action( $action_id ) { $this->log( $action_id, __( 'action reset', 'action-scheduler' ) ); } /** * Log ignored action. * * @param int $action_id Action ID. * @param string $context Action execution context. */ public function log_ignored_action( $action_id, $context = '' ) { if ( ! empty( $context ) ) { /* translators: %s: context */ $message = sprintf( __( 'action ignored via %s', 'action-scheduler' ), $context ); } else { $message = __( 'action ignored', 'action-scheduler' ); } $this->log( $action_id, $message ); } /** * Log the failure of fetching the action. * * @param string $action_id Action ID. * @param null|Exception $exception The exception which occurred when fetching the action. NULL by default for backward compatibility. */ public function log_failed_fetch_action( $action_id, ?Exception $exception = null ) { if ( ! is_null( $exception ) ) { /* translators: %s: exception message */ $log_message = sprintf( __( 'There was a failure fetching this action: %s', 'action-scheduler' ), $exception->getMessage() ); } else { $log_message = __( 'There was a failure fetching this action', 'action-scheduler' ); } $this->log( $action_id, $log_message ); } /** * Log the failure of scheduling the action's next instance. * * @param int $action_id Action ID. * @param Exception $exception Exception object. */ public function log_failed_schedule_next_instance( $action_id, Exception $exception ) { /* translators: %s: exception message */ $this->log( $action_id, sprintf( __( 'There was a failure scheduling the next instance of this action: %s', 'action-scheduler' ), $exception->getMessage() ) ); } /** * Bulk add cancel action log entries. * * Implemented here for backward compatibility. Should be implemented in parent loggers * for more performant bulk logging. * * @param array $action_ids List of action ID. */ public function bulk_log_cancel_actions( $action_ids ) { if ( empty( $action_ids ) ) { return; } foreach ( $action_ids as $action_id ) { $this->log_canceled_action( $action_id ); } } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_ListTable.php 0000644 00000061057 15151523433 0025325 0 ustar 00 <?php if ( ! class_exists( 'WP_List_Table' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php'; } /** * Action Scheduler Abstract List Table class * * This abstract class enhances WP_List_Table making it ready to use. * * By extending this class we can focus on describing how our table looks like, * which columns needs to be shown, filter, ordered by and more and forget about the details. * * This class supports: * - Bulk actions * - Search * - Sortable columns * - Automatic translations of the columns * * @codeCoverageIgnore * @since 2.0.0 */ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table { /** * The table name * * @var string */ protected $table_name; /** * Package name, used to get options from WP_List_Table::get_items_per_page. * * @var string */ protected $package; /** * How many items do we render per page? * * @var int */ protected $items_per_page = 10; /** * Enables search in this table listing. If this array * is empty it means the listing is not searchable. * * @var array */ protected $search_by = array(); /** * Columns to show in the table listing. It is a key => value pair. The * key must much the table column name and the value is the label, which is * automatically translated. * * @var array */ protected $columns = array(); /** * Defines the row-actions. It expects an array where the key * is the column name and the value is an array of actions. * * The array of actions are key => value, where key is the method name * (with the prefix row_action_<key>) and the value is the label * and title. * * @var array */ protected $row_actions = array(); /** * The Primary key of our table * * @var string */ protected $ID = 'ID'; /** * Enables sorting, it expects an array * of columns (the column names are the values) * * @var array */ protected $sort_by = array(); /** * The default sort order * * @var string */ protected $filter_by = array(); /** * The status name => count combinations for this table's items. Used to display status filters. * * @var array */ protected $status_counts = array(); /** * Notices to display when loading the table. Array of arrays of form array( 'class' => {updated|error}, 'message' => 'This is the notice text display.' ). * * @var array */ protected $admin_notices = array(); /** * Localised string displayed in the <h1> element above the able. * * @var string */ protected $table_header; /** * Enables bulk actions. It must be an array where the key is the action name * and the value is the label (which is translated automatically). It is important * to notice that it will check that the method exists (`bulk_$name`) and will throw * an exception if it does not exists. * * This class will automatically check if the current request has a bulk action, will do the * validations and afterwards will execute the bulk method, with two arguments. The first argument * is the array with primary keys, the second argument is a string with a list of the primary keys, * escaped and ready to use (with `IN`). * * @var array */ protected $bulk_actions = array(); /** * Makes translation easier, it basically just wraps * `_x` with some default (the package name). * * @param string $text The new text to translate. * @param string $context The context of the text. * @return string|void The translated text. * * @deprecated 3.0.0 Use `_x()` instead. */ protected function translate( $text, $context = '' ) { return $text; } /** * Reads `$this->bulk_actions` and returns an array that WP_List_Table understands. It * also validates that the bulk method handler exists. It throws an exception because * this is a library meant for developers and missing a bulk method is a development-time error. * * @return array * * @throws RuntimeException Throws RuntimeException when the bulk action does not have a callback method. */ protected function get_bulk_actions() { $actions = array(); foreach ( $this->bulk_actions as $action => $label ) { if ( ! is_callable( array( $this, 'bulk_' . $action ) ) ) { throw new RuntimeException( "The bulk action $action does not have a callback method" ); } $actions[ $action ] = $label; } return $actions; } /** * Checks if the current request has a bulk action. If that is the case it will validate and will * execute the bulk method handler. Regardless if the action is valid or not it will redirect to * the previous page removing the current arguments that makes this request a bulk action. */ protected function process_bulk_action() { global $wpdb; // Detect when a bulk action is being triggered. $action = $this->current_action(); if ( ! $action ) { return; } check_admin_referer( 'bulk-' . $this->_args['plural'] ); $method = 'bulk_' . $action; if ( array_key_exists( $action, $this->bulk_actions ) && is_callable( array( $this, $method ) ) && ! empty( $_GET['ID'] ) && is_array( $_GET['ID'] ) ) { $ids_sql = '(' . implode( ',', array_fill( 0, count( $_GET['ID'] ), '%s' ) ) . ')'; $id = array_map( 'absint', $_GET['ID'] ); $this->$method( $id, $wpdb->prepare( $ids_sql, $id ) ); //phpcs:ignore WordPress.DB.PreparedSQL } if ( isset( $_SERVER['REQUEST_URI'] ) ) { wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce', 'ID', 'action', 'action2' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } } /** * Default code for deleting entries. * validated already by process_bulk_action() * * @param array $ids ids of the items to delete. * @param string $ids_sql the sql for the ids. * @return void */ protected function bulk_delete( array $ids, $ids_sql ) { $store = ActionScheduler::store(); foreach ( $ids as $action_id ) { $store->delete( $action_id ); } } /** * Prepares the _column_headers property which is used by WP_Table_List at rendering. * It merges the columns and the sortable columns. */ protected function prepare_column_headers() { $this->_column_headers = array( $this->get_columns(), get_hidden_columns( $this->screen ), $this->get_sortable_columns(), ); } /** * Reads $this->sort_by and returns the columns name in a format that WP_Table_List * expects */ public function get_sortable_columns() { $sort_by = array(); foreach ( $this->sort_by as $column ) { $sort_by[ $column ] = array( $column, true ); } return $sort_by; } /** * Returns the columns names for rendering. It adds a checkbox for selecting everything * as the first column */ public function get_columns() { $columns = array_merge( array( 'cb' => '<input type="checkbox" />' ), $this->columns ); return $columns; } /** * Get prepared LIMIT clause for items query * * @global wpdb $wpdb * * @return string Prepared LIMIT clause for items query. */ protected function get_items_query_limit() { global $wpdb; $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); return $wpdb->prepare( 'LIMIT %d', $per_page ); } /** * Returns the number of items to offset/skip for this current view. * * @return int */ protected function get_items_offset() { $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); $current_page = $this->get_pagenum(); if ( 1 < $current_page ) { $offset = $per_page * ( $current_page - 1 ); } else { $offset = 0; } return $offset; } /** * Get prepared OFFSET clause for items query * * @global wpdb $wpdb * * @return string Prepared OFFSET clause for items query. */ protected function get_items_query_offset() { global $wpdb; return $wpdb->prepare( 'OFFSET %d', $this->get_items_offset() ); } /** * Prepares the ORDER BY sql statement. It uses `$this->sort_by` to know which * columns are sortable. This requests validates the orderby $_GET parameter is a valid * column and sortable. It will also use order (ASC|DESC) using DESC by default. */ protected function get_items_query_order() { if ( empty( $this->sort_by ) ) { return ''; } $orderby = esc_sql( $this->get_request_orderby() ); $order = esc_sql( $this->get_request_order() ); return "ORDER BY {$orderby} {$order}"; } /** * Querystring arguments to persist between form submissions. * * @since 3.7.3 * * @return string[] */ protected function get_request_query_args_to_persist() { return array_merge( $this->sort_by, array( 'page', 'status', 'tab', ) ); } /** * Return the sortable column specified for this request to order the results by, if any. * * @return string */ protected function get_request_orderby() { $valid_sortable_columns = array_values( $this->sort_by ); if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_sortable_columns, true ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended $orderby = sanitize_text_field( wp_unslash( $_GET['orderby'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended } else { $orderby = $valid_sortable_columns[0]; } return $orderby; } /** * Return the sortable column order specified for this request. * * @return string */ protected function get_request_order() { if ( ! empty( $_GET['order'] ) && 'desc' === strtolower( sanitize_text_field( wp_unslash( $_GET['order'] ) ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended $order = 'DESC'; } else { $order = 'ASC'; } return $order; } /** * Return the status filter for this request, if any. * * @return string */ protected function get_request_status() { $status = ( ! empty( $_GET['status'] ) ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended return $status; } /** * Return the search filter for this request, if any. * * @return string */ protected function get_request_search_query() { $search_query = ( ! empty( $_GET['s'] ) ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended return $search_query; } /** * Process and return the columns name. This is meant for using with SQL, this means it * always includes the primary key. * * @return array */ protected function get_table_columns() { $columns = array_keys( $this->columns ); if ( ! in_array( $this->ID, $columns, true ) ) { $columns[] = $this->ID; } return $columns; } /** * Check if the current request is doing a "full text" search. If that is the case * prepares the SQL to search texts using LIKE. * * If the current request does not have any search or if this list table does not support * that feature it will return an empty string. * * @return string */ protected function get_items_query_search() { global $wpdb; if ( empty( $_GET['s'] ) || empty( $this->search_by ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended return ''; } $search_string = sanitize_text_field( wp_unslash( $_GET['s'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended $filter = array(); foreach ( $this->search_by as $column ) { $wild = '%'; $sql_like = $wild . $wpdb->esc_like( $search_string ) . $wild; $filter[] = $wpdb->prepare( '`' . $column . '` LIKE %s', $sql_like ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.NotPrepared } return implode( ' OR ', $filter ); } /** * Prepares the SQL to filter rows by the options defined at `$this->filter_by`. Before trusting * any data sent by the user it validates that it is a valid option. */ protected function get_items_query_filters() { global $wpdb; if ( ! $this->filter_by || empty( $_GET['filter_by'] ) || ! is_array( $_GET['filter_by'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended return ''; } $filter = array(); foreach ( $this->filter_by as $column => $options ) { if ( empty( $_GET['filter_by'][ $column ] ) || empty( $options[ $_GET['filter_by'][ $column ] ] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended continue; } $filter[] = $wpdb->prepare( "`$column` = %s", sanitize_text_field( wp_unslash( $_GET['filter_by'][ $column ] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQL.InterpolatedNotPrepared } return implode( ' AND ', $filter ); } /** * Prepares the data to feed WP_Table_List. * * This has the core for selecting, sorting and filtering data. To keep the code simple * its logic is split among many methods (get_items_query_*). * * Beside populating the items this function will also count all the records that matches * the filtering criteria and will do fill the pagination variables. */ public function prepare_items() { global $wpdb; $this->process_bulk_action(); $this->process_row_actions(); if ( ! empty( $_REQUEST['_wp_http_referer'] && ! empty( $_SERVER['REQUEST_URI'] ) ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended // _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } $this->prepare_column_headers(); $limit = $this->get_items_query_limit(); $offset = $this->get_items_query_offset(); $order = $this->get_items_query_order(); $where = array_filter( array( $this->get_items_query_search(), $this->get_items_query_filters(), ) ); $columns = '`' . implode( '`, `', $this->get_table_columns() ) . '`'; if ( ! empty( $where ) ) { $where = 'WHERE (' . implode( ') AND (', $where ) . ')'; } else { $where = ''; } $sql = "SELECT $columns FROM {$this->table_name} {$where} {$order} {$limit} {$offset}"; $this->set_items( $wpdb->get_results( $sql, ARRAY_A ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $query_count = "SELECT COUNT({$this->ID}) FROM {$this->table_name} {$where}"; $total_items = $wpdb->get_var( $query_count ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ), ) ); } /** * Display the table. * * @param string $which The name of the table. */ public function extra_tablenav( $which ) { if ( ! $this->filter_by || 'top' !== $which ) { return; } echo '<div class="alignleft actions">'; foreach ( $this->filter_by as $id => $options ) { $default = ! empty( $_GET['filter_by'][ $id ] ) ? sanitize_text_field( wp_unslash( $_GET['filter_by'][ $id ] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( empty( $options[ $default ] ) ) { $default = ''; } echo '<select name="filter_by[' . esc_attr( $id ) . ']" class="first" id="filter-by-' . esc_attr( $id ) . '">'; foreach ( $options as $value => $label ) { echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value === $default ? 'selected' : '' ) . '>' . esc_html( $label ) . '</option>'; } echo '</select>'; } submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) ); echo '</div>'; } /** * Set the data for displaying. It will attempt to unserialize (There is a chance that some columns * are serialized). This can be override in child classes for further data transformation. * * @param array $items Items array. */ protected function set_items( array $items ) { $this->items = array(); foreach ( $items as $item ) { $this->items[ $item[ $this->ID ] ] = array_map( 'maybe_unserialize', $item ); } } /** * Renders the checkbox for each row, this is the first column and it is named ID regardless * of how the primary key is named (to keep the code simpler). The bulk actions will do the proper * name transformation though using `$this->ID`. * * @param array $row The row to render. */ public function column_cb( $row ) { return '<input name="ID[]" type="checkbox" value="' . esc_attr( $row[ $this->ID ] ) . '" />'; } /** * Renders the row-actions. * * This method renders the action menu, it reads the definition from the $row_actions property, * and it checks that the row action method exists before rendering it. * * @param array $row Row to be rendered. * @param string $column_name Column name. * @return string */ protected function maybe_render_actions( $row, $column_name ) { if ( empty( $this->row_actions[ $column_name ] ) ) { return; } $row_id = $row[ $this->ID ]; $actions = '<div class="row-actions">'; $action_count = 0; foreach ( $this->row_actions[ $column_name ] as $action_key => $action ) { $action_count++; if ( ! method_exists( $this, 'row_action_' . $action_key ) ) { continue; } $action_link = ! empty( $action['link'] ) ? $action['link'] : add_query_arg( array( 'row_action' => $action_key, 'row_id' => $row_id, 'nonce' => wp_create_nonce( $action_key . '::' . $row_id ), ) ); $span_class = ! empty( $action['class'] ) ? $action['class'] : $action_key; $separator = ( $action_count < count( $this->row_actions[ $column_name ] ) ) ? ' | ' : ''; $actions .= sprintf( '<span class="%s">', esc_attr( $span_class ) ); $actions .= sprintf( '<a href="%1$s" title="%2$s">%3$s</a>', esc_url( $action_link ), esc_attr( $action['desc'] ), esc_html( $action['name'] ) ); $actions .= sprintf( '%s</span>', $separator ); } $actions .= '</div>'; return $actions; } /** * Process the bulk actions. * * @return void */ protected function process_row_actions() { $parameters = array( 'row_action', 'row_id', 'nonce' ); foreach ( $parameters as $parameter ) { if ( empty( $_REQUEST[ $parameter ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } } $action = sanitize_text_field( wp_unslash( $_REQUEST['row_action'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated $row_id = sanitize_text_field( wp_unslash( $_REQUEST['row_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated $nonce = sanitize_text_field( wp_unslash( $_REQUEST['nonce'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated $method = 'row_action_' . $action; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( wp_verify_nonce( $nonce, $action . '::' . $row_id ) && method_exists( $this, $method ) ) { $this->$method( sanitize_text_field( wp_unslash( $row_id ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended } if ( isset( $_SERVER['REQUEST_URI'] ) ) { wp_safe_redirect( remove_query_arg( array( 'row_id', 'row_action', 'nonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } } /** * Default column formatting, it will escape everything for security. * * @param array $item The item array. * @param string $column_name Column name to display. * * @return string */ public function column_default( $item, $column_name ) { $column_html = esc_html( $item[ $column_name ] ); $column_html .= $this->maybe_render_actions( $item, $column_name ); return $column_html; } /** * Display the table heading and search query, if any */ protected function display_header() { echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>'; if ( $this->get_request_search_query() ) { /* translators: %s: search query */ echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . '</span>'; } echo '<hr class="wp-header-end">'; } /** * Display the table heading and search query, if any */ protected function display_admin_notices() { foreach ( $this->admin_notices as $notice ) { echo '<div id="message" class="' . esc_attr( $notice['class'] ) . '">'; echo ' <p>' . wp_kses_post( $notice['message'] ) . '</p>'; echo '</div>'; } } /** * Prints the available statuses so the user can click to filter. */ protected function display_filter_by_status() { $status_list_items = array(); $request_status = $this->get_request_status(); // Helper to set 'all' filter when not set on status counts passed in. if ( ! isset( $this->status_counts['all'] ) ) { $all_count = array_sum( $this->status_counts ); if ( isset( $this->status_counts['past-due'] ) ) { $all_count -= $this->status_counts['past-due']; } $this->status_counts = array( 'all' => $all_count ) + $this->status_counts; } // Translated status labels. $status_labels = ActionScheduler_Store::instance()->get_status_labels(); $status_labels['all'] = esc_html_x( 'All', 'status labels', 'action-scheduler' ); $status_labels['past-due'] = esc_html_x( 'Past-due', 'status labels', 'action-scheduler' ); foreach ( $this->status_counts as $status_slug => $count ) { if ( 0 === $count ) { continue; } if ( $status_slug === $request_status || ( empty( $request_status ) && 'all' === $status_slug ) ) { $status_list_item = '<li class="%1$s"><a href="%2$s" class="current">%3$s</a> (%4$d)</li>'; } else { $status_list_item = '<li class="%1$s"><a href="%2$s">%3$s</a> (%4$d)</li>'; } $status_name = isset( $status_labels[ $status_slug ] ) ? $status_labels[ $status_slug ] : ucfirst( $status_slug ); $status_filter_url = ( 'all' === $status_slug ) ? remove_query_arg( 'status' ) : add_query_arg( 'status', $status_slug ); $status_filter_url = remove_query_arg( array( 'paged', 's' ), $status_filter_url ); $status_list_items[] = sprintf( $status_list_item, esc_attr( $status_slug ), esc_url( $status_filter_url ), esc_html( $status_name ), absint( $count ) ); } if ( $status_list_items ) { echo '<ul class="subsubsub">'; echo implode( " | \n", $status_list_items ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo '</ul>'; } } /** * Renders the table list, we override the original class to render the table inside a form * and to render any needed HTML (like the search box). By doing so the callee of a function can simple * forget about any extra HTML. */ protected function display_table() { echo '<form id="' . esc_attr( $this->_args['plural'] ) . '-filter" method="get">'; foreach ( $this->get_request_query_args_to_persist() as $arg ) { $arg_value = isset( $_GET[ $arg ] ) ? sanitize_text_field( wp_unslash( $_GET[ $arg ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( ! $arg_value ) { continue; } echo '<input type="hidden" name="' . esc_attr( $arg ) . '" value="' . esc_attr( $arg_value ) . '" />'; } if ( ! empty( $this->search_by ) ) { echo $this->search_box( $this->get_search_box_button_text(), 'plugin' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } parent::display(); echo '</form>'; } /** * Process any pending actions. */ public function process_actions() { $this->process_bulk_action(); $this->process_row_actions(); if ( ! empty( $_REQUEST['_wp_http_referer'] ) && ! empty( $_SERVER['REQUEST_URI'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended // _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter wp_safe_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); exit; } } /** * Render the list table page, including header, notices, status filters and table. */ public function display_page() { $this->prepare_items(); echo '<div class="wrap">'; $this->display_header(); $this->display_admin_notices(); $this->display_filter_by_status(); $this->display_table(); echo '</div>'; } /** * Get the text to display in the search box on the list table. */ protected function get_search_box_placeholder() { return esc_html__( 'Search', 'action-scheduler' ); } /** * Gets the screen per_page option name. * * @return string */ protected function get_per_page_option_name() { return $this->package . '_items_per_page'; } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php 0000644 00000011415 15151523433 0024542 0 ustar 00 <?php /** * Class ActionScheduler_TimezoneHelper */ abstract class ActionScheduler_TimezoneHelper { /** * DateTimeZone object. * * @var null|DateTimeZone */ private static $local_timezone = null; /** * Set a DateTime's timezone to the WordPress site's timezone, or a UTC offset * if no timezone string is available. * * @since 2.1.0 * * @param DateTime $date Timestamp. * @return ActionScheduler_DateTime */ public static function set_local_timezone( DateTime $date ) { // Accept a DateTime for easier backward compatibility, even though we require methods on ActionScheduler_DateTime. if ( ! is_a( $date, 'ActionScheduler_DateTime' ) ) { $date = as_get_datetime_object( $date->format( 'U' ) ); } if ( get_option( 'timezone_string' ) ) { $date->setTimezone( new DateTimeZone( self::get_local_timezone_string() ) ); } else { $date->setUtcOffset( self::get_local_timezone_offset() ); } return $date; } /** * Helper to retrieve the timezone string for a site until a WP core method exists * (see https://core.trac.wordpress.org/ticket/24730). * * Adapted from wc_timezone_string() and https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155. * * If no timezone string is set, and its not possible to match the UTC offset set for the site to a timezone * string, then an empty string will be returned, and the UTC offset should be used to set a DateTime's * timezone. * * @since 2.1.0 * @param bool $reset Unused. * @return string PHP timezone string for the site or empty if no timezone string is available. */ protected static function get_local_timezone_string( $reset = false ) { // If site timezone string exists, return it. $timezone = get_option( 'timezone_string' ); if ( $timezone ) { return $timezone; } // Get UTC offset, if it isn't set then return UTC. $utc_offset = intval( get_option( 'gmt_offset', 0 ) ); if ( 0 === $utc_offset ) { return 'UTC'; } // Adjust UTC offset from hours to seconds. $utc_offset *= 3600; // Attempt to guess the timezone string from the UTC offset. $timezone = timezone_name_from_abbr( '', $utc_offset ); if ( $timezone ) { return $timezone; } // Last try, guess timezone string manually. foreach ( timezone_abbreviations_list() as $abbr ) { foreach ( $abbr as $city ) { if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) { // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- we are actually interested in the runtime timezone. return $city['timezone_id']; } } } // No timezone string. return ''; } /** * Get timezone offset in seconds. * * @since 2.1.0 * @return float */ protected static function get_local_timezone_offset() { $timezone = get_option( 'timezone_string' ); if ( $timezone ) { $timezone_object = new DateTimeZone( $timezone ); return $timezone_object->getOffset( new DateTime( 'now' ) ); } else { return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS; } } /** * Get local timezone. * * @param bool $reset Toggle to discard stored value. * @deprecated 2.1.0 */ public static function get_local_timezone( $reset = false ) { _deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' ); if ( $reset ) { self::$local_timezone = null; } if ( ! isset( self::$local_timezone ) ) { $tzstring = get_option( 'timezone_string' ); if ( empty( $tzstring ) ) { $gmt_offset = absint( get_option( 'gmt_offset' ) ); if ( 0 === $gmt_offset ) { $tzstring = 'UTC'; } else { $gmt_offset *= HOUR_IN_SECONDS; $tzstring = timezone_name_from_abbr( '', $gmt_offset, 1 ); // If there's no timezone string, try again with no DST. if ( false === $tzstring ) { $tzstring = timezone_name_from_abbr( '', $gmt_offset, 0 ); } // Try mapping to the first abbreviation we can find. if ( false === $tzstring ) { $is_dst = date( 'I' ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- we are actually interested in the runtime timezone. foreach ( timezone_abbreviations_list() as $abbr ) { foreach ( $abbr as $city ) { if ( $city['dst'] === $is_dst && $city['offset'] === $gmt_offset ) { // If there's no valid timezone ID, keep looking. if ( is_null( $city['timezone_id'] ) ) { continue; } $tzstring = $city['timezone_id']; break 2; } } } } // If we still have no valid string, then fall back to UTC. if ( false === $tzstring ) { $tzstring = 'UTC'; } } } self::$local_timezone = new DateTimeZone( $tzstring ); } return self::$local_timezone; } } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php 0000644 00000032712 15151523433 0025714 0 ustar 00 <?php /** * Abstract class with common Queue Cleaner functionality. */ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abstract_QueueRunner_Deprecated { /** * ActionScheduler_QueueCleaner instance. * * @var ActionScheduler_QueueCleaner */ protected $cleaner; /** * ActionScheduler_FatalErrorMonitor instance. * * @var ActionScheduler_FatalErrorMonitor */ protected $monitor; /** * ActionScheduler_Store instance. * * @var ActionScheduler_Store */ protected $store; /** * The created time. * * Represents when the queue runner was constructed and used when calculating how long a PHP request has been running. * For this reason it should be as close as possible to the PHP request start time. * * @var int */ private $created_time; /** * ActionScheduler_Abstract_QueueRunner constructor. * * @param ActionScheduler_Store|null $store Store object. * @param ActionScheduler_FatalErrorMonitor|null $monitor Monitor object. * @param ActionScheduler_QueueCleaner|null $cleaner Cleaner object. */ public function __construct( ?ActionScheduler_Store $store = null, ?ActionScheduler_FatalErrorMonitor $monitor = null, ?ActionScheduler_QueueCleaner $cleaner = null ) { $this->created_time = microtime( true ); $this->store = $store ? $store : ActionScheduler_Store::instance(); $this->monitor = $monitor ? $monitor : new ActionScheduler_FatalErrorMonitor( $this->store ); $this->cleaner = $cleaner ? $cleaner : new ActionScheduler_QueueCleaner( $this->store ); } /** * Process an individual action. * * @param int $action_id The action ID to process. * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @throws \Exception When error running action. */ public function process_action( $action_id, $context = '' ) { // Temporarily override the error handler while we process the current action. // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler set_error_handler( /** * Temporary error handler which can catch errors and convert them into exceptions. This facilitates more * robust error handling across all supported PHP versions. * * @throws Exception * * @param int $type Error level expressed as an integer. * @param string $message Error message. */ function ( $type, $message ) { throw new Exception( $message ); }, E_USER_ERROR | E_RECOVERABLE_ERROR ); /* * The nested try/catch structure is required because we potentially need to convert thrown errors into * exceptions (and an exception thrown from a catch block cannot be caught by a later catch block in the *same* * structure). */ try { try { $valid_action = true; do_action( 'action_scheduler_before_execute', $action_id, $context ); if ( ActionScheduler_Store::STATUS_PENDING !== $this->store->get_status( $action_id ) ) { $valid_action = false; do_action( 'action_scheduler_execution_ignored', $action_id, $context ); return; } do_action( 'action_scheduler_begin_execute', $action_id, $context ); $action = $this->store->fetch_action( $action_id ); $this->store->log_execution( $action_id ); $action->execute(); do_action( 'action_scheduler_after_execute', $action_id, $action, $context ); $this->store->mark_complete( $action_id ); } catch ( Throwable $e ) { // Throwable is defined when executing under PHP 7.0 and up. We convert it to an exception, for // compatibility with ActionScheduler_Logger. throw new Exception( $e->getMessage(), $e->getCode(), $e ); } } catch ( Exception $e ) { // This catch block exists for compatibility with PHP 5.6. $this->handle_action_error( $action_id, $e, $context, $valid_action ); } finally { restore_error_handler(); } if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) { $this->schedule_next_instance( $action, $action_id ); } } /** * Marks actions as either having failed execution or failed validation, as appropriate. * * @param int $action_id Action ID. * @param Exception $e Exception instance. * @param string $context Execution context. * @param bool $valid_action If the action is valid. * * @return void */ private function handle_action_error( $action_id, $e, $context, $valid_action ) { if ( $valid_action ) { $this->store->mark_failure( $action_id ); /** * Runs when action execution fails. * * @param int $action_id Action ID. * @param Exception $e Exception instance. * @param string $context Execution context. */ do_action( 'action_scheduler_failed_execution', $action_id, $e, $context ); } else { /** * Runs when action validation fails. * * @param int $action_id Action ID. * @param Exception $e Exception instance. * @param string $context Execution context. */ do_action( 'action_scheduler_failed_validation', $action_id, $e, $context ); } } /** * Schedule the next instance of the action if necessary. * * @param ActionScheduler_Action $action Action. * @param int $action_id Action ID. */ protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) { // If a recurring action has been consistently failing, we may wish to stop rescheduling it. if ( ActionScheduler_Store::STATUS_FAILED === $this->store->get_status( $action_id ) && $this->recurring_action_is_consistently_failing( $action, $action_id ) ) { ActionScheduler_Logger::instance()->log( $action_id, __( 'This action appears to be consistently failing. A new instance will not be scheduled.', 'action-scheduler' ) ); return; } try { ActionScheduler::factory()->repeat( $action ); } catch ( Exception $e ) { do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action ); } } /** * Determine if the specified recurring action has been consistently failing. * * @param ActionScheduler_Action $action The recurring action to be rescheduled. * @param int $action_id The ID of the recurring action. * * @return bool */ private function recurring_action_is_consistently_failing( ActionScheduler_Action $action, $action_id ) { /** * Controls the failure threshold for recurring actions. * * Before rescheduling a recurring action, we look at its status. If it failed, we then check if all of the most * recent actions (upto the threshold set by this filter) sharing the same hook have also failed: if they have, * that is considered consistent failure and a new instance of the action will not be scheduled. * * @param int $failure_threshold Number of actions of the same hook to examine for failure. Defaults to 5. */ $consistent_failure_threshold = (int) apply_filters( 'action_scheduler_recurring_action_failure_threshold', 5 ); // This query should find the earliest *failing* action (for the hook we are interested in) within our threshold. $query_args = array( 'hook' => $action->get_hook(), 'status' => ActionScheduler_Store::STATUS_FAILED, 'date' => date_create( 'now', timezone_open( 'UTC' ) )->format( 'Y-m-d H:i:s' ), 'date_compare' => '<', 'per_page' => 1, 'offset' => $consistent_failure_threshold - 1, ); $first_failing_action_id = $this->store->query_actions( $query_args ); // If we didn't retrieve an action ID, then there haven't been enough failures for us to worry about. if ( empty( $first_failing_action_id ) ) { return false; } // Now let's fetch the first action (having the same hook) of *any status* within the same window. unset( $query_args['status'] ); $first_action_id_with_the_same_hook = $this->store->query_actions( $query_args ); /** * If a recurring action is assessed as consistently failing, it will not be rescheduled. This hook provides a * way to observe and optionally override that assessment. * * @param bool $is_consistently_failing If the action is considered to be consistently failing. * @param ActionScheduler_Action $action The action being assessed. */ return (bool) apply_filters( 'action_scheduler_recurring_action_is_consistently_failing', $first_action_id_with_the_same_hook === $first_failing_action_id, $action ); } /** * Run the queue cleaner. */ protected function run_cleanup() { $this->cleaner->clean( 10 * $this->get_time_limit() ); } /** * Get the number of concurrent batches a runner allows. * * @return int */ public function get_allowed_concurrent_batches() { return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 1 ); } /** * Check if the number of allowed concurrent batches is met or exceeded. * * @return bool */ public function has_maximum_concurrent_batches() { return $this->store->get_claim_count() >= $this->get_allowed_concurrent_batches(); } /** * Get the maximum number of seconds a batch can run for. * * @return int The number of seconds. */ protected function get_time_limit() { $time_limit = 30; // Apply deprecated filter from deprecated get_maximum_execution_time() method. if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) { _deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' ); $time_limit = apply_filters( 'action_scheduler_maximum_execution_time', $time_limit ); } return absint( apply_filters( 'action_scheduler_queue_runner_time_limit', $time_limit ) ); } /** * Get the number of seconds the process has been running. * * @return int The number of seconds. */ protected function get_execution_time() { $execution_time = microtime( true ) - $this->created_time; // Get the CPU time if the hosting environment uses it rather than wall-clock time to calculate a process's execution time. if ( function_exists( 'getrusage' ) && apply_filters( 'action_scheduler_use_cpu_execution_time', defined( 'PANTHEON_ENVIRONMENT' ) ) ) { $resource_usages = getrusage(); if ( isset( $resource_usages['ru_stime.tv_usec'], $resource_usages['ru_stime.tv_usec'] ) ) { $execution_time = $resource_usages['ru_stime.tv_sec'] + ( $resource_usages['ru_stime.tv_usec'] / 1000000 ); } } return $execution_time; } /** * Check if the host's max execution time is (likely) to be exceeded if processing more actions. * * @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action. * @return bool */ protected function time_likely_to_be_exceeded( $processed_actions ) { $execution_time = $this->get_execution_time(); $max_execution_time = $this->get_time_limit(); // Safety against division by zero errors. if ( 0 === $processed_actions ) { return $execution_time >= $max_execution_time; } $time_per_action = $execution_time / $processed_actions; $estimated_time = $execution_time + ( $time_per_action * 3 ); $likely_to_be_exceeded = $estimated_time > $max_execution_time; return apply_filters( 'action_scheduler_maximum_execution_time_likely_to_be_exceeded', $likely_to_be_exceeded, $this, $processed_actions, $execution_time, $max_execution_time ); } /** * Get memory limit * * Based on WP_Background_Process::get_memory_limit() * * @return int */ protected function get_memory_limit() { if ( function_exists( 'ini_get' ) ) { $memory_limit = ini_get( 'memory_limit' ); } else { $memory_limit = '128M'; // Sensible default, and minimum required by WooCommerce. } if ( ! $memory_limit || -1 === $memory_limit || '-1' === $memory_limit ) { // Unlimited, set to 32GB. $memory_limit = '32G'; } return ActionScheduler_Compatibility::convert_hr_to_bytes( $memory_limit ); } /** * Memory exceeded * * Ensures the batch process never exceeds 90% of the maximum WordPress memory. * * Based on WP_Background_Process::memory_exceeded() * * @return bool */ protected function memory_exceeded() { $memory_limit = $this->get_memory_limit() * 0.90; $current_memory = memory_get_usage( true ); $memory_exceeded = $current_memory >= $memory_limit; return apply_filters( 'action_scheduler_memory_exceeded', $memory_exceeded, $this ); } /** * See if the batch limits have been exceeded, which is when memory usage is almost at * the maximum limit, or the time to process more actions will exceed the max time limit. * * Based on WC_Background_Process::batch_limits_exceeded() * * @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action. * @return bool */ protected function batch_limits_exceeded( $processed_actions ) { return $this->memory_exceeded() || $this->time_likely_to_be_exceeded( $processed_actions ); } /** * Process actions in the queue. * * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @return int The number of actions processed. */ abstract public function run( $context = '' ); } woocommerce/action-scheduler/classes/abstracts/ActionScheduler_WPCLI_Command.php 0000644 00000004073 15151523433 0024126 0 ustar 00 <?php /** * Abstract for WP-CLI commands. */ abstract class ActionScheduler_WPCLI_Command extends \WP_CLI_Command { const DATE_FORMAT = 'Y-m-d H:i:s O'; /** * Keyed arguments. * * @var string[] */ protected $args; /** * Positional arguments. * * @var array<string, string> */ protected $assoc_args; /** * Construct. * * @param string[] $args Positional arguments. * @param array<string, string> $assoc_args Keyed arguments. * @throws \Exception When loading a CLI command file outside of WP CLI context. */ public function __construct( array $args, array $assoc_args ) { if ( ! defined( 'WP_CLI' ) || ! constant( 'WP_CLI' ) ) { /* translators: %s php class name */ throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), get_class( $this ) ) ); } $this->args = $args; $this->assoc_args = $assoc_args; } /** * Execute command. */ abstract public function execute(); /** * Get the scheduled date in a human friendly format. * * @see ActionScheduler_ListTable::get_schedule_display_string() * @param ActionScheduler_Schedule $schedule Schedule. * @return string */ protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) { $schedule_display_string = ''; if ( ! $schedule->get_date() ) { return '0000-00-00 00:00:00'; } $next_timestamp = $schedule->get_date()->getTimestamp(); $schedule_display_string .= $schedule->get_date()->format( static::DATE_FORMAT ); return $schedule_display_string; } /** * Transforms arguments with '__' from CSV into expected arrays. * * @see \WP_CLI\CommandWithDBObject::process_csv_arguments_to_arrays() * @link https://github.com/wp-cli/entity-command/blob/c270cc9a2367cb8f5845f26a6b5e203397c91392/src/WP_CLI/CommandWithDBObject.php#L99 * @return void */ protected function process_csv_arguments_to_arrays() { foreach ( $this->assoc_args as $k => $v ) { if ( false !== strpos( $k, '__' ) ) { $this->assoc_args[ $k ] = explode( ',', $v ); } } } } woocommerce/action-scheduler/classes/migration/DryRun_LogMigrator.php 0000644 00000000713 15151523433 0022207 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class DryRun_LogMigrator * * @package Action_Scheduler\Migration * * @codeCoverageIgnore */ class DryRun_LogMigrator extends LogMigrator { /** * Simulate migrating an action log. * * @param int $source_action_id Source logger object. * @param int $destination_action_id Destination logger object. */ public function migrate( $source_action_id, $destination_action_id ) { // no-op. } } woocommerce/action-scheduler/classes/migration/Scheduler.php 0000644 00000006050 15151523433 0020374 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class Scheduler * * @package Action_Scheduler\WP_CLI * * @since 3.0.0 * * @codeCoverageIgnore */ class Scheduler { /** Migration action hook. */ const HOOK = 'action_scheduler/migration_hook'; /** Migration action group. */ const GROUP = 'action-scheduler-migration'; /** * Set up the callback for the scheduled job. */ public function hook() { add_action( self::HOOK, array( $this, 'run_migration' ), 10, 0 ); } /** * Remove the callback for the scheduled job. */ public function unhook() { remove_action( self::HOOK, array( $this, 'run_migration' ), 10 ); } /** * The migration callback. */ public function run_migration() { $migration_runner = $this->get_migration_runner(); $count = $migration_runner->run( $this->get_batch_size() ); if ( 0 === $count ) { $this->mark_complete(); } else { $this->schedule_migration( time() + $this->get_schedule_interval() ); } } /** * Mark the migration complete. */ public function mark_complete() { $this->unschedule_migration(); \ActionScheduler_DataController::mark_migration_complete(); do_action( 'action_scheduler/migration_complete' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Get a flag indicating whether the migration is scheduled. * * @return bool Whether there is a pending action in the store to handle the migration */ public function is_migration_scheduled() { $next = as_next_scheduled_action( self::HOOK ); return ! empty( $next ); } /** * Schedule the migration. * * @param int $when Optional timestamp to run the next migration batch. Defaults to now. * * @return string The action ID */ public function schedule_migration( $when = 0 ) { $next = as_next_scheduled_action( self::HOOK ); if ( ! empty( $next ) ) { return $next; } if ( empty( $when ) ) { $when = time() + MINUTE_IN_SECONDS; } return as_schedule_single_action( $when, self::HOOK, array(), self::GROUP ); } /** * Remove the scheduled migration action. */ public function unschedule_migration() { as_unschedule_action( self::HOOK, null, self::GROUP ); } /** * Get migration batch schedule interval. * * @return int Seconds between migration runs. Defaults to 0 seconds to allow chaining migration via Async Runners. */ private function get_schedule_interval() { return (int) apply_filters( 'action_scheduler/migration_interval', 0 ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Get migration batch size. * * @return int Number of actions to migrate in each batch. Defaults to 250. */ private function get_batch_size() { return (int) apply_filters( 'action_scheduler/migration_batch_size', 250 ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Get migration runner object. * * @return Runner */ private function get_migration_runner() { $config = Controller::instance()->get_migration_config_object(); return new Runner( $config ); } } woocommerce/action-scheduler/classes/migration/ActionScheduler_DBStoreMigrator.php 0000644 00000003453 15151523433 0024625 0 ustar 00 <?php /** * Class ActionScheduler_DBStoreMigrator * * A class for direct saving of actions to the table data store during migration. * * @since 3.0.0 */ class ActionScheduler_DBStoreMigrator extends ActionScheduler_DBStore { /** * Save an action with optional last attempt date. * * Normally, saving an action sets its attempted date to 0000-00-00 00:00:00 because when an action is first saved, * it can't have been attempted yet, but migrated completed actions will have an attempted date, so we need to save * that when first saving the action. * * @param ActionScheduler_Action $action Action to migrate. * @param null|DateTime $scheduled_date Optional date of the first instance to store. * @param null|DateTime $last_attempt_date Optional date the action was last attempted. * * @return string The action ID * @throws \RuntimeException When the action is not saved. */ public function save_action( ActionScheduler_Action $action, ?DateTime $scheduled_date = null, ?DateTime $last_attempt_date = null ) { try { /** * Global. * * @var \wpdb $wpdb */ global $wpdb; $action_id = parent::save_action( $action, $scheduled_date ); if ( null !== $last_attempt_date ) { $data = array( 'last_attempt_gmt' => $this->get_scheduled_date_string( $action, $last_attempt_date ), 'last_attempt_local' => $this->get_scheduled_date_string_local( $action, $last_attempt_date ), ); $wpdb->update( $wpdb->actionscheduler_actions, $data, array( 'action_id' => $action_id ), array( '%s', '%s' ), array( '%d' ) ); } return $action_id; } catch ( \Exception $e ) { // translators: %s is an error message. throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 ); } } } woocommerce/action-scheduler/classes/migration/Runner.php 0000644 00000010174 15151523433 0017731 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class Runner * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class Runner { /** * Source store instance. * * @var ActionScheduler_Store */ private $source_store; /** * Destination store instance. * * @var ActionScheduler_Store */ private $destination_store; /** * Source logger instance. * * @var ActionScheduler_Logger */ private $source_logger; /** * Destination logger instance. * * @var ActionScheduler_Logger */ private $destination_logger; /** * Batch fetcher instance. * * @var BatchFetcher */ private $batch_fetcher; /** * Action migrator instance. * * @var ActionMigrator */ private $action_migrator; /** * Log migrator instance. * * @var LogMigrator */ private $log_migrator; /** * Progress bar instance. * * @var ProgressBar */ private $progress_bar; /** * Runner constructor. * * @param Config $config Migration configuration object. */ public function __construct( Config $config ) { $this->source_store = $config->get_source_store(); $this->destination_store = $config->get_destination_store(); $this->source_logger = $config->get_source_logger(); $this->destination_logger = $config->get_destination_logger(); $this->batch_fetcher = new BatchFetcher( $this->source_store ); if ( $config->get_dry_run() ) { $this->log_migrator = new DryRun_LogMigrator( $this->source_logger, $this->destination_logger ); $this->action_migrator = new DryRun_ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator ); } else { $this->log_migrator = new LogMigrator( $this->source_logger, $this->destination_logger ); $this->action_migrator = new ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator ); } if ( defined( 'WP_CLI' ) && WP_CLI ) { $this->progress_bar = $config->get_progress_bar(); } } /** * Run migration batch. * * @param int $batch_size Optional batch size. Default 10. * * @return int Size of batch processed. */ public function run( $batch_size = 10 ) { $batch = $this->batch_fetcher->fetch( $batch_size ); $batch_size = count( $batch ); if ( ! $batch_size ) { return 0; } if ( $this->progress_bar ) { /* translators: %d: amount of actions */ $this->progress_bar->set_message( sprintf( _n( 'Migrating %d action', 'Migrating %d actions', $batch_size, 'action-scheduler' ), $batch_size ) ); $this->progress_bar->set_count( $batch_size ); } $this->migrate_actions( $batch ); return $batch_size; } /** * Migration a batch of actions. * * @param array $action_ids List of action IDs to migrate. */ public function migrate_actions( array $action_ids ) { do_action( 'action_scheduler/migration_batch_starting', $action_ids ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores \ActionScheduler::logger()->unhook_stored_action(); $this->destination_logger->unhook_stored_action(); foreach ( $action_ids as $source_action_id ) { $destination_action_id = $this->action_migrator->migrate( $source_action_id ); if ( $destination_action_id ) { $this->destination_logger->log( $destination_action_id, sprintf( /* translators: 1: source action ID 2: source store class 3: destination action ID 4: destination store class */ __( 'Migrated action with ID %1$d in %2$s to ID %3$d in %4$s', 'action-scheduler' ), $source_action_id, get_class( $this->source_store ), $destination_action_id, get_class( $this->destination_store ) ) ); } if ( $this->progress_bar ) { $this->progress_bar->tick(); } } if ( $this->progress_bar ) { $this->progress_bar->finish(); } \ActionScheduler::logger()->hook_stored_action(); do_action( 'action_scheduler/migration_batch_complete', $action_ids ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Initialize destination store and logger. */ public function init_destination() { $this->destination_store->init(); $this->destination_logger->init(); } } woocommerce/action-scheduler/classes/migration/DryRun_ActionMigrator.php 0000644 00000001052 15151523433 0022700 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class DryRun_ActionMigrator * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class DryRun_ActionMigrator extends ActionMigrator { /** * Simulate migrating an action. * * @param int $source_action_id Action ID. * * @return int */ public function migrate( $source_action_id ) { do_action( 'action_scheduler/migrate_action_dry_run', $source_action_id ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return 0; } } woocommerce/action-scheduler/classes/migration/LogMigrator.php 0000644 00000002441 15151523433 0020704 0 ustar 00 <?php namespace Action_Scheduler\Migration; use ActionScheduler_Logger; /** * Class LogMigrator * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class LogMigrator { /** * Source logger instance. * * @var ActionScheduler_Logger */ private $source; /** * Destination logger instance. * * @var ActionScheduler_Logger */ private $destination; /** * ActionMigrator constructor. * * @param ActionScheduler_Logger $source_logger Source logger object. * @param ActionScheduler_Logger $destination_logger Destination logger object. */ public function __construct( ActionScheduler_Logger $source_logger, ActionScheduler_Logger $destination_logger ) { $this->source = $source_logger; $this->destination = $destination_logger; } /** * Migrate an action log. * * @param int $source_action_id Source logger object. * @param int $destination_action_id Destination logger object. */ public function migrate( $source_action_id, $destination_action_id ) { $logs = $this->source->get_logs( $source_action_id ); foreach ( $logs as $log ) { if ( absint( $log->get_action_id() ) === absint( $source_action_id ) ) { $this->destination->log( $destination_action_id, $log->get_message(), $log->get_date() ); } } } } woocommerce/action-scheduler/classes/migration/Controller.php 0000644 00000014574 15151523433 0020613 0 ustar 00 <?php namespace Action_Scheduler\Migration; use ActionScheduler_DataController; use ActionScheduler_LoggerSchema; use ActionScheduler_StoreSchema; use Action_Scheduler\WP_CLI\ProgressBar; /** * Class Controller * * The main plugin/initialization class for migration to custom tables. * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class Controller { /** * Instance. * * @var self */ private static $instance; /** * Scheduler instance. * * @var Action_Scheduler\Migration\Scheduler */ private $migration_scheduler; /** * Class name of the store object. * * @var string */ private $store_classname; /** * Class name of the logger object. * * @var string */ private $logger_classname; /** * Flag to indicate migrating custom store. * * @var bool */ private $migrate_custom_store; /** * Controller constructor. * * @param Scheduler $migration_scheduler Migration scheduler object. */ protected function __construct( Scheduler $migration_scheduler ) { $this->migration_scheduler = $migration_scheduler; $this->store_classname = ''; } /** * Set the action store class name. * * @param string $class Classname of the store class. * * @return string */ public function get_store_class( $class ) { if ( \ActionScheduler_DataController::is_migration_complete() ) { return \ActionScheduler_DataController::DATASTORE_CLASS; } elseif ( \ActionScheduler_Store::DEFAULT_CLASS !== $class ) { $this->store_classname = $class; return $class; } else { return 'ActionScheduler_HybridStore'; } } /** * Set the action logger class name. * * @param string $class Classname of the logger class. * * @return string */ public function get_logger_class( $class ) { \ActionScheduler_Store::instance(); if ( $this->has_custom_datastore() ) { $this->logger_classname = $class; return $class; } else { return \ActionScheduler_DataController::LOGGER_CLASS; } } /** * Get flag indicating whether a custom datastore is in use. * * @return bool */ public function has_custom_datastore() { return (bool) $this->store_classname; } /** * Set up the background migration process. * * @return void */ public function schedule_migration() { $logging_tables = new ActionScheduler_LoggerSchema(); $store_tables = new ActionScheduler_StoreSchema(); /* * In some unusual cases, the expected tables may not have been created. In such cases * we do not schedule a migration as doing so will lead to fatal error conditions. * * In such cases the user will likely visit the Tools > Scheduled Actions screen to * investigate, and will see appropriate messaging (this step also triggers an attempt * to rebuild any missing tables). * * @see https://github.com/woocommerce/action-scheduler/issues/653 */ if ( ActionScheduler_DataController::is_migration_complete() || $this->migration_scheduler->is_migration_scheduled() || ! $store_tables->tables_exist() || ! $logging_tables->tables_exist() ) { return; } $this->migration_scheduler->schedule_migration(); } /** * Get the default migration config object * * @return ActionScheduler\Migration\Config */ public function get_migration_config_object() { static $config = null; if ( ! $config ) { $source_store = $this->store_classname ? new $this->store_classname() : new \ActionScheduler_wpPostStore(); $source_logger = $this->logger_classname ? new $this->logger_classname() : new \ActionScheduler_wpCommentLogger(); $config = new Config(); $config->set_source_store( $source_store ); $config->set_source_logger( $source_logger ); $config->set_destination_store( new \ActionScheduler_DBStoreMigrator() ); $config->set_destination_logger( new \ActionScheduler_DBLogger() ); if ( defined( 'WP_CLI' ) && WP_CLI ) { $config->set_progress_bar( new ProgressBar( '', 0 ) ); } } return apply_filters( 'action_scheduler/migration_config', $config ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Hook dashboard migration notice. */ public function hook_admin_notices() { if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) { return; } add_action( 'admin_notices', array( $this, 'display_migration_notice' ), 10, 0 ); } /** * Show a dashboard notice that migration is in progress. */ public function display_migration_notice() { printf( '<div class="notice notice-warning"><p>%s</p></div>', esc_html__( 'Action Scheduler migration in progress. The list of scheduled actions may be incomplete.', 'action-scheduler' ) ); } /** * Add store classes. Hook migration. */ private function hook() { add_filter( 'action_scheduler_store_class', array( $this, 'get_store_class' ), 100, 1 ); add_filter( 'action_scheduler_logger_class', array( $this, 'get_logger_class' ), 100, 1 ); add_action( 'init', array( $this, 'maybe_hook_migration' ) ); add_action( 'wp_loaded', array( $this, 'schedule_migration' ) ); // Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen. add_action( 'load-tools_page_action-scheduler', array( $this, 'hook_admin_notices' ), 10, 0 ); add_action( 'load-woocommerce_page_wc-status', array( $this, 'hook_admin_notices' ), 10, 0 ); } /** * Possibly hook the migration scheduler action. */ public function maybe_hook_migration() { if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) { return; } $this->migration_scheduler->hook(); } /** * Allow datastores to enable migration to AS tables. */ public function allow_migration() { if ( ! \ActionScheduler_DataController::dependencies_met() ) { return false; } if ( null === $this->migrate_custom_store ) { $this->migrate_custom_store = apply_filters( 'action_scheduler_migrate_data_store', false ); } return ( ! $this->has_custom_datastore() ) || $this->migrate_custom_store; } /** * Proceed with the migration if the dependencies have been met. */ public static function init() { if ( \ActionScheduler_DataController::dependencies_met() ) { self::instance()->hook(); } } /** * Singleton factory. */ public static function instance() { if ( ! isset( self::$instance ) ) { self::$instance = new static( new Scheduler() ); } return self::$instance; } } woocommerce/action-scheduler/classes/migration/Config.php 0000644 00000010156 15151523433 0017665 0 ustar 00 <?php namespace Action_Scheduler\Migration; use Action_Scheduler\WP_CLI\ProgressBar; use ActionScheduler_Logger as Logger; use ActionScheduler_Store as Store; /** * Class Config * * @package Action_Scheduler\Migration * * @since 3.0.0 * * A config builder for the ActionScheduler\Migration\Runner class */ class Config { /** * Source store instance. * * @var ActionScheduler_Store */ private $source_store; /** * Source logger instance. * * @var ActionScheduler_Logger */ private $source_logger; /** * Destination store instance. * * @var ActionScheduler_Store */ private $destination_store; /** * Destination logger instance. * * @var ActionScheduler_Logger */ private $destination_logger; /** * Progress bar object. * * @var Action_Scheduler\WP_CLI\ProgressBar */ private $progress_bar; /** * Flag indicating a dryrun. * * @var bool */ private $dry_run = false; /** * Config constructor. */ public function __construct() { } /** * Get the configured source store. * * @return ActionScheduler_Store * @throws \RuntimeException When source store is not configured. */ public function get_source_store() { if ( empty( $this->source_store ) ) { throw new \RuntimeException( __( 'Source store must be configured before running a migration', 'action-scheduler' ) ); } return $this->source_store; } /** * Set the configured source store. * * @param ActionScheduler_Store $store Source store object. */ public function set_source_store( Store $store ) { $this->source_store = $store; } /** * Get the configured source logger. * * @return ActionScheduler_Logger * @throws \RuntimeException When source logger is not configured. */ public function get_source_logger() { if ( empty( $this->source_logger ) ) { throw new \RuntimeException( __( 'Source logger must be configured before running a migration', 'action-scheduler' ) ); } return $this->source_logger; } /** * Set the configured source logger. * * @param ActionScheduler_Logger $logger Logger object. */ public function set_source_logger( Logger $logger ) { $this->source_logger = $logger; } /** * Get the configured destination store. * * @return ActionScheduler_Store * @throws \RuntimeException When destination store is not configured. */ public function get_destination_store() { if ( empty( $this->destination_store ) ) { throw new \RuntimeException( __( 'Destination store must be configured before running a migration', 'action-scheduler' ) ); } return $this->destination_store; } /** * Set the configured destination store. * * @param ActionScheduler_Store $store Action store object. */ public function set_destination_store( Store $store ) { $this->destination_store = $store; } /** * Get the configured destination logger. * * @return ActionScheduler_Logger * @throws \RuntimeException When destination logger is not configured. */ public function get_destination_logger() { if ( empty( $this->destination_logger ) ) { throw new \RuntimeException( __( 'Destination logger must be configured before running a migration', 'action-scheduler' ) ); } return $this->destination_logger; } /** * Set the configured destination logger. * * @param ActionScheduler_Logger $logger Logger object. */ public function set_destination_logger( Logger $logger ) { $this->destination_logger = $logger; } /** * Get flag indicating whether it's a dry run. * * @return bool */ public function get_dry_run() { return $this->dry_run; } /** * Set flag indicating whether it's a dry run. * * @param bool $dry_run Dry run toggle. */ public function set_dry_run( $dry_run ) { $this->dry_run = (bool) $dry_run; } /** * Get progress bar object. * * @return ActionScheduler\WPCLI\ProgressBar */ public function get_progress_bar() { return $this->progress_bar; } /** * Set progress bar object. * * @param ActionScheduler\WPCLI\ProgressBar $progress_bar Progress bar object. */ public function set_progress_bar( ProgressBar $progress_bar ) { $this->progress_bar = $progress_bar; } } woocommerce/action-scheduler/classes/migration/ActionMigrator.php 0000644 00000010253 15151523433 0021400 0 ustar 00 <?php namespace Action_Scheduler\Migration; /** * Class ActionMigrator * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class ActionMigrator { /** * Source store instance. * * @var ActionScheduler_Store */ private $source; /** * Destination store instance. * * @var ActionScheduler_Store */ private $destination; /** * LogMigrator instance. * * @var LogMigrator */ private $log_migrator; /** * ActionMigrator constructor. * * @param \ActionScheduler_Store $source_store Source store object. * @param \ActionScheduler_Store $destination_store Destination store object. * @param LogMigrator $log_migrator Log migrator object. */ public function __construct( \ActionScheduler_Store $source_store, \ActionScheduler_Store $destination_store, LogMigrator $log_migrator ) { $this->source = $source_store; $this->destination = $destination_store; $this->log_migrator = $log_migrator; } /** * Migrate an action. * * @param int $source_action_id Action ID. * * @return int 0|new action ID * @throws \RuntimeException When unable to delete action from the source store. */ public function migrate( $source_action_id ) { try { $action = $this->source->fetch_action( $source_action_id ); $status = $this->source->get_status( $source_action_id ); } catch ( \Exception $e ) { $action = null; $status = ''; } if ( is_null( $action ) || empty( $status ) || ! $action->get_schedule()->get_date() ) { // null action or empty status means the fetch operation failed or the action didn't exist. // null schedule means it's missing vital data. // delete it and move on. try { $this->source->delete_action( $source_action_id ); } catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch // nothing to do, it didn't exist in the first place. } do_action( 'action_scheduler/no_action_to_migrate', $source_action_id, $this->source, $this->destination ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return 0; } try { // Make sure the last attempt date is set correctly for completed and failed actions. $last_attempt_date = ( \ActionScheduler_Store::STATUS_PENDING !== $status ) ? $this->source->get_date( $source_action_id ) : null; $destination_action_id = $this->destination->save_action( $action, null, $last_attempt_date ); } catch ( \Exception $e ) { do_action( 'action_scheduler/migrate_action_failed', $source_action_id, $this->source, $this->destination ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return 0; // could not save the action in the new store. } try { switch ( $status ) { case \ActionScheduler_Store::STATUS_FAILED: $this->destination->mark_failure( $destination_action_id ); break; case \ActionScheduler_Store::STATUS_CANCELED: $this->destination->cancel_action( $destination_action_id ); break; } $this->log_migrator->migrate( $source_action_id, $destination_action_id ); $this->source->delete_action( $source_action_id ); $test_action = $this->source->fetch_action( $source_action_id ); if ( ! is_a( $test_action, 'ActionScheduler_NullAction' ) ) { // translators: %s is an action ID. throw new \RuntimeException( sprintf( __( 'Unable to remove source migrated action %s', 'action-scheduler' ), $source_action_id ) ); } do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return $destination_action_id; } catch ( \Exception $e ) { // could not delete from the old store. $this->source->mark_migrated( $source_action_id ); // phpcs:disable WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'action_scheduler/migrate_action_incomplete', $source_action_id, $destination_action_id, $this->source, $this->destination ); do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination ); // phpcs:enable return $destination_action_id; } } } woocommerce/action-scheduler/classes/migration/BatchFetcher.php 0000644 00000003350 15151523433 0021000 0 ustar 00 <?php namespace Action_Scheduler\Migration; use ActionScheduler_Store as Store; /** * Class BatchFetcher * * @package Action_Scheduler\Migration * * @since 3.0.0 * * @codeCoverageIgnore */ class BatchFetcher { /** * Store instance. * * @var ActionScheduler_Store */ private $store; /** * BatchFetcher constructor. * * @param ActionScheduler_Store $source_store Source store object. */ public function __construct( Store $source_store ) { $this->store = $source_store; } /** * Retrieve a list of actions. * * @param int $count The number of actions to retrieve. * * @return int[] A list of action IDs */ public function fetch( $count = 10 ) { foreach ( $this->get_query_strategies( $count ) as $query ) { $action_ids = $this->store->query_actions( $query ); if ( ! empty( $action_ids ) ) { return $action_ids; } } return array(); } /** * Generate a list of prioritized of action search parameters. * * @param int $count Number of actions to find. * * @return array */ private function get_query_strategies( $count ) { $now = as_get_datetime_object(); $args = array( 'date' => $now, 'per_page' => $count, 'offset' => 0, 'orderby' => 'date', 'order' => 'ASC', ); $priorities = array( Store::STATUS_PENDING, Store::STATUS_FAILED, Store::STATUS_CANCELED, Store::STATUS_COMPLETE, Store::STATUS_RUNNING, '', // any other unanticipated status. ); foreach ( $priorities as $status ) { yield wp_parse_args( array( 'status' => $status, 'date_compare' => '<=', ), $args ); yield wp_parse_args( array( 'status' => $status, 'date_compare' => '>=', ), $args ); } } } woocommerce/action-scheduler/classes/ActionScheduler_ActionClaim.php 0000644 00000001214 15151523433 0022001 0 ustar 00 <?php /** * Class ActionScheduler_ActionClaim */ class ActionScheduler_ActionClaim { /** * Claim ID. * * @var string */ private $id = ''; /** * Claimed action IDs. * * @var int[] */ private $action_ids = array(); /** * Construct. * * @param string $id Claim ID. * @param int[] $action_ids Action IDs. */ public function __construct( $id, array $action_ids ) { $this->id = $id; $this->action_ids = $action_ids; } /** * Get claim ID. */ public function get_id() { return $this->id; } /** * Get IDs of claimed actions. */ public function get_actions() { return $this->action_ids; } } woocommerce/action-scheduler/classes/ActionScheduler_InvalidActionException.php 0000644 00000002717 15151523433 0024232 0 ustar 00 <?php /** * InvalidAction Exception. * * Used for identifying actions that are invalid in some way. * * @package ActionScheduler */ class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception { /** * Create a new exception when the action's schedule cannot be fetched. * * @param string $action_id The action ID with bad args. * @param mixed $schedule Passed schedule. * @return static */ public static function from_schedule( $action_id, $schedule ) { $message = sprintf( /* translators: 1: action ID 2: schedule */ __( 'Action [%1$s] has an invalid schedule: %2$s', 'action-scheduler' ), $action_id, var_export( $schedule, true ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export ); return new static( $message ); } /** * Create a new exception when the action's args cannot be decoded to an array. * * @param string $action_id The action ID with bad args. * @param mixed $args Passed arguments. * @return static */ public static function from_decoding_args( $action_id, $args = array() ) { $message = sprintf( /* translators: 1: action ID 2: arguments */ __( 'Action [%1$s] has invalid arguments. It cannot be JSON decoded to an array. $args = %2$s', 'action-scheduler' ), $action_id, var_export( $args, true ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export ); return new static( $message ); } } woocommerce/action-scheduler/classes/ActionScheduler_LogEntry.php 0000644 00000003626 15151523433 0021372 0 ustar 00 <?php /** * Class ActionScheduler_LogEntry */ class ActionScheduler_LogEntry { /** * Action's ID for log entry. * * @var int $action_id */ protected $action_id = ''; /** * Log entry's message. * * @var string $message */ protected $message = ''; /** * Log entry's date. * * @var Datetime $date */ protected $date; /** * Constructor * * @param mixed $action_id Action ID. * @param string $message Message. * @param Datetime $date Datetime object with the time when this log entry was created. If this parameter is * not provided a new Datetime object (with current time) will be created. */ public function __construct( $action_id, $message, $date = null ) { /* * ActionScheduler_wpCommentLogger::get_entry() previously passed a 3rd param of $comment->comment_type * to ActionScheduler_LogEntry::__construct(), goodness knows why, and the Follow-up Emails plugin * hard-codes loading its own version of ActionScheduler_wpCommentLogger with that out-dated method, * goodness knows why, so we need to guard against that here instead of using a DateTime type declaration * for the constructor's 3rd param of $date and causing a fatal error with older versions of FUE. */ if ( null !== $date && ! is_a( $date, 'DateTime' ) ) { _doing_it_wrong( __METHOD__, 'The third parameter must be a valid DateTime instance, or null.', '2.0.0' ); $date = null; } $this->action_id = $action_id; $this->message = $message; $this->date = $date ? $date : new Datetime(); } /** * Returns the date when this log entry was created * * @return Datetime */ public function get_date() { return $this->date; } /** * Get action ID of log entry. */ public function get_action_id() { return $this->action_id; } /** * Get log entry message. */ public function get_message() { return $this->message; } } woocommerce/action-scheduler/classes/ActionScheduler_DataController.php 0000644 00000013211 15151523434 0022534 0 ustar 00 <?php use Action_Scheduler\Migration\Controller; /** * Class ActionScheduler_DataController * * The main plugin/initialization class for the data stores. * * Responsible for hooking everything up with WordPress. * * @package Action_Scheduler * * @since 3.0.0 */ class ActionScheduler_DataController { /** Action data store class name. */ const DATASTORE_CLASS = 'ActionScheduler_DBStore'; /** Logger data store class name. */ const LOGGER_CLASS = 'ActionScheduler_DBLogger'; /** Migration status option name. */ const STATUS_FLAG = 'action_scheduler_migration_status'; /** Migration status option value. */ const STATUS_COMPLETE = 'complete'; /** Migration minimum required PHP version. */ const MIN_PHP_VERSION = '5.5'; /** * Instance. * * @var ActionScheduler_DataController */ private static $instance; /** * Sleep time in seconds. * * @var int */ private static $sleep_time = 0; /** * Tick count required for freeing memory. * * @var int */ private static $free_ticks = 50; /** * Get a flag indicating whether the migration environment dependencies are met. * * @return bool */ public static function dependencies_met() { $php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' ); return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true ); } /** * Get a flag indicating whether the migration is complete. * * @return bool Whether the flag has been set marking the migration as complete */ public static function is_migration_complete() { return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE; } /** * Mark the migration as complete. */ public static function mark_migration_complete() { update_option( self::STATUS_FLAG, self::STATUS_COMPLETE ); } /** * Unmark migration when a plugin is de-activated. Will not work in case of silent activation, for example in an update. * We do this to mitigate the bug of lost actions which happens if there was an AS 2.x to AS 3.x migration in the past, but that plugin is now * deactivated and the site was running on AS 2.x again. */ public static function mark_migration_incomplete() { delete_option( self::STATUS_FLAG ); } /** * Set the action store class name. * * @param string $class Classname of the store class. * * @return string */ public static function set_store_class( $class ) { return self::DATASTORE_CLASS; } /** * Set the action logger class name. * * @param string $class Classname of the logger class. * * @return string */ public static function set_logger_class( $class ) { return self::LOGGER_CLASS; } /** * Set the sleep time in seconds. * * @param integer $sleep_time The number of seconds to pause before resuming operation. */ public static function set_sleep_time( $sleep_time ) { self::$sleep_time = (int) $sleep_time; } /** * Set the tick count required for freeing memory. * * @param integer $free_ticks The number of ticks to free memory on. */ public static function set_free_ticks( $free_ticks ) { self::$free_ticks = (int) $free_ticks; } /** * Free memory if conditions are met. * * @param int $ticks Current tick count. */ public static function maybe_free_memory( $ticks ) { if ( self::$free_ticks && 0 === $ticks % self::$free_ticks ) { self::free_memory(); } } /** * Reduce memory footprint by clearing the database query and object caches. */ public static function free_memory() { if ( 0 < self::$sleep_time ) { /* translators: %d: amount of time */ \WP_CLI::warning( sprintf( _n( 'Stopped the insanity for %d second', 'Stopped the insanity for %d seconds', self::$sleep_time, 'action-scheduler' ), self::$sleep_time ) ); sleep( self::$sleep_time ); } \WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) ); /** * Globals. * * @var $wpdb \wpdb * @var $wp_object_cache \WP_Object_Cache */ global $wpdb, $wp_object_cache; $wpdb->queries = array(); if ( ! is_a( $wp_object_cache, 'WP_Object_Cache' ) ) { return; } // Not all drop-ins support these props, however, there may be existing installations that rely on these being cleared. if ( property_exists( $wp_object_cache, 'group_ops' ) ) { $wp_object_cache->group_ops = array(); } if ( property_exists( $wp_object_cache, 'stats' ) ) { $wp_object_cache->stats = array(); } if ( property_exists( $wp_object_cache, 'memcache_debug' ) ) { $wp_object_cache->memcache_debug = array(); } if ( property_exists( $wp_object_cache, 'cache' ) ) { $wp_object_cache->cache = array(); } if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) { call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important! } } /** * Connect to table datastores if migration is complete. * Otherwise, proceed with the migration if the dependencies have been met. */ public static function init() { if ( self::is_migration_complete() ) { add_filter( 'action_scheduler_store_class', array( 'ActionScheduler_DataController', 'set_store_class' ), 100 ); add_filter( 'action_scheduler_logger_class', array( 'ActionScheduler_DataController', 'set_logger_class' ), 100 ); add_action( 'deactivate_plugin', array( 'ActionScheduler_DataController', 'mark_migration_incomplete' ) ); } elseif ( self::dependencies_met() ) { Controller::init(); } add_action( 'action_scheduler/progress_tick', array( 'ActionScheduler_DataController', 'maybe_free_memory' ) ); } /** * Singleton factory. */ public static function instance() { if ( ! isset( self::$instance ) ) { self::$instance = new static(); } return self::$instance; } } woocommerce/action-scheduler/classes/actions/ActionScheduler_CanceledAction.php 0000644 00000001563 15151523434 0024122 0 ustar 00 <?php /** * Class ActionScheduler_CanceledAction * * Stored action which was canceled and therefore acts like a finished action but should always return a null schedule, * regardless of schedule passed to its constructor. */ class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction { /** * Construct. * * @param string $hook Action's hook. * @param array $args Action's arguments. * @param null|ActionScheduler_Schedule $schedule Action's schedule. * @param string $group Action's group. */ public function __construct( $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) { parent::__construct( $hook, $args, $schedule, $group ); if ( is_null( $schedule ) ) { $this->set_schedule( new ActionScheduler_NullSchedule() ); } } } woocommerce/action-scheduler/classes/actions/ActionScheduler_Action.php 0000644 00000007510 15151523434 0022501 0 ustar 00 <?php /** * Class ActionScheduler_Action */ class ActionScheduler_Action { /** * Action's hook. * * @var string */ protected $hook = ''; /** * Action's args. * * @var array<string, mixed> */ protected $args = array(); /** * Action's schedule. * * @var ActionScheduler_Schedule */ protected $schedule = null; /** * Action's group. * * @var string */ protected $group = ''; /** * Priorities are conceptually similar to those used for regular WordPress actions. * Like those, a lower priority takes precedence over a higher priority and the default * is 10. * * Unlike regular WordPress actions, the priority of a scheduled action is strictly an * integer and should be kept within the bounds 0-255 (anything outside the bounds will * be brought back into the acceptable range). * * @var int */ protected $priority = 10; /** * Construct. * * @param string $hook Action's hook. * @param mixed[] $args Action's arguments. * @param null|ActionScheduler_Schedule $schedule Action's schedule. * @param string $group Action's group. */ public function __construct( $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) { $schedule = empty( $schedule ) ? new ActionScheduler_NullSchedule() : $schedule; $this->set_hook( $hook ); $this->set_schedule( $schedule ); $this->set_args( $args ); $this->set_group( $group ); } /** * Executes the action. * * If no callbacks are registered, an exception will be thrown and the action will not be * fired. This is useful to help detect cases where the code responsible for setting up * a scheduled action no longer exists. * * @throws Exception If no callbacks are registered for this action. */ public function execute() { $hook = $this->get_hook(); if ( ! has_action( $hook ) ) { throw new Exception( sprintf( /* translators: 1: action hook. */ __( 'Scheduled action for %1$s will not be executed as no callbacks are registered.', 'action-scheduler' ), $hook ) ); } do_action_ref_array( $hook, array_values( $this->get_args() ) ); } /** * Set action's hook. * * @param string $hook Action's hook. */ protected function set_hook( $hook ) { $this->hook = $hook; } /** * Get action's hook. */ public function get_hook() { return $this->hook; } /** * Set action's schedule. * * @param ActionScheduler_Schedule $schedule Action's schedule. */ protected function set_schedule( ActionScheduler_Schedule $schedule ) { $this->schedule = $schedule; } /** * Action's schedule. * * @return ActionScheduler_Schedule */ public function get_schedule() { return $this->schedule; } /** * Set action's args. * * @param mixed[] $args Action's arguments. */ protected function set_args( array $args ) { $this->args = $args; } /** * Get action's args. */ public function get_args() { return $this->args; } /** * Section action's group. * * @param string $group Action's group. */ protected function set_group( $group ) { $this->group = $group; } /** * Action's group. * * @return string */ public function get_group() { return $this->group; } /** * Action has not finished. * * @return bool */ public function is_finished() { return false; } /** * Sets the priority of the action. * * @param int $priority Priority level (lower is higher priority). Should be in the range 0-255. * * @return void */ public function set_priority( $priority ) { if ( $priority < 0 ) { $priority = 0; } elseif ( $priority > 255 ) { $priority = 255; } $this->priority = (int) $priority; } /** * Gets the action priority. * * @return int */ public function get_priority() { return $this->priority; } } woocommerce/action-scheduler/classes/actions/ActionScheduler_FinishedAction.php 0000644 00000000450 15151523434 0024147 0 ustar 00 <?php /** * Class ActionScheduler_FinishedAction */ class ActionScheduler_FinishedAction extends ActionScheduler_Action { /** * Execute action. */ public function execute() { // don't execute. } /** * Get finished state. */ public function is_finished() { return true; } } woocommerce/action-scheduler/classes/actions/ActionScheduler_NullAction.php 0000644 00000001131 15151523434 0023325 0 ustar 00 <?php /** * Class ActionScheduler_NullAction */ class ActionScheduler_NullAction extends ActionScheduler_Action { /** * Construct. * * @param string $hook Action hook. * @param mixed[] $args Action arguments. * @param null|ActionScheduler_Schedule $schedule Action schedule. */ public function __construct( $hook = '', array $args = array(), ?ActionScheduler_Schedule $schedule = null ) { $this->set_schedule( new ActionScheduler_NullSchedule() ); } /** * Execute action. */ public function execute() { // don't execute. } } woocommerce/action-scheduler/classes/ActionScheduler_ListTable.php 0000644 00000052166 15151523434 0021516 0 ustar 00 <?php /** * Implements the admin view of the actions. * * @codeCoverageIgnore */ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable { /** * The package name. * * @var string */ protected $package = 'action-scheduler'; /** * Columns to show (name => label). * * @var array */ protected $columns = array(); /** * Actions (name => label). * * @var array */ protected $row_actions = array(); /** * The active data stores * * @var ActionScheduler_Store */ protected $store; /** * A logger to use for getting action logs to display * * @var ActionScheduler_Logger */ protected $logger; /** * A ActionScheduler_QueueRunner runner instance (or child class) * * @var ActionScheduler_QueueRunner */ protected $runner; /** * Bulk actions. The key of the array is the method name of the implementation. * Example: bulk_<key>(array $ids, string $sql_in). * * See the comments in the parent class for further details * * @var array */ protected $bulk_actions = array(); /** * Flag variable to render our notifications, if any, once. * * @var bool */ protected static $did_notification = false; /** * Array of seconds for common time periods, like week or month, alongside an internationalised string representation, i.e. "Day" or "Days" * * @var array */ private static $time_periods; /** * Sets the current data store object into `store->action` and initialises the object. * * @param ActionScheduler_Store $store Store object. * @param ActionScheduler_Logger $logger Logger object. * @param ActionScheduler_QueueRunner $runner Runner object. */ public function __construct( ActionScheduler_Store $store, ActionScheduler_Logger $logger, ActionScheduler_QueueRunner $runner ) { $this->store = $store; $this->logger = $logger; $this->runner = $runner; $this->table_header = __( 'Scheduled Actions', 'action-scheduler' ); $this->bulk_actions = array( 'delete' => __( 'Delete', 'action-scheduler' ), ); $this->columns = array( 'hook' => __( 'Hook', 'action-scheduler' ), 'status' => __( 'Status', 'action-scheduler' ), 'args' => __( 'Arguments', 'action-scheduler' ), 'group' => __( 'Group', 'action-scheduler' ), 'recurrence' => __( 'Recurrence', 'action-scheduler' ), 'schedule' => __( 'Scheduled Date', 'action-scheduler' ), 'log_entries' => __( 'Log', 'action-scheduler' ), ); $this->sort_by = array( 'schedule', 'hook', 'group', ); $this->search_by = array( 'hook', 'args', 'claim_id', ); $request_status = $this->get_request_status(); if ( empty( $request_status ) ) { $this->sort_by[] = 'status'; } elseif ( in_array( $request_status, array( 'in-progress', 'failed' ), true ) ) { $this->columns += array( 'claim_id' => __( 'Claim ID', 'action-scheduler' ) ); $this->sort_by[] = 'claim_id'; } $this->row_actions = array( 'hook' => array( 'run' => array( 'name' => __( 'Run', 'action-scheduler' ), 'desc' => __( 'Process the action now as if it were run as part of a queue', 'action-scheduler' ), ), 'cancel' => array( 'name' => __( 'Cancel', 'action-scheduler' ), 'desc' => __( 'Cancel the action now to avoid it being run in future', 'action-scheduler' ), 'class' => 'cancel trash', ), ), ); self::$time_periods = array( array( 'seconds' => YEAR_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ), ), array( 'seconds' => MONTH_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ), ), array( 'seconds' => WEEK_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ), ), array( 'seconds' => DAY_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ), ), array( 'seconds' => HOUR_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ), ), array( 'seconds' => MINUTE_IN_SECONDS, /* translators: %s: amount of time */ 'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ), ), array( 'seconds' => 1, /* translators: %s: amount of time */ 'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ), ), ); parent::__construct( array( 'singular' => 'action-scheduler', 'plural' => 'action-scheduler', 'ajax' => false, ) ); add_screen_option( 'per_page', array( 'default' => $this->items_per_page, ) ); add_filter( 'set_screen_option_' . $this->get_per_page_option_name(), array( $this, 'set_items_per_page_option' ), 10, 3 ); set_screen_options(); } /** * Handles setting the items_per_page option for this screen. * * @param mixed $status Default false (to skip saving the current option). * @param string $option Screen option name. * @param int $value Screen option value. * @return int */ public function set_items_per_page_option( $status, $option, $value ) { return $value; } /** * Convert an interval of seconds into a two part human friendly string. * * The WordPress human_time_diff() function only calculates the time difference to one degree, meaning * even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step * further to display two degrees of accuracy. * * Inspired by the Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/ * * @param int $interval A interval in seconds. * @param int $periods_to_include Depth of time periods to include, e.g. for an interval of 70, and $periods_to_include of 2, both minutes and seconds would be included. With a value of 1, only minutes would be included. * @return string A human friendly string representation of the interval. */ private static function human_interval( $interval, $periods_to_include = 2 ) { if ( $interval <= 0 ) { return __( 'Now!', 'action-scheduler' ); } $output = ''; $num_time_periods = count( self::$time_periods ); for ( $time_period_index = 0, $periods_included = 0, $seconds_remaining = $interval; $time_period_index < $num_time_periods && $seconds_remaining > 0 && $periods_included < $periods_to_include; $time_period_index++ ) { $periods_in_interval = floor( $seconds_remaining / self::$time_periods[ $time_period_index ]['seconds'] ); if ( $periods_in_interval > 0 ) { if ( ! empty( $output ) ) { $output .= ' '; } $output .= sprintf( translate_nooped_plural( self::$time_periods[ $time_period_index ]['names'], $periods_in_interval, 'action-scheduler' ), $periods_in_interval ); $seconds_remaining -= $periods_in_interval * self::$time_periods[ $time_period_index ]['seconds']; $periods_included++; } } return $output; } /** * Returns the recurrence of an action or 'Non-repeating'. The output is human readable. * * @param ActionScheduler_Action $action Action object. * * @return string */ protected function get_recurrence( $action ) { $schedule = $action->get_schedule(); if ( $schedule->is_recurring() && method_exists( $schedule, 'get_recurrence' ) ) { $recurrence = $schedule->get_recurrence(); if ( is_numeric( $recurrence ) ) { /* translators: %s: time interval */ return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) ); } else { return $recurrence; } } return __( 'Non-repeating', 'action-scheduler' ); } /** * Serializes the argument of an action to render it in a human friendly format. * * @param array $row The array representation of the current row of the table. * * @return string */ public function column_args( array $row ) { if ( empty( $row['args'] ) ) { return apply_filters( 'action_scheduler_list_table_column_args', '', $row ); } $row_html = '<ul>'; foreach ( $row['args'] as $key => $value ) { $row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export } $row_html .= '</ul>'; return apply_filters( 'action_scheduler_list_table_column_args', $row_html, $row ); } /** * Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal. * * @param array $row Action array. * @return string */ public function column_log_entries( array $row ) { $log_entries_html = '<ol>'; $timezone = new DateTimezone( 'UTC' ); foreach ( $row['log_entries'] as $log_entry ) { $log_entries_html .= $this->get_log_entry_html( $log_entry, $timezone ); } $log_entries_html .= '</ol>'; return $log_entries_html; } /** * Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal. * * @param ActionScheduler_LogEntry $log_entry Log entry object. * @param DateTimezone $timezone Timestamp. * @return string */ protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) { $date = $log_entry->get_date(); $date->setTimezone( $timezone ); return sprintf( '<li><strong>%s</strong><br/>%s</li>', esc_html( $date->format( 'Y-m-d H:i:s O' ) ), esc_html( $log_entry->get_message() ) ); } /** * Only display row actions for pending actions. * * @param array $row Row to render. * @param string $column_name Current row. * * @return string */ protected function maybe_render_actions( $row, $column_name ) { if ( 'pending' === strtolower( $row['status_name'] ) ) { return parent::maybe_render_actions( $row, $column_name ); } return ''; } /** * Renders admin notifications * * Notifications: * 1. When the maximum number of tasks are being executed simultaneously. * 2. Notifications when a task is manually executed. * 3. Tables are missing. */ public function display_admin_notices() { global $wpdb; if ( ( is_a( $this->store, 'ActionScheduler_HybridStore' ) || is_a( $this->store, 'ActionScheduler_DBStore' ) ) && apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) { $table_list = array( 'actionscheduler_actions', 'actionscheduler_logs', 'actionscheduler_groups', 'actionscheduler_claims', ); $found_tables = $wpdb->get_col( "SHOW TABLES LIKE '{$wpdb->prefix}actionscheduler%'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared foreach ( $table_list as $table_name ) { if ( ! in_array( $wpdb->prefix . $table_name, $found_tables, true ) ) { $this->admin_notices[] = array( 'class' => 'error', 'message' => __( 'It appears one or more database tables were missing. Attempting to re-create the missing table(s).', 'action-scheduler' ), ); $this->recreate_tables(); parent::display_admin_notices(); return; } } } if ( $this->runner->has_maximum_concurrent_batches() ) { $claim_count = $this->store->get_claim_count(); $this->admin_notices[] = array( 'class' => 'updated', 'message' => sprintf( /* translators: %s: amount of claims */ _n( 'Maximum simultaneous queues already in progress (%s queue). No additional queues will begin processing until the current queues are complete.', 'Maximum simultaneous queues already in progress (%s queues). No additional queues will begin processing until the current queues are complete.', $claim_count, 'action-scheduler' ), $claim_count ), ); } elseif ( $this->store->has_pending_actions_due() ) { $async_request_lock_expiration = ActionScheduler::lock()->get_expiration( 'async-request-runner' ); // No lock set or lock expired. if ( false === $async_request_lock_expiration || $async_request_lock_expiration < time() ) { $in_progress_url = add_query_arg( 'status', 'in-progress', remove_query_arg( 'status' ) ); /* translators: %s: process URL */ $async_request_message = sprintf( __( 'A new queue has begun processing. <a href="%s">View actions in-progress »</a>', 'action-scheduler' ), esc_url( $in_progress_url ) ); } else { /* translators: %d: seconds */ $async_request_message = sprintf( __( 'The next queue will begin processing in approximately %d seconds.', 'action-scheduler' ), $async_request_lock_expiration - time() ); } $this->admin_notices[] = array( 'class' => 'notice notice-info', 'message' => $async_request_message, ); } $notification = get_transient( 'action_scheduler_admin_notice' ); if ( is_array( $notification ) ) { delete_transient( 'action_scheduler_admin_notice' ); $action = $this->store->fetch_action( $notification['action_id'] ); $action_hook_html = '<strong><code>' . $action->get_hook() . '</code></strong>'; if ( 1 === absint( $notification['success'] ) ) { $class = 'updated'; switch ( $notification['row_action_type'] ) { case 'run': /* translators: %s: action HTML */ $action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html ); break; case 'cancel': /* translators: %s: action HTML */ $action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html ); break; default: /* translators: %s: action HTML */ $action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html ); break; } } else { $class = 'error'; /* translators: 1: action HTML 2: action ID 3: error message */ $action_message_html = sprintf( __( 'Could not process change for action: "%1$s" (ID: %2$d). Error: %3$s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) ); } $action_message_html = apply_filters( 'action_scheduler_admin_notice_html', $action_message_html, $action, $notification ); $this->admin_notices[] = array( 'class' => $class, 'message' => $action_message_html, ); } parent::display_admin_notices(); } /** * Prints the scheduled date in a human friendly format. * * @param array $row The array representation of the current row of the table. * * @return string */ public function column_schedule( $row ) { return $this->get_schedule_display_string( $row['schedule'] ); } /** * Get the scheduled date in a human friendly format. * * @param ActionScheduler_Schedule $schedule Action's schedule. * @return string */ protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) { $schedule_display_string = ''; if ( is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) { return __( 'async', 'action-scheduler' ); } if ( ! method_exists( $schedule, 'get_date' ) || ! $schedule->get_date() ) { return '0000-00-00 00:00:00'; } $next_timestamp = $schedule->get_date()->getTimestamp(); $schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' ); $schedule_display_string .= '<br/>'; if ( gmdate( 'U' ) > $next_timestamp ) { /* translators: %s: date interval */ $schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) ); } else { /* translators: %s: date interval */ $schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) ); } return $schedule_display_string; } /** * Bulk delete. * * Deletes actions based on their ID. This is the handler for the bulk delete. It assumes the data * properly validated by the callee and it will delete the actions without any extra validation. * * @param int[] $ids Action IDs. * @param string $ids_sql Inherited and unused. */ protected function bulk_delete( array $ids, $ids_sql ) { foreach ( $ids as $id ) { try { $this->store->delete_action( $id ); } catch ( Exception $e ) { // A possible reason for an exception would include a scenario where the same action is deleted by a // concurrent request. // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( sprintf( /* translators: 1: action ID 2: exception message. */ __( 'Action Scheduler was unable to delete action %1$d. Reason: %2$s', 'action-scheduler' ), $id, $e->getMessage() ) ); } } } /** * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their * parameters are valid. * * @param int $action_id Action ID. */ protected function row_action_cancel( $action_id ) { $this->process_row_action( $action_id, 'cancel' ); } /** * Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their * parameters are valid. * * @param int $action_id Action ID. */ protected function row_action_run( $action_id ) { $this->process_row_action( $action_id, 'run' ); } /** * Force the data store schema updates. */ protected function recreate_tables() { if ( is_a( $this->store, 'ActionScheduler_HybridStore' ) ) { $store = $this->store; } else { $store = new ActionScheduler_HybridStore(); } add_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10, 2 ); $store_schema = new ActionScheduler_StoreSchema(); $logger_schema = new ActionScheduler_LoggerSchema(); $store_schema->register_tables( true ); $logger_schema->register_tables( true ); remove_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10 ); } /** * Implements the logic behind processing an action once an action link is clicked on the list table. * * @param int $action_id Action ID. * @param string $row_action_type The type of action to perform on the action. */ protected function process_row_action( $action_id, $row_action_type ) { try { switch ( $row_action_type ) { case 'run': $this->runner->process_action( $action_id, 'Admin List Table' ); break; case 'cancel': $this->store->cancel_action( $action_id ); break; } $success = 1; $error_message = ''; } catch ( Exception $e ) { $success = 0; $error_message = $e->getMessage(); } set_transient( 'action_scheduler_admin_notice', compact( 'action_id', 'success', 'error_message', 'row_action_type' ), 30 ); } /** * {@inheritDoc} */ public function prepare_items() { $this->prepare_column_headers(); $per_page = $this->get_items_per_page( $this->get_per_page_option_name(), $this->items_per_page ); $query = array( 'per_page' => $per_page, 'offset' => $this->get_items_offset(), 'status' => $this->get_request_status(), 'orderby' => $this->get_request_orderby(), 'order' => $this->get_request_order(), 'search' => $this->get_request_search_query(), ); /** * Change query arguments to query for past-due actions. * Past-due actions have the 'pending' status and are in the past. * This is needed because registering 'past-due' as a status is overkill. */ if ( 'past-due' === $this->get_request_status() ) { $query['status'] = ActionScheduler_Store::STATUS_PENDING; $query['date'] = as_get_datetime_object(); } $this->items = array(); $total_items = $this->store->query_actions( $query, 'count' ); $status_labels = $this->store->get_status_labels(); foreach ( $this->store->query_actions( $query ) as $action_id ) { try { $action = $this->store->fetch_action( $action_id ); } catch ( Exception $e ) { continue; } if ( is_a( $action, 'ActionScheduler_NullAction' ) ) { continue; } $this->items[ $action_id ] = array( 'ID' => $action_id, 'hook' => $action->get_hook(), 'status_name' => $this->store->get_status( $action_id ), 'status' => $status_labels[ $this->store->get_status( $action_id ) ], 'args' => $action->get_args(), 'group' => $action->get_group(), 'log_entries' => $this->logger->get_logs( $action_id ), 'claim_id' => $this->store->get_claim_id( $action_id ), 'recurrence' => $this->get_recurrence( $action ), 'schedule' => $action->get_schedule(), ); } $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil( $total_items / $per_page ), ) ); } /** * Prints the available statuses so the user can click to filter. */ protected function display_filter_by_status() { $this->status_counts = $this->store->action_counts() + $this->store->extra_action_counts(); parent::display_filter_by_status(); } /** * Get the text to display in the search box on the list table. */ protected function get_search_box_button_text() { return __( 'Search hook, args and claim ID', 'action-scheduler' ); } /** * {@inheritDoc} */ protected function get_per_page_option_name() { return str_replace( '-', '_', $this->screen->id ) . '_per_page'; } } woocommerce/action-scheduler/classes/ActionScheduler_Compatibility.php 0000644 00000007500 15151523434 0022434 0 ustar 00 <?php /** * Class ActionScheduler_Compatibility */ class ActionScheduler_Compatibility { /** * Converts a shorthand byte value to an integer byte value. * * Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php * * @link https://secure.php.net/manual/en/function.ini-get.php * @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes * * @param string $value A (PHP ini) byte value, either shorthand or ordinary. * @return int An integer byte value. */ public static function convert_hr_to_bytes( $value ) { if ( function_exists( 'wp_convert_hr_to_bytes' ) ) { return wp_convert_hr_to_bytes( $value ); } $value = strtolower( trim( $value ) ); $bytes = (int) $value; if ( false !== strpos( $value, 'g' ) ) { $bytes *= GB_IN_BYTES; } elseif ( false !== strpos( $value, 'm' ) ) { $bytes *= MB_IN_BYTES; } elseif ( false !== strpos( $value, 'k' ) ) { $bytes *= KB_IN_BYTES; } // Deal with large (float) values which run into the maximum integer size. return min( $bytes, PHP_INT_MAX ); } /** * Attempts to raise the PHP memory limit for memory intensive processes. * * Only allows raising the existing limit and prevents lowering it. * * Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0 * * @return bool|int|string The limit that was set or false on failure. */ public static function raise_memory_limit() { if ( function_exists( 'wp_raise_memory_limit' ) ) { return wp_raise_memory_limit( 'admin' ); } $current_limit = @ini_get( 'memory_limit' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $current_limit_int = self::convert_hr_to_bytes( $current_limit ); if ( -1 === $current_limit_int ) { return false; } $wp_max_limit = WP_MAX_MEMORY_LIMIT; $wp_max_limit_int = self::convert_hr_to_bytes( $wp_max_limit ); $filtered_limit = apply_filters( 'admin_memory_limit', $wp_max_limit ); $filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit ); // phpcs:disable WordPress.PHP.IniSet.memory_limit_Blacklisted // phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) { if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) { return $filtered_limit; } else { return false; } } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) { if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) { return $wp_max_limit; } else { return false; } } // phpcs:enable return false; } /** * Attempts to raise the PHP timeout for time intensive processes. * * Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available. * * @param int $limit The time limit in seconds. */ public static function raise_time_limit( $limit = 0 ) { $limit = (int) $limit; $max_execution_time = (int) ini_get( 'max_execution_time' ); // If the max execution time is already set to zero (unlimited), there is no reason to make a further change. if ( 0 === $max_execution_time ) { return; } // Whichever of $max_execution_time or $limit is higher is the amount by which we raise the time limit. $raise_by = 0 === $limit || $limit > $max_execution_time ? $limit : $max_execution_time; if ( function_exists( 'wc_set_time_limit' ) ) { wc_set_time_limit( $raise_by ); } elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved @set_time_limit( $raise_by ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } } } woocommerce/action-scheduler/classes/ActionScheduler_AsyncRequest_QueueRunner.php 0000644 00000004163 15151523434 0024611 0 ustar 00 <?php defined( 'ABSPATH' ) || exit; /** * ActionScheduler_AsyncRequest_QueueRunner class. */ class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request { /** * Data store for querying actions * * @var ActionScheduler_Store */ protected $store; /** * Prefix for ajax hooks * * @var string */ protected $prefix = 'as'; /** * Action for ajax hooks * * @var string */ protected $action = 'async_request_queue_runner'; /** * Initiate new async request. * * @param ActionScheduler_Store $store Store object. */ public function __construct( ActionScheduler_Store $store ) { parent::__construct(); $this->store = $store; } /** * Handle async requests * * Run a queue, and maybe dispatch another async request to run another queue * if there are still pending actions after completing a queue in this request. */ protected function handle() { do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context. $sleep_seconds = $this->get_sleep_seconds(); if ( $sleep_seconds ) { sleep( $sleep_seconds ); } $this->maybe_dispatch(); } /** * If the async request runner is needed and allowed to run, dispatch a request. */ public function maybe_dispatch() { if ( ! $this->allow() ) { return; } $this->dispatch(); ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request(); } /** * Only allow async requests when needed. * * Also allow 3rd party code to disable running actions via async requests. */ protected function allow() { if ( ! has_action( 'action_scheduler_run_queue' ) || ActionScheduler::runner()->has_maximum_concurrent_batches() || ! $this->store->has_pending_actions_due() ) { $allow = false; } else { $allow = true; } return apply_filters( 'action_scheduler_allow_async_request_runner', $allow ); } /** * Chaining async requests can crash MySQL. A brief sleep call in PHP prevents that. */ protected function get_sleep_seconds() { return apply_filters( 'action_scheduler_async_request_sleep_seconds', 5, $this ); } } woocommerce/action-scheduler/classes/ActionScheduler_FatalErrorMonitor.php 0000644 00000005005 15151523434 0023232 0 ustar 00 <?php /** * Class ActionScheduler_FatalErrorMonitor */ class ActionScheduler_FatalErrorMonitor { /** * ActionScheduler_ActionClaim instance. * * @var ActionScheduler_ActionClaim */ private $claim = null; /** * ActionScheduler_Store instance. * * @var ActionScheduler_Store */ private $store = null; /** * Current action's ID. * * @var int */ private $action_id = 0; /** * Construct. * * @param ActionScheduler_Store $store Action store. */ public function __construct( ActionScheduler_Store $store ) { $this->store = $store; } /** * Start monitoring. * * @param ActionScheduler_ActionClaim $claim Claimed actions. */ public function attach( ActionScheduler_ActionClaim $claim ) { $this->claim = $claim; add_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) ); add_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 ); add_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 ); add_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0, 0 ); add_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 ); } /** * Stop monitoring. */ public function detach() { $this->claim = null; $this->untrack_action(); remove_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) ); remove_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0 ); remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0 ); remove_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0 ); remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0 ); } /** * Track specified action. * * @param int $action_id Action ID to track. */ public function track_current_action( $action_id ) { $this->action_id = $action_id; } /** * Un-track action. */ public function untrack_action() { $this->action_id = 0; } /** * Handle unexpected shutdown. */ public function handle_unexpected_shutdown() { $error = error_get_last(); if ( $error ) { if ( in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ), true ) ) { if ( ! empty( $this->action_id ) ) { $this->store->mark_failure( $this->action_id ); do_action( 'action_scheduler_unexpected_shutdown', $this->action_id, $error ); } } $this->store->release_claim( $this->claim ); } } } woocommerce/action-scheduler/classes/ActionScheduler_ActionFactory.php 0000644 00000037657 15151523434 0022410 0 ustar 00 <?php /** * Class ActionScheduler_ActionFactory */ class ActionScheduler_ActionFactory { /** * Return stored actions for given params. * * @param string $status The action's status in the data store. * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass to callbacks when the hook is triggered. * @param ActionScheduler_Schedule|null $schedule The action's schedule. * @param string $group A group to put the action in. * phpcs:ignore Squiz.Commenting.FunctionComment.ExtraParamComment * @param int $priority The action priority. * * @return ActionScheduler_Action An instance of the stored action. */ public function get_stored_action( $status, $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) { // The 6th parameter ($priority) is not formally declared in the method signature to maintain compatibility with // third-party subclasses created before this param was added. $priority = func_num_args() >= 6 ? (int) func_get_arg( 5 ) : 10; switch ( $status ) { case ActionScheduler_Store::STATUS_PENDING: $action_class = 'ActionScheduler_Action'; break; case ActionScheduler_Store::STATUS_CANCELED: $action_class = 'ActionScheduler_CanceledAction'; if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) && ! is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) { $schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() ); } break; default: $action_class = 'ActionScheduler_FinishedAction'; break; } $action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group ); $action = new $action_class( $hook, $args, $schedule, $group ); $action->set_priority( $priority ); /** * Allow 3rd party code to change the instantiated action for a given hook, args, schedule and group. * * @param ActionScheduler_Action $action The instantiated action. * @param string $hook The instantiated action's hook. * @param array $args The instantiated action's args. * @param ActionScheduler_Schedule $schedule The instantiated action's schedule. * @param string $group The instantiated action's group. * @param int $priority The action priority. */ return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group, $priority ); } /** * Enqueue an action to run one time, as soon as possible (rather a specific scheduled time). * * This method creates a new action using the NullSchedule. In practice, this results in an action scheduled to * execute "now". Therefore, it will generally run as soon as possible but is not prioritized ahead of other actions * that are already past-due. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function async( $hook, $args = array(), $group = '' ) { return $this->async_unique( $hook, $args, $group, false ); } /** * Same as async, but also supports $unique param. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param string $group A group to put the action in. * @param bool $unique Whether to ensure the action is unique. * * @return int The ID of the stored action. */ public function async_unique( $hook, $args = array(), $group = '', $unique = true ) { $schedule = new ActionScheduler_NullSchedule(); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action, $unique ) : $this->store( $action ); } /** * Create single action. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $when Unix timestamp when the action will run. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function single( $hook, $args = array(), $when = null, $group = '' ) { return $this->single_unique( $hook, $args, $when, $group, false ); } /** * Create single action only if there is no pending or running action with same name and params. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $when Unix timestamp when the action will run. * @param string $group A group to put the action in. * @param bool $unique Whether action scheduled should be unique. * * @return int The ID of the stored action. */ public function single_unique( $hook, $args = array(), $when = null, $group = '', $unique = true ) { $date = as_get_datetime_object( $when ); $schedule = new ActionScheduler_SimpleSchedule( $date ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action ) : $this->store( $action ); } /** * Create the first instance of an action recurring on a given interval. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $first Unix timestamp for the first run. * @param int $interval Seconds between runs. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) { return $this->recurring_unique( $hook, $args, $first, $interval, $group, false ); } /** * Create the first instance of an action recurring on a given interval only if there is no pending or running action with same name and params. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $first Unix timestamp for the first run. * @param int $interval Seconds between runs. * @param string $group A group to put the action in. * @param bool $unique Whether action scheduled should be unique. * * @return int The ID of the stored action. */ public function recurring_unique( $hook, $args = array(), $first = null, $interval = null, $group = '', $unique = true ) { if ( empty( $interval ) ) { return $this->single_unique( $hook, $args, $first, $group, $unique ); } $date = as_get_datetime_object( $first ); $schedule = new ActionScheduler_IntervalSchedule( $date, $interval ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action ) : $this->store( $action ); } /** * Create the first instance of an action recurring on a Cron schedule. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $base_timestamp The first instance of the action will be scheduled * to run at a time calculated after this timestamp matching the cron * expression. This can be used to delay the first instance of the action. * @param int $schedule A cron definition string. * @param string $group A group to put the action in. * * @return int The ID of the stored action. */ public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) { return $this->cron_unique( $hook, $args, $base_timestamp, $schedule, $group, false ); } /** * Create the first instance of an action recurring on a Cron schedule only if there is no pending or running action with same name and params. * * @param string $hook The hook to trigger when this action runs. * @param array $args Args to pass when the hook is triggered. * @param int $base_timestamp The first instance of the action will be scheduled * to run at a time calculated after this timestamp matching the cron * expression. This can be used to delay the first instance of the action. * @param int $schedule A cron definition string. * @param string $group A group to put the action in. * @param bool $unique Whether action scheduled should be unique. * * @return int The ID of the stored action. **/ public function cron_unique( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '', $unique = true ) { if ( empty( $schedule ) ) { return $this->single_unique( $hook, $args, $base_timestamp, $group, $unique ); } $date = as_get_datetime_object( $base_timestamp ); $cron = CronExpression::factory( $schedule ); $schedule = new ActionScheduler_CronSchedule( $date, $cron ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return $unique ? $this->store_unique_action( $action ) : $this->store( $action ); } /** * Create a successive instance of a recurring or cron action. * * Importantly, the action will be rescheduled to run based on the current date/time. * That means when the action is scheduled to run in the past, the next scheduled date * will be pushed forward. For example, if a recurring action set to run every hour * was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the * future, which is 1 hour and 5 seconds from when it was last scheduled to run. * * Alternatively, if the action is scheduled to run in the future, and is run early, * likely via manual intervention, then its schedule will change based on the time now. * For example, if a recurring action set to run every day, and is run 12 hours early, * it will run again in 24 hours, not 36 hours. * * This slippage is less of an issue with Cron actions, as the specific run time can * be set for them to run, e.g. 1am each day. In those cases, and entire period would * need to be missed before there was any change is scheduled, e.g. in the case of an * action scheduled for 1am each day, the action would need to run an entire day late. * * @param ActionScheduler_Action $action The existing action. * * @return string The ID of the stored action * @throws InvalidArgumentException If $action is not a recurring action. */ public function repeat( $action ) { $schedule = $action->get_schedule(); $next = $schedule->get_next( as_get_datetime_object() ); if ( is_null( $next ) || ! $schedule->is_recurring() ) { throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) ); } $schedule_class = get_class( $schedule ); $new_schedule = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() ); $new_action = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() ); $new_action->set_priority( $action->get_priority() ); return $this->store( $new_action ); } /** * Creates a scheduled action. * * This general purpose method can be used in place of specific methods such as async(), * async_unique(), single() or single_unique(), etc. * * @internal Not intended for public use, should not be overridden by subclasses. * * @param array $options { * Describes the action we wish to schedule. * * @type string $type Must be one of 'async', 'cron', 'recurring', or 'single'. * @type string $hook The hook to be executed. * @type array $arguments Arguments to be passed to the callback. * @type string $group The action group. * @type bool $unique If the action should be unique. * @type int $when Timestamp. Indicates when the action, or first instance of the action in the case * of recurring or cron actions, becomes due. * @type int|string $pattern Recurrence pattern. This is either an interval in seconds for recurring actions * or a cron expression for cron actions. * @type int $priority Lower values means higher priority. Should be in the range 0-255. * } * * @return int The action ID. Zero if there was an error scheduling the action. */ public function create( array $options = array() ) { $defaults = array( 'type' => 'single', 'hook' => '', 'arguments' => array(), 'group' => '', 'unique' => false, 'when' => time(), 'pattern' => null, 'priority' => 10, ); $options = array_merge( $defaults, $options ); // Cron/recurring actions without a pattern are treated as single actions (this gives calling code the ability // to use functions like as_schedule_recurring_action() to schedule recurring as well as single actions). if ( ( 'cron' === $options['type'] || 'recurring' === $options['type'] ) && empty( $options['pattern'] ) ) { $options['type'] = 'single'; } switch ( $options['type'] ) { case 'async': $schedule = new ActionScheduler_NullSchedule(); break; case 'cron': $date = as_get_datetime_object( $options['when'] ); $cron = CronExpression::factory( $options['pattern'] ); $schedule = new ActionScheduler_CronSchedule( $date, $cron ); break; case 'recurring': $date = as_get_datetime_object( $options['when'] ); $schedule = new ActionScheduler_IntervalSchedule( $date, $options['pattern'] ); break; case 'single': $date = as_get_datetime_object( $options['when'] ); $schedule = new ActionScheduler_SimpleSchedule( $date ); break; default: // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( "Unknown action type '{$options['type']}' specified when trying to create an action for '{$options['hook']}'." ); return 0; } $action = new ActionScheduler_Action( $options['hook'], $options['arguments'], $schedule, $options['group'] ); $action->set_priority( $options['priority'] ); $action_id = 0; try { $action_id = $options['unique'] ? $this->store_unique_action( $action ) : $this->store( $action ); } catch ( Exception $e ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log error_log( sprintf( /* translators: %1$s is the name of the hook to be enqueued, %2$s is the exception message. */ __( 'Caught exception while enqueuing action "%1$s": %2$s', 'action-scheduler' ), $options['hook'], $e->getMessage() ) ); } return $action_id; } /** * Save action to database. * * @param ActionScheduler_Action $action Action object to save. * * @return int The ID of the stored action */ protected function store( ActionScheduler_Action $action ) { $store = ActionScheduler_Store::instance(); return $store->save_action( $action ); } /** * Store action if it's unique. * * @param ActionScheduler_Action $action Action object to store. * * @return int ID of the created action. Will be 0 if action was not created. */ protected function store_unique_action( ActionScheduler_Action $action ) { $store = ActionScheduler_Store::instance(); if ( method_exists( $store, 'save_unique_action' ) ) { return $store->save_unique_action( $action ); } else { /** * Fallback to non-unique action if the store doesn't support unique actions. * We try to save the action as unique, accepting that there might be a race condition. * This is likely still better than giving up on unique actions entirely. */ $existing_action_id = (int) $store->find_action( $action->get_hook(), array( 'args' => $action->get_args(), 'status' => ActionScheduler_Store::STATUS_PENDING, 'group' => $action->get_group(), ) ); if ( $existing_action_id > 0 ) { return 0; } return $store->save_action( $action ); } } } woocommerce/action-scheduler/classes/schema/ActionScheduler_StoreSchema.php 0000644 00000012217 15151523434 0023301 0 ustar 00 <?php /** * Class ActionScheduler_StoreSchema * * @codeCoverageIgnore * * Creates custom tables for storing scheduled actions */ class ActionScheduler_StoreSchema extends ActionScheduler_Abstract_Schema { const ACTIONS_TABLE = 'actionscheduler_actions'; const CLAIMS_TABLE = 'actionscheduler_claims'; const GROUPS_TABLE = 'actionscheduler_groups'; const DEFAULT_DATE = '0000-00-00 00:00:00'; /** * Schema version. * * Increment this value to trigger a schema update. * * @var int */ protected $schema_version = 8; /** * Construct. */ public function __construct() { $this->tables = array( self::ACTIONS_TABLE, self::CLAIMS_TABLE, self::GROUPS_TABLE, ); } /** * Performs additional setup work required to support this schema. */ public function init() { add_action( 'action_scheduler_before_schema_update', array( $this, 'update_schema_5_0' ), 10, 2 ); } /** * Get table definition. * * @param string $table Table name. */ protected function get_table_definition( $table ) { global $wpdb; $table_name = $wpdb->$table; $charset_collate = $wpdb->get_charset_collate(); $default_date = self::DEFAULT_DATE; // phpcs:ignore Squiz.PHP.CommentedOutCode $max_index_length = 191; // @see wp_get_db_schema() $hook_status_scheduled_date_gmt_max_index_length = $max_index_length - 20 - 8; // - status, - scheduled_date_gmt switch ( $table ) { case self::ACTIONS_TABLE: return "CREATE TABLE {$table_name} ( action_id bigint(20) unsigned NOT NULL auto_increment, hook varchar(191) NOT NULL, status varchar(20) NOT NULL, scheduled_date_gmt datetime NULL default '{$default_date}', scheduled_date_local datetime NULL default '{$default_date}', priority tinyint unsigned NOT NULL default '10', args varchar($max_index_length), schedule longtext, group_id bigint(20) unsigned NOT NULL default '0', attempts int(11) NOT NULL default '0', last_attempt_gmt datetime NULL default '{$default_date}', last_attempt_local datetime NULL default '{$default_date}', claim_id bigint(20) unsigned NOT NULL default '0', extended_args varchar(8000) DEFAULT NULL, PRIMARY KEY (action_id), KEY hook_status_scheduled_date_gmt (hook($hook_status_scheduled_date_gmt_max_index_length), status, scheduled_date_gmt), KEY status_scheduled_date_gmt (status, scheduled_date_gmt), KEY scheduled_date_gmt (scheduled_date_gmt), KEY args (args($max_index_length)), KEY group_id (group_id), KEY last_attempt_gmt (last_attempt_gmt), KEY `claim_id_status_priority_scheduled_date_gmt` (`claim_id`,`status`,`priority`,`scheduled_date_gmt`), KEY `status_last_attempt_gmt` (`status`,`last_attempt_gmt`), KEY `status_claim_id` (`status`,`claim_id`) ) $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 } } woocommerce/action-scheduler/classes/schema/ActionScheduler_LoggerSchema.php 0000644 00000005672 15151523434 0023433 0 ustar 00 <?php /** * Class ActionScheduler_LoggerSchema * * @codeCoverageIgnore * * Creates a custom table for storing action logs */ class ActionScheduler_LoggerSchema extends ActionScheduler_Abstract_Schema { const LOG_TABLE = 'actionscheduler_logs'; /** * Schema version. * * Increment this value to trigger a schema update. * * @var int */ protected $schema_version = 3; /** * Construct. */ public function __construct() { $this->tables = array( self::LOG_TABLE, ); } /** * Performs additional setup work required to support this schema. */ public function init() { add_action( 'action_scheduler_before_schema_update', array( $this, 'update_schema_3_0' ), 10, 2 ); } /** * Get table definition. * * @param string $table Table name. */ protected function get_table_definition( $table ) { global $wpdb; $table_name = $wpdb->$table; $charset_collate = $wpdb->get_charset_collate(); switch ( $table ) { case self::LOG_TABLE: $default_date = ActionScheduler_StoreSchema::DEFAULT_DATE; return "CREATE TABLE $table_name ( log_id bigint(20) unsigned NOT NULL auto_increment, action_id bigint(20) unsigned NOT NULL, message text NOT NULL, log_date_gmt datetime NULL default '{$default_date}', log_date_local datetime NULL default '{$default_date}', PRIMARY KEY (log_id), KEY action_id (action_id), KEY log_date_gmt (log_date_gmt) ) $charset_collate"; default: return ''; } } /** * Update the logs table schema, allowing datetime fields to be NULL. * * This is needed because the NOT NULL constraint causes a conflict with some versions of MySQL * configured with sql_mode=NO_ZERO_DATE, which can for instance lead to tables not being created. * * Most other schema updates happen via ActionScheduler_Abstract_Schema::update_table(), however * that method relies on dbDelta() and this change is not possible when using that function. * * @param string $table Name of table being updated. * @param string $db_version The existing schema version of the table. */ public function update_schema_3_0( $table, $db_version ) { global $wpdb; if ( 'actionscheduler_logs' !== $table || version_compare( $db_version, '3', '>=' ) ) { return; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $table_name = $wpdb->prefix . 'actionscheduler_logs'; $table_list = $wpdb->get_col( "SHOW TABLES LIKE '{$table_name}'" ); $default_date = ActionScheduler_StoreSchema::DEFAULT_DATE; if ( ! empty( $table_list ) ) { $query = " ALTER TABLE {$table_name} MODIFY COLUMN log_date_gmt datetime NULL default '{$default_date}', MODIFY COLUMN log_date_local datetime NULL default '{$default_date}' "; $wpdb->query( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared } } woocommerce/action-scheduler/classes/ActionScheduler_Versions.php 0000644 00000007152 15151523434 0021436 0 ustar 00 <?php /** * Class ActionScheduler_Versions */ class ActionScheduler_Versions { /** * ActionScheduler_Versions instance. * * @var ActionScheduler_Versions */ private static $instance = null; /** * Versions. * * @var array<string, callable> */ private $versions = array(); /** * Registered sources. * * @var array<string, string> */ private $sources = array(); /** * Register version's callback. * * @param string $version_string Action Scheduler version. * @param callable $initialization_callback Callback to initialize the version. */ public function register( $version_string, $initialization_callback ) { if ( isset( $this->versions[ $version_string ] ) ) { return false; } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ); $source = $backtrace[0]['file']; $this->versions[ $version_string ] = $initialization_callback; $this->sources[ $source ] = $version_string; return true; } /** * Get all versions. */ public function get_versions() { return $this->versions; } /** * Get registered sources. * * Use with caution: this method is only available as of Action Scheduler's 3.9.1 * release and, owing to the way Action Scheduler is loaded, it's possible that the * class definition used at runtime will belong to an earlier version. * * @since 3.9.1 * * @return array<string, string> */ public function get_sources() { return $this->sources; } /** * Get latest version registered. */ public function latest_version() { $keys = array_keys( $this->versions ); if ( empty( $keys ) ) { return false; } uasort( $keys, 'version_compare' ); return end( $keys ); } /** * Get callback for latest registered version. */ public function latest_version_callback() { $latest = $this->latest_version(); if ( empty( $latest ) || ! isset( $this->versions[ $latest ] ) ) { return '__return_null'; } return $this->versions[ $latest ]; } /** * Get instance. * * @return ActionScheduler_Versions * @codeCoverageIgnore */ public static function instance() { if ( empty( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } /** * Initialize. * * @codeCoverageIgnore */ public static function initialize_latest_version() { $self = self::instance(); call_user_func( $self->latest_version_callback() ); } /** * Returns information about the plugin or theme which contains the current active version * of Action Scheduler. * * If this cannot be determined, or if Action Scheduler is being loaded via some other * method, then it will return an empty array. Otherwise, if populated, the array will * look like the following: * * [ * 'type' => 'plugin', # or 'theme' * 'name' => 'Name', * ] * * @deprecated 3.9.2 Use ActionScheduler_SystemInformation::active_source(). * * @return array */ public function active_source(): array { _deprecated_function( __METHOD__, '3.9.2', 'ActionScheduler_SystemInformation::active_source()' ); return ActionScheduler_SystemInformation::active_source(); } /** * Returns the directory path for the currently active installation of Action Scheduler. * * @deprecated 3.9.2 Use ActionScheduler_SystemInformation::active_source_path(). * * @return string */ public function active_source_path(): string { _deprecated_function( __METHOD__, '3.9.2', 'ActionScheduler_SystemInformation::active_source_path()' ); return ActionScheduler_SystemInformation::active_source_path(); } } woocommerce/action-scheduler/classes/WP_CLI/Action_Command.php 0000644 00000020224 15151523434 0020355 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI; /** * Action command for Action Scheduler. */ class Action_Command extends \WP_CLI_Command { /** * Cancel the next occurrence or all occurrences of a scheduled action. * * ## OPTIONS * * [<hook>] * : Name of the action hook. * * [--group=<group>] * : The group the job is assigned to. * * [--args=<args>] * : JSON object of arguments assigned to the job. * --- * default: [] * --- * * [--all] * : Cancel all occurrences of a scheduled action. * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function cancel( array $args, array $assoc_args ) { require_once 'Action/Cancel_Command.php'; $command = new Action\Cancel_Command( $args, $assoc_args ); $command->execute(); } /** * Creates a new scheduled action. * * ## OPTIONS * * <hook> * : Name of the action hook. * * <start> * : A unix timestamp representing the date you want the action to start. Also 'async' or 'now' to enqueue an async action. * * [--args=<args>] * : JSON object of arguments to pass to callbacks when the hook triggers. * --- * default: [] * --- * * [--cron=<cron>] * : A cron-like schedule string (https://crontab.guru/). * --- * default: '' * --- * * [--group=<group>] * : The group to assign this job to. * --- * default: '' * --- * * [--interval=<interval>] * : Number of seconds to wait between runs. * --- * default: 0 * --- * * ## EXAMPLES * * wp action-scheduler action create hook_async async * wp action-scheduler action create hook_single 1627147598 * wp action-scheduler action create hook_recurring 1627148188 --interval=5 * wp action-scheduler action create hook_cron 1627147655 --cron='5 4 * * *' * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function create( array $args, array $assoc_args ) { require_once 'Action/Create_Command.php'; $command = new Action\Create_Command( $args, $assoc_args ); $command->execute(); } /** * Delete existing scheduled action(s). * * ## OPTIONS * * <id>... * : One or more IDs of actions to delete. * --- * default: 0 * --- * * ## EXAMPLES * * # Delete the action with id 100 * $ wp action-scheduler action delete 100 * * # Delete the actions with ids 100 and 200 * $ wp action-scheduler action delete 100 200 * * # Delete the first five pending actions in 'action-scheduler' group * $ wp action-scheduler action delete $( wp action-scheduler action list --status=pending --group=action-scheduler --format=ids ) * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function delete( array $args, array $assoc_args ) { require_once 'Action/Delete_Command.php'; $command = new Action\Delete_Command( $args, $assoc_args ); $command->execute(); } /** * Generates some scheduled actions. * * ## OPTIONS * * <hook> * : Name of the action hook. * * <start> * : The Unix timestamp representing the date you want the action to start. * * [--count=<count>] * : Number of actions to create. * --- * default: 1 * --- * * [--interval=<interval>] * : Number of seconds to wait between runs. * --- * default: 0 * --- * * [--args=<args>] * : JSON object of arguments to pass to callbacks when the hook triggers. * --- * default: [] * --- * * [--group=<group>] * : The group to assign this job to. * --- * default: '' * --- * * ## EXAMPLES * * wp action-scheduler action generate test_multiple 1627147598 --count=5 --interval=5 * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function generate( array $args, array $assoc_args ) { require_once 'Action/Generate_Command.php'; $command = new Action\Generate_Command( $args, $assoc_args ); $command->execute(); } /** * Get details about a scheduled action. * * ## OPTIONS * * <id> * : The ID of the action to get. * --- * default: 0 * --- * * [--field=<field>] * : Instead of returning the whole action, returns the value of a single field. * * [--fields=<fields>] * : Limit the output to specific fields (comma-separated). Defaults to all fields. * * [--format=<format>] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - json * - yaml * --- * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function get( array $args, array $assoc_args ) { require_once 'Action/Get_Command.php'; $command = new Action\Get_Command( $args, $assoc_args ); $command->execute(); } /** * Get a list of scheduled actions. * * Display actions based on all arguments supported by * [as_get_scheduled_actions()](https://actionscheduler.org/api/#function-reference--as_get_scheduled_actions). * * ## OPTIONS * * [--<field>=<value>] * : One or more arguments to pass to as_get_scheduled_actions(). * * [--field=<field>] * : Prints the value of a single property for each action. * * [--fields=<fields>] * : Limit the output to specific object properties. * * [--format=<format>] * : Render output in a particular format. * --- * default: table * options: * - table * - csv * - ids * - json * - count * - yaml * --- * * ## AVAILABLE FIELDS * * These fields will be displayed by default for each action: * * * id * * hook * * status * * group * * recurring * * scheduled_date * * These fields are optionally available: * * * args * * log_entries * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void * * @subcommand list */ public function subcommand_list( array $args, array $assoc_args ) { require_once 'Action/List_Command.php'; $command = new Action\List_Command( $args, $assoc_args ); $command->execute(); } /** * Get logs for a scheduled action. * * ## OPTIONS * * <id> * : The ID of the action to get. * --- * default: 0 * --- * * @param array $args Positional arguments. * @return void */ public function logs( array $args ) { $command = sprintf( 'action-scheduler action get %d --field=log_entries', $args[0] ); WP_CLI::runcommand( $command ); } /** * Get the ID or timestamp of the next scheduled action. * * ## OPTIONS * * <hook> * : The hook of the next scheduled action. * * [--args=<args>] * : JSON object of arguments to search for next scheduled action. * --- * default: [] * --- * * [--group=<group>] * : The group to which the next scheduled action is assigned. * --- * default: '' * --- * * [--raw] * : Display the raw output of as_next_scheduled_action() (timestamp or boolean). * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function next( array $args, array $assoc_args ) { require_once 'Action/Next_Command.php'; $command = new Action\Next_Command( $args, $assoc_args ); $command->execute(); } /** * Run existing scheduled action(s). * * ## OPTIONS * * <id>... * : One or more IDs of actions to run. * --- * default: 0 * --- * * ## EXAMPLES * * # Run the action with id 100 * $ wp action-scheduler action run 100 * * # Run the actions with ids 100 and 200 * $ wp action-scheduler action run 100 200 * * # Run the first five pending actions in 'action-scheduler' group * $ wp action-scheduler action run $( wp action-scheduler action list --status=pending --group=action-scheduler --format=ids ) * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @return void */ public function run( array $args, array $assoc_args ) { require_once 'Action/Run_Command.php'; $command = new Action\Run_Command( $args, $assoc_args ); $command->execute(); } } woocommerce/action-scheduler/classes/WP_CLI/Action/Get_Command.php 0000644 00000004240 15151523434 0021074 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; /** * WP-CLI command: action-scheduler action get */ class Get_Command extends \ActionScheduler_WPCLI_Command { /** * Execute command. * * @return void */ public function execute() { $action_id = $this->args[0]; $store = \ActionScheduler::store(); $logger = \ActionScheduler::logger(); $action = $store->fetch_action( $action_id ); if ( is_a( $action, ActionScheduler_NullAction::class ) ) { /* translators: %d is action ID. */ \WP_CLI::error( sprintf( esc_html__( 'Unable to retrieve action %d.', 'action-scheduler' ), $action_id ) ); } $only_logs = ! empty( $this->assoc_args['field'] ) && 'log_entries' === $this->assoc_args['field']; $only_logs = $only_logs || ( ! empty( $this->assoc_args['fields'] ) && 'log_entries' === $this->assoc_args['fields'] ); $log_entries = array(); foreach ( $logger->get_logs( $action_id ) as $log_entry ) { $log_entries[] = array( 'date' => $log_entry->get_date()->format( static::DATE_FORMAT ), 'message' => $log_entry->get_message(), ); } if ( $only_logs ) { $args = array( 'format' => \WP_CLI\Utils\get_flag_value( $this->assoc_args, 'format', 'table' ), ); $formatter = new \WP_CLI\Formatter( $args, array( 'date', 'message' ) ); $formatter->display_items( $log_entries ); return; } try { $status = $store->get_status( $action_id ); } catch ( \Exception $e ) { \WP_CLI::error( $e->getMessage() ); } $action_arr = array( 'id' => $this->args[0], 'hook' => $action->get_hook(), 'status' => $status, 'args' => $action->get_args(), 'group' => $action->get_group(), 'recurring' => $action->get_schedule()->is_recurring() ? 'yes' : 'no', 'scheduled_date' => $this->get_schedule_display_string( $action->get_schedule() ), 'log_entries' => $log_entries, ); $fields = array_keys( $action_arr ); if ( ! empty( $this->assoc_args['fields'] ) ) { $fields = explode( ',', $this->assoc_args['fields'] ); } $formatter = new \WP_CLI\Formatter( $this->assoc_args, $fields ); $formatter->display_item( $action_arr ); } } woocommerce/action-scheduler/classes/WP_CLI/Action/Run_Command.php 0000644 00000011161 15151523434 0021121 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; /** * WP-CLI command: action-scheduler action run */ class Run_Command extends \ActionScheduler_WPCLI_Command { /** * Array of action IDs to execute. * * @var int[] */ protected $action_ids = array(); /** * Number of executed, failed, ignored, invalid, and total actions. * * @var array<string, int> */ protected $action_counts = array( 'executed' => 0, 'failed' => 0, 'ignored' => 0, 'invalid' => 0, 'total' => 0, ); /** * Construct. * * @param string[] $args Positional arguments. * @param array<string, string> $assoc_args Keyed arguments. */ public function __construct( array $args, array $assoc_args ) { parent::__construct( $args, $assoc_args ); $this->action_ids = array_map( 'absint', $args ); $this->action_counts['total'] = count( $this->action_ids ); add_action( 'action_scheduler_execution_ignored', array( $this, 'on_action_ignored' ) ); add_action( 'action_scheduler_after_execute', array( $this, 'on_action_executed' ) ); add_action( 'action_scheduler_failed_execution', array( $this, 'on_action_failed' ), 10, 2 ); add_action( 'action_scheduler_failed_validation', array( $this, 'on_action_invalid' ), 10, 2 ); } /** * Execute. * * @return void */ public function execute() { $runner = \ActionScheduler::runner(); $progress_bar = \WP_CLI\Utils\make_progress_bar( sprintf( /* translators: %d: number of actions */ _n( 'Executing %d action', 'Executing %d actions', $this->action_counts['total'], 'action-scheduler' ), number_format_i18n( $this->action_counts['total'] ) ), $this->action_counts['total'] ); foreach ( $this->action_ids as $action_id ) { $runner->process_action( $action_id, 'Action Scheduler CLI' ); $progress_bar->tick(); } $progress_bar->finish(); foreach ( array( 'ignored', 'invalid', 'failed', ) as $type ) { $count = $this->action_counts[ $type ]; if ( empty( $count ) ) { continue; } /* * translators: * %1$d: count of actions evaluated. * %2$s: type of action evaluated. */ $format = _n( '%1$d action %2$s.', '%1$d actions %2$s.', $count, 'action-scheduler' ); \WP_CLI::warning( sprintf( $format, number_format_i18n( $count ), $type ) ); } \WP_CLI::success( sprintf( /* translators: %d: number of executed actions */ _n( 'Executed %d action.', 'Executed %d actions.', $this->action_counts['executed'], 'action-scheduler' ), number_format_i18n( $this->action_counts['executed'] ) ) ); } /** * Action: action_scheduler_execution_ignored * * @param int $action_id Action ID. * @return void */ public function on_action_ignored( $action_id ) { if ( 'action_scheduler_execution_ignored' !== current_action() ) { return; } $action_id = absint( $action_id ); if ( ! in_array( $action_id, $this->action_ids, true ) ) { return; } $this->action_counts['ignored']++; \WP_CLI::debug( sprintf( 'Action %d was ignored.', $action_id ) ); } /** * Action: action_scheduler_after_execute * * @param int $action_id Action ID. * @return void */ public function on_action_executed( $action_id ) { if ( 'action_scheduler_after_execute' !== current_action() ) { return; } $action_id = absint( $action_id ); if ( ! in_array( $action_id, $this->action_ids, true ) ) { return; } $this->action_counts['executed']++; \WP_CLI::debug( sprintf( 'Action %d was executed.', $action_id ) ); } /** * Action: action_scheduler_failed_execution * * @param int $action_id Action ID. * @param \Exception $e Exception. * @return void */ public function on_action_failed( $action_id, \Exception $e ) { if ( 'action_scheduler_failed_execution' !== current_action() ) { return; } $action_id = absint( $action_id ); if ( ! in_array( $action_id, $this->action_ids, true ) ) { return; } $this->action_counts['failed']++; \WP_CLI::debug( sprintf( 'Action %d failed execution: %s', $action_id, $e->getMessage() ) ); } /** * Action: action_scheduler_failed_validation * * @param int $action_id Action ID. * @param \Exception $e Exception. * @return void */ public function on_action_invalid( $action_id, \Exception $e ) { if ( 'action_scheduler_failed_validation' !== current_action() ) { return; } $action_id = absint( $action_id ); if ( ! in_array( $action_id, $this->action_ids, true ) ) { return; } $this->action_counts['invalid']++; \WP_CLI::debug( sprintf( 'Action %d failed validation: %s', $action_id, $e->getMessage() ) ); } } woocommerce/action-scheduler/classes/WP_CLI/Action/List_Command.php 0000644 00000006067 15151523434 0021301 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI. /** * WP-CLI command: action-scheduler action list */ class List_Command extends \ActionScheduler_WPCLI_Command { const PARAMETERS = array( 'hook', 'args', 'date', 'date_compare', 'modified', 'modified_compare', 'group', 'status', 'claimed', 'per_page', 'offset', 'orderby', 'order', ); /** * Execute command. * * @return void */ public function execute() { $store = \ActionScheduler::store(); $logger = \ActionScheduler::logger(); $fields = array( 'id', 'hook', 'status', 'group', 'recurring', 'scheduled_date', ); $this->process_csv_arguments_to_arrays(); if ( ! empty( $this->assoc_args['fields'] ) ) { $fields = $this->assoc_args['fields']; } $formatter = new \WP_CLI\Formatter( $this->assoc_args, $fields ); $query_args = $this->assoc_args; /** * The `claimed` parameter expects a boolean or integer: * check for string 'false', and set explicitly to `false` boolean. */ if ( array_key_exists( 'claimed', $query_args ) && 'false' === strtolower( $query_args['claimed'] ) ) { $query_args['claimed'] = false; } $return_format = 'OBJECT'; if ( in_array( $formatter->format, array( 'ids', 'count' ), true ) ) { $return_format = '\'ids\''; } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export $params = var_export( $query_args, true ); if ( empty( $query_args ) ) { $params = 'array()'; } \WP_CLI::debug( sprintf( 'as_get_scheduled_actions( %s, %s )', $params, $return_format ) ); if ( ! empty( $query_args['args'] ) ) { $query_args['args'] = json_decode( $query_args['args'], true ); } switch ( $formatter->format ) { case 'ids': $actions = as_get_scheduled_actions( $query_args, 'ids' ); echo implode( ' ', $actions ); break; case 'count': $actions = as_get_scheduled_actions( $query_args, 'ids' ); $formatter->display_items( $actions ); break; default: $actions = as_get_scheduled_actions( $query_args, OBJECT ); $actions_arr = array(); foreach ( $actions as $action_id => $action ) { $action_arr = array( 'id' => $action_id, 'hook' => $action->get_hook(), 'status' => $store->get_status( $action_id ), 'args' => $action->get_args(), 'group' => $action->get_group(), 'recurring' => $action->get_schedule()->is_recurring() ? 'yes' : 'no', 'scheduled_date' => $this->get_schedule_display_string( $action->get_schedule() ), 'log_entries' => array(), ); foreach ( $logger->get_logs( $action_id ) as $log_entry ) { $action_arr['log_entries'][] = array( 'date' => $log_entry->get_date()->format( static::DATE_FORMAT ), 'message' => $log_entry->get_message(), ); } $actions_arr[] = $action_arr; } $formatter->display_items( $actions_arr ); break; } } } woocommerce/action-scheduler/classes/WP_CLI/Action/Next_Command.php 0000644 00000003503 15151523434 0021274 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI. use function \WP_CLI\Utils\get_flag_value; /** * WP-CLI command: action-scheduler action next */ class Next_Command extends \ActionScheduler_WPCLI_Command { /** * Execute command. * * @return void */ public function execute() { $hook = $this->args[0]; $group = get_flag_value( $this->assoc_args, 'group', '' ); $callback_args = get_flag_value( $this->assoc_args, 'args', null ); $raw = (bool) get_flag_value( $this->assoc_args, 'raw', false ); if ( ! empty( $callback_args ) ) { $callback_args = json_decode( $callback_args, true ); } if ( $raw ) { \WP_CLI::line( as_next_scheduled_action( $hook, $callback_args, $group ) ); return; } $params = array( 'hook' => $hook, 'orderby' => 'date', 'order' => 'ASC', 'group' => $group, ); if ( is_array( $callback_args ) ) { $params['args'] = $callback_args; } $params['status'] = \ActionScheduler_Store::STATUS_RUNNING; // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export \WP_CLI::debug( 'ActionScheduler()::store()->query_action( ' . var_export( $params, true ) . ' )' ); $store = \ActionScheduler::store(); $action_id = $store->query_action( $params ); if ( $action_id ) { echo $action_id; return; } $params['status'] = \ActionScheduler_Store::STATUS_PENDING; // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export \WP_CLI::debug( 'ActionScheduler()::store()->query_action( ' . var_export( $params, true ) . ' )' ); $action_id = $store->query_action( $params ); if ( $action_id ) { echo $action_id; return; } \WP_CLI::warning( 'No matching next action.' ); } } woocommerce/action-scheduler/classes/WP_CLI/Action/Cancel_Command.php 0000644 00000006410 15151523434 0021543 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; use function \WP_CLI\Utils\get_flag_value; /** * WP-CLI command: action-scheduler action cancel */ class Cancel_Command extends \ActionScheduler_WPCLI_Command { /** * Execute command. * * @return void */ public function execute() { $hook = ''; $group = get_flag_value( $this->assoc_args, 'group', '' ); $callback_args = get_flag_value( $this->assoc_args, 'args', null ); $all = get_flag_value( $this->assoc_args, 'all', false ); if ( ! empty( $this->args[0] ) ) { $hook = $this->args[0]; } if ( ! empty( $callback_args ) ) { $callback_args = json_decode( $callback_args, true ); } if ( $all ) { $this->cancel_all( $hook, $callback_args, $group ); return; } $this->cancel_single( $hook, $callback_args, $group ); } /** * Cancel single action. * * @param string $hook The hook that the job will trigger. * @param array $callback_args Args that would have been passed to the job. * @param string $group The group the job is assigned to. * @return void */ protected function cancel_single( $hook, $callback_args, $group ) { if ( empty( $hook ) ) { \WP_CLI::error( __( 'Please specify hook of action to cancel.', 'action-scheduler' ) ); } try { $result = as_unschedule_action( $hook, $callback_args, $group ); } catch ( \Exception $e ) { $this->print_error( $e, false ); } if ( null === $result ) { $e = new \Exception( __( 'Unable to cancel scheduled action: check the logs.', 'action-scheduler' ) ); $this->print_error( $e, false ); } $this->print_success( false ); } /** * Cancel all actions. * * @param string $hook The hook that the job will trigger. * @param array $callback_args Args that would have been passed to the job. * @param string $group The group the job is assigned to. * @return void */ protected function cancel_all( $hook, $callback_args, $group ) { if ( empty( $hook ) && empty( $group ) ) { \WP_CLI::error( __( 'Please specify hook and/or group of actions to cancel.', 'action-scheduler' ) ); } try { $result = as_unschedule_all_actions( $hook, $callback_args, $group ); } catch ( \Exception $e ) { $this->print_error( $e, $multiple ); } /** * Because as_unschedule_all_actions() does not provide a result, * neither confirm or deny actions cancelled. */ \WP_CLI::success( __( 'Request to cancel scheduled actions completed.', 'action-scheduler' ) ); } /** * Print a success message. * * @return void */ protected function print_success() { \WP_CLI::success( __( 'Scheduled action cancelled.', 'action-scheduler' ) ); } /** * Convert an exception into a WP CLI error. * * @param \Exception $e The error object. * @param bool $multiple Boolean if multiple actions. * @throws \WP_CLI\ExitException When an error occurs. * @return void */ protected function print_error( \Exception $e, $multiple ) { \WP_CLI::error( sprintf( /* translators: %1$s: singular or plural %2$s: refers to the exception error message. */ __( 'There was an error cancelling the %1$s: %2$s', 'action-scheduler' ), $multiple ? __( 'scheduled actions', 'action-scheduler' ) : __( 'scheduled action', 'action-scheduler' ), $e->getMessage() ) ); } } woocommerce/action-scheduler/classes/WP_CLI/Action/Generate_Command.php 0000644 00000006737 15151523434 0022124 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; use function \WP_CLI\Utils\get_flag_value; /** * WP-CLI command: action-scheduler action generate */ class Generate_Command extends \ActionScheduler_WPCLI_Command { /** * Execute command. * * @return void */ public function execute() { $hook = $this->args[0]; $schedule_start = $this->args[1]; $callback_args = get_flag_value( $this->assoc_args, 'args', array() ); $group = get_flag_value( $this->assoc_args, 'group', '' ); $interval = (int) get_flag_value( $this->assoc_args, 'interval', 0 ); // avoid absint() to support negative intervals $count = absint( get_flag_value( $this->assoc_args, 'count', 1 ) ); if ( ! empty( $callback_args ) ) { $callback_args = json_decode( $callback_args, true ); } $schedule_start = as_get_datetime_object( $schedule_start ); $function_args = array( 'start' => absint( $schedule_start->format( 'U' ) ), 'interval' => $interval, 'count' => $count, 'hook' => $hook, 'callback_args' => $callback_args, 'group' => $group, ); $function_args = array_values( $function_args ); try { $actions_added = $this->generate( ...$function_args ); } catch ( \Exception $e ) { $this->print_error( $e ); } $num_actions_added = count( (array) $actions_added ); $this->print_success( $num_actions_added, 'single' ); } /** * Schedule multiple single actions. * * @param int $schedule_start Starting timestamp of first action. * @param int $interval How long to wait between runs. * @param int $count Limit number of actions to schedule. * @param string $hook The hook to trigger. * @param array $args Arguments to pass when the hook triggers. * @param string $group The group to assign this job to. * @return int[] IDs of actions added. */ protected function generate( $schedule_start, $interval, $count, $hook, array $args = array(), $group = '' ) { $actions_added = array(); $progress_bar = \WP_CLI\Utils\make_progress_bar( sprintf( /* translators: %d is number of actions to create */ _n( 'Creating %d action', 'Creating %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ), $count ); for ( $i = 0; $i < $count; $i++ ) { $actions_added[] = as_schedule_single_action( $schedule_start + ( $i * $interval ), $hook, $args, $group ); $progress_bar->tick(); } $progress_bar->finish(); return $actions_added; } /** * Print a success message with the action ID. * * @param int $actions_added Number of actions generated. * @param string $action_type Type of actions scheduled. * @return void */ protected function print_success( $actions_added, $action_type ) { \WP_CLI::success( sprintf( /* translators: %1$d refers to the total number of tasks added, %2$s is the action type */ _n( '%1$d %2$s action scheduled.', '%1$d %2$s actions scheduled.', $actions_added, 'action-scheduler' ), number_format_i18n( $actions_added ), $action_type ) ); } /** * Convert an exception into a WP CLI error. * * @param \Exception $e The error object. * @throws \WP_CLI\ExitException When an error occurs. * @return void */ protected function print_error( \Exception $e ) { \WP_CLI::error( sprintf( /* translators: %s refers to the exception error message. */ __( 'There was an error creating the scheduled action: %s', 'action-scheduler' ), $e->getMessage() ) ); } } woocommerce/action-scheduler/classes/WP_CLI/Action/Create_Command.php 0000644 00000010552 15151523434 0021563 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; use function \WP_CLI\Utils\get_flag_value; /** * WP-CLI command: action-scheduler action create */ class Create_Command extends \ActionScheduler_WPCLI_Command { const ASYNC_OPTS = array( 'async', 0 ); /** * Execute command. * * @return void */ public function execute() { $hook = $this->args[0]; $schedule_start = $this->args[1]; $callback_args = get_flag_value( $this->assoc_args, 'args', array() ); $group = get_flag_value( $this->assoc_args, 'group', '' ); $interval = absint( get_flag_value( $this->assoc_args, 'interval', 0 ) ); $cron = get_flag_value( $this->assoc_args, 'cron', '' ); $unique = get_flag_value( $this->assoc_args, 'unique', false ); $priority = absint( get_flag_value( $this->assoc_args, 'priority', 10 ) ); if ( ! empty( $callback_args ) ) { $callback_args = json_decode( $callback_args, true ); } $function_args = array( 'start' => $schedule_start, 'cron' => $cron, 'interval' => $interval, 'hook' => $hook, 'callback_args' => $callback_args, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ); try { // Generate schedule start if appropriate. if ( ! in_array( $schedule_start, static::ASYNC_OPTS, true ) ) { $schedule_start = as_get_datetime_object( $schedule_start ); $function_args['start'] = $schedule_start->format( 'U' ); } } catch ( \Exception $e ) { \WP_CLI::error( $e->getMessage() ); } // Default to creating single action. $action_type = 'single'; $function = 'as_schedule_single_action'; if ( ! empty( $interval ) ) { // Creating recurring action. $action_type = 'recurring'; $function = 'as_schedule_recurring_action'; $function_args = array_filter( $function_args, static function( $key ) { return in_array( $key, array( 'start', 'interval', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true ); }, ARRAY_FILTER_USE_KEY ); } elseif ( ! empty( $cron ) ) { // Creating cron action. $action_type = 'cron'; $function = 'as_schedule_cron_action'; $function_args = array_filter( $function_args, static function( $key ) { return in_array( $key, array( 'start', 'cron', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true ); }, ARRAY_FILTER_USE_KEY ); } elseif ( in_array( $function_args['start'], static::ASYNC_OPTS, true ) ) { // Enqueue async action. $action_type = 'async'; $function = 'as_enqueue_async_action'; $function_args = array_filter( $function_args, static function( $key ) { return in_array( $key, array( 'hook', 'callback_args', 'group', 'unique', 'priority' ), true ); }, ARRAY_FILTER_USE_KEY ); } else { // Enqueue single action. $function_args = array_filter( $function_args, static function( $key ) { return in_array( $key, array( 'start', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true ); }, ARRAY_FILTER_USE_KEY ); } $function_args = array_values( $function_args ); try { $action_id = call_user_func_array( $function, $function_args ); } catch ( \Exception $e ) { $this->print_error( $e ); } if ( 0 === $action_id ) { $e = new \Exception( __( 'Unable to create a scheduled action.', 'action-scheduler' ) ); $this->print_error( $e ); } $this->print_success( $action_id, $action_type ); } /** * Print a success message with the action ID. * * @param int $action_id Created action ID. * @param string $action_type Type of action. * * @return void */ protected function print_success( $action_id, $action_type ) { \WP_CLI::success( sprintf( /* translators: %1$s: type of action, %2$d: ID of the created action */ __( '%1$s action (%2$d) scheduled.', 'action-scheduler' ), ucfirst( $action_type ), $action_id ) ); } /** * Convert an exception into a WP CLI error. * * @param \Exception $e The error object. * @throws \WP_CLI\ExitException When an error occurs. * @return void */ protected function print_error( \Exception $e ) { \WP_CLI::error( sprintf( /* translators: %s refers to the exception error message. */ __( 'There was an error creating the scheduled action: %s', 'action-scheduler' ), $e->getMessage() ) ); } } woocommerce/action-scheduler/classes/WP_CLI/Action/Delete_Command.php 0000644 00000005145 15151523434 0021564 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI\Action; /** * WP-CLI command: action-scheduler action delete */ class Delete_Command extends \ActionScheduler_WPCLI_Command { /** * Array of action IDs to delete. * * @var int[] */ protected $action_ids = array(); /** * Number of deleted, failed, and total actions deleted. * * @var array<string, int> */ protected $action_counts = array( 'deleted' => 0, 'failed' => 0, 'total' => 0, ); /** * Construct. * * @param string[] $args Positional arguments. * @param array<string, string> $assoc_args Keyed arguments. */ public function __construct( array $args, array $assoc_args ) { parent::__construct( $args, $assoc_args ); $this->action_ids = array_map( 'absint', $args ); $this->action_counts['total'] = count( $this->action_ids ); add_action( 'action_scheduler_deleted_action', array( $this, 'on_action_deleted' ) ); } /** * Execute. * * @return void */ public function execute() { $store = \ActionScheduler::store(); $progress_bar = \WP_CLI\Utils\make_progress_bar( sprintf( /* translators: %d: number of actions to be deleted */ _n( 'Deleting %d action', 'Deleting %d actions', $this->action_counts['total'], 'action-scheduler' ), number_format_i18n( $this->action_counts['total'] ) ), $this->action_counts['total'] ); foreach ( $this->action_ids as $action_id ) { try { $store->delete_action( $action_id ); } catch ( \Exception $e ) { $this->action_counts['failed']++; \WP_CLI::warning( $e->getMessage() ); } $progress_bar->tick(); } $progress_bar->finish(); /* translators: %1$d: number of actions deleted */ $format = _n( 'Deleted %1$d action', 'Deleted %1$d actions', $this->action_counts['deleted'], 'action-scheduler' ) . ', '; /* translators: %2$d: number of actions deletions failed */ $format .= _n( '%2$d failure.', '%2$d failures.', $this->action_counts['failed'], 'action-scheduler' ); \WP_CLI::success( sprintf( $format, number_format_i18n( $this->action_counts['deleted'] ), number_format_i18n( $this->action_counts['failed'] ) ) ); } /** * Action: action_scheduler_deleted_action * * @param int $action_id Action ID. * @return void */ public function on_action_deleted( $action_id ) { if ( 'action_scheduler_deleted_action' !== current_action() ) { return; } $action_id = absint( $action_id ); if ( ! in_array( $action_id, $this->action_ids, true ) ) { return; } $this->action_counts['deleted']++; \WP_CLI::debug( sprintf( 'Action %d was deleted.', $action_id ) ); } } woocommerce/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Scheduler_command.php 0000644 00000015307 15151523434 0025216 0 ustar 00 <?php /** * Commands for Action Scheduler. */ class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command { /** * Force tables schema creation for Action Scheduler * * ## OPTIONS * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * * @subcommand fix-schema */ public function fix_schema( $args, $assoc_args ) { $schema_classes = array( ActionScheduler_LoggerSchema::class, ActionScheduler_StoreSchema::class ); foreach ( $schema_classes as $classname ) { if ( is_subclass_of( $classname, ActionScheduler_Abstract_Schema::class ) ) { $obj = new $classname(); $obj->init(); $obj->register_tables( true ); WP_CLI::success( sprintf( /* translators: %s refers to the schema name*/ __( 'Registered schema for %s', 'action-scheduler' ), $classname ) ); } } } /** * Run the Action Scheduler * * ## OPTIONS * * [--batch-size=<size>] * : The maximum number of actions to run. Defaults to 100. * * [--batches=<size>] * : Limit execution to a number of batches. Defaults to 0, meaning batches will continue being executed until all actions are complete. * * [--cleanup-batch-size=<size>] * : The maximum number of actions to clean up. Defaults to the value of --batch-size. * * [--hooks=<hooks>] * : Only run actions with the specified hook. Omitting this option runs actions with any hook. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=hook_one,hook_two,hook_three` * * [--group=<group>] * : Only run actions from the specified group. Omitting this option runs actions from all groups. * * [--exclude-groups=<groups>] * : Run actions from all groups except the specified group(s). Define multiple groups as a comma separated string (without spaces), e.g. '--group_a,group_b'. This option is ignored when `--group` is used. * * [--free-memory-on=<count>] * : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50. * * [--pause=<seconds>] * : The number of seconds to pause when freeing memory. Default no pause. * * [--force] * : Whether to force execution despite the maximum number of concurrent processes being exceeded. * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @throws \WP_CLI\ExitException When an error occurs. * * @subcommand run */ public function run( $args, $assoc_args ) { // Handle passed arguments. $batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 100 ) ); $batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) ); $clean = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'cleanup-batch-size', $batch ) ); $hooks = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) ); $hooks = array_filter( array_map( 'trim', $hooks ) ); $group = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' ); $exclude_groups = \WP_CLI\Utils\get_flag_value( $assoc_args, 'exclude-groups', '' ); $free_on = \WP_CLI\Utils\get_flag_value( $assoc_args, 'free-memory-on', 50 ); $sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 ); $force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false ); ActionScheduler_DataController::set_free_ticks( $free_on ); ActionScheduler_DataController::set_sleep_time( $sleep ); $batches_completed = 0; $actions_completed = 0; $unlimited = 0 === $batches; if ( is_callable( array( ActionScheduler::store(), 'set_claim_filter' ) ) ) { $exclude_groups = $this->parse_comma_separated_string( $exclude_groups ); if ( ! empty( $exclude_groups ) ) { ActionScheduler::store()->set_claim_filter( 'exclude-groups', $exclude_groups ); } } try { // Custom queue cleaner instance. $cleaner = new ActionScheduler_QueueCleaner( null, $clean ); // Get the queue runner instance. $runner = new ActionScheduler_WPCLI_QueueRunner( null, null, $cleaner ); // Determine how many tasks will be run in the first batch. $total = $runner->setup( $batch, $hooks, $group, $force ); // Run actions for as long as possible. while ( $total > 0 ) { $this->print_total_actions( $total ); $actions_completed += $runner->run(); $batches_completed++; // Maybe set up tasks for the next batch. $total = ( $unlimited || $batches_completed < $batches ) ? $runner->setup( $batch, $hooks, $group, $force ) : 0; } } catch ( Exception $e ) { $this->print_error( $e ); } $this->print_total_batches( $batches_completed ); $this->print_success( $actions_completed ); } /** * Converts a string of comma-separated values into an array of those same values. * * @param string $string The string of one or more comma separated values. * * @return array */ private function parse_comma_separated_string( $string ): array { return array_filter( str_getcsv( $string ) ); } /** * Print WP CLI message about how many actions are about to be processed. * * @param int $total Number of actions found. */ protected function print_total_actions( $total ) { WP_CLI::log( sprintf( /* translators: %d refers to how many scheduled tasks were found to run */ _n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ), $total ) ); } /** * Print WP CLI message about how many batches of actions were processed. * * @param int $batches_completed Number of completed batches. */ protected function print_total_batches( $batches_completed ) { WP_CLI::log( sprintf( /* translators: %d refers to the total number of batches executed */ _n( '%d batch executed.', '%d batches executed.', $batches_completed, 'action-scheduler' ), $batches_completed ) ); } /** * Convert an exception into a WP CLI error. * * @param Exception $e The error object. * * @throws \WP_CLI\ExitException Under some conditions WP CLI may throw an exception. */ protected function print_error( Exception $e ) { WP_CLI::error( sprintf( /* translators: %s refers to the exception error message */ __( 'There was an error running the action scheduler: %s', 'action-scheduler' ), $e->getMessage() ) ); } /** * Print a success message with the number of completed actions. * * @param int $actions_completed Number of completed actions. */ protected function print_success( $actions_completed ) { WP_CLI::success( sprintf( /* translators: %d refers to the total number of tasks completed */ _n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ), $actions_completed ) ); } } woocommerce/action-scheduler/classes/WP_CLI/Migration_Command.php 0000644 00000011670 15151523434 0021076 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI; use Action_Scheduler\Migration\Config; use Action_Scheduler\Migration\Runner; use Action_Scheduler\Migration\Scheduler; use Action_Scheduler\Migration\Controller; use WP_CLI; use WP_CLI_Command; /** * Class Migration_Command * * @package Action_Scheduler\WP_CLI * * @since 3.0.0 * * @codeCoverageIgnore */ class Migration_Command extends WP_CLI_Command { /** * Number of actions migrated. * * @var int */ private $total_processed = 0; /** * Register the command with WP-CLI */ public function register() { if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) { return; } WP_CLI::add_command( 'action-scheduler migrate', array( $this, 'migrate' ), array( 'shortdesc' => 'Migrates actions to the DB tables store', 'synopsis' => array( array( 'type' => 'assoc', 'name' => 'batch-size', 'optional' => true, 'default' => 100, 'description' => 'The number of actions to process in each batch', ), array( 'type' => 'assoc', 'name' => 'free-memory-on', 'optional' => true, 'default' => 50, 'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory', ), array( 'type' => 'assoc', 'name' => 'pause', 'optional' => true, 'default' => 0, 'description' => 'The number of seconds to pause when freeing memory', ), array( 'type' => 'flag', 'name' => 'dry-run', 'optional' => true, 'description' => 'Reports on the actions that would have been migrated, but does not change any data', ), ), ) ); } /** * Process the data migration. * * @param array $positional_args Required for WP CLI. Not used in migration. * @param array $assoc_args Optional arguments. * * @return void */ public function migrate( $positional_args, $assoc_args ) { $this->init_logging(); $config = $this->get_migration_config( $assoc_args ); $runner = new Runner( $config ); $runner->init_destination(); $batch_size = isset( $assoc_args['batch-size'] ) ? (int) $assoc_args['batch-size'] : 100; $free_on = isset( $assoc_args['free-memory-on'] ) ? (int) $assoc_args['free-memory-on'] : 50; $sleep = isset( $assoc_args['pause'] ) ? (int) $assoc_args['pause'] : 0; \ActionScheduler_DataController::set_free_ticks( $free_on ); \ActionScheduler_DataController::set_sleep_time( $sleep ); do { $actions_processed = $runner->run( $batch_size ); $this->total_processed += $actions_processed; } while ( $actions_processed > 0 ); if ( ! $config->get_dry_run() ) { // let the scheduler know that there's nothing left to do. $scheduler = new Scheduler(); $scheduler->mark_complete(); } WP_CLI::success( sprintf( '%s complete. %d actions processed.', $config->get_dry_run() ? 'Dry run' : 'Migration', $this->total_processed ) ); } /** * Build the config object used to create the Runner * * @param array $args Optional arguments. * * @return ActionScheduler\Migration\Config */ private function get_migration_config( $args ) { $args = wp_parse_args( $args, array( 'dry-run' => false, ) ); $config = Controller::instance()->get_migration_config_object(); $config->set_dry_run( ! empty( $args['dry-run'] ) ); return $config; } /** * Hook command line logging into migration actions. */ private function init_logging() { add_action( 'action_scheduler/migrate_action_dry_run', function ( $action_id ) { WP_CLI::debug( sprintf( 'Dry-run: migrated action %d', $action_id ) ); } ); add_action( 'action_scheduler/no_action_to_migrate', function ( $action_id ) { WP_CLI::debug( sprintf( 'No action found to migrate for ID %d', $action_id ) ); } ); add_action( 'action_scheduler/migrate_action_failed', function ( $action_id ) { WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) ); } ); add_action( 'action_scheduler/migrate_action_incomplete', function ( $source_id, $destination_id ) { WP_CLI::warning( sprintf( 'Unable to remove source action with ID %d after migrating to new ID %d', $source_id, $destination_id ) ); }, 10, 2 ); add_action( 'action_scheduler/migrated_action', function ( $source_id, $destination_id ) { WP_CLI::debug( sprintf( 'Migrated source action with ID %d to new store with ID %d', $source_id, $destination_id ) ); }, 10, 2 ); add_action( 'action_scheduler/migration_batch_starting', function ( $batch ) { WP_CLI::debug( 'Beginning migration of batch: ' . print_r( $batch, true ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r } ); add_action( 'action_scheduler/migration_batch_complete', function ( $batch ) { WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) ); } ); } } woocommerce/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Clean_Command.php 0000644 00000007363 15151523434 0024265 0 ustar 00 <?php /** * Commands for Action Scheduler. */ class ActionScheduler_WPCLI_Clean_Command extends WP_CLI_Command { /** * Run the Action Scheduler Queue Cleaner * * ## OPTIONS * * [--batch-size=<size>] * : The maximum number of actions to delete per batch. Defaults to 20. * * [--batches=<size>] * : Limit execution to a number of batches. Defaults to 0, meaning batches will continue all eligible actions are deleted. * * [--status=<status>] * : Only clean actions with the specified status. Defaults to Canceled, Completed. Define multiple statuses as a comma separated string (without spaces), e.g. `--status=complete,failed,canceled` * * [--before=<datestring>] * : Only delete actions with scheduled date older than this. Defaults to 31 days. e.g `--before='7 days ago'`, `--before='02-Feb-2020 20:20:20'` * * [--pause=<seconds>] * : The number of seconds to pause between batches. Default no pause. * * @param array $args Positional arguments. * @param array $assoc_args Keyed arguments. * @throws \WP_CLI\ExitException When an error occurs. * * @subcommand clean */ public function clean( $args, $assoc_args ) { // Handle passed arguments. $batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 20 ) ); $batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) ); $status = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'status', '' ) ); $status = array_filter( array_map( 'trim', $status ) ); $before = \WP_CLI\Utils\get_flag_value( $assoc_args, 'before', '' ); $sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 ); $batches_completed = 0; $actions_deleted = 0; $unlimited = 0 === $batches; try { $lifespan = as_get_datetime_object( $before ); } catch ( Exception $e ) { $lifespan = null; } try { // Custom queue cleaner instance. $cleaner = new ActionScheduler_QueueCleaner( null, $batch ); // Clean actions for as long as possible. while ( $unlimited || $batches_completed < $batches ) { if ( $sleep && $batches_completed > 0 ) { sleep( $sleep ); } $deleted = count( $cleaner->clean_actions( $status, $lifespan, null, 'CLI' ) ); if ( $deleted <= 0 ) { break; } $actions_deleted += $deleted; $batches_completed++; $this->print_success( $deleted ); } } catch ( Exception $e ) { $this->print_error( $e ); } $this->print_total_batches( $batches_completed ); if ( $batches_completed > 1 ) { $this->print_success( $actions_deleted ); } } /** * Print WP CLI message about how many batches of actions were processed. * * @param int $batches_processed Number of batches processed. */ protected function print_total_batches( int $batches_processed ) { WP_CLI::log( sprintf( /* translators: %d refers to the total number of batches processed */ _n( '%d batch processed.', '%d batches processed.', $batches_processed, 'action-scheduler' ), $batches_processed ) ); } /** * Convert an exception into a WP CLI error. * * @param Exception $e The error object. */ protected function print_error( Exception $e ) { WP_CLI::error( sprintf( /* translators: %s refers to the exception error message */ __( 'There was an error deleting an action: %s', 'action-scheduler' ), $e->getMessage() ) ); } /** * Print a success message with the number of completed actions. * * @param int $actions_deleted Number of deleted actions. */ protected function print_success( int $actions_deleted ) { WP_CLI::success( sprintf( /* translators: %d refers to the total number of actions deleted */ _n( '%d action deleted.', '%d actions deleted.', $actions_deleted, 'action-scheduler' ), $actions_deleted ) ); } } woocommerce/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_QueueRunner.php 0000644 00000014331 15151523434 0024054 0 ustar 00 <?php use Action_Scheduler\WP_CLI\ProgressBar; /** * WP CLI Queue runner. * * This class can only be called from within a WP CLI instance. */ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner { /** * Claimed actions. * * @var array */ protected $actions; /** * ActionScheduler_ActionClaim instance. * * @var ActionScheduler_ActionClaim */ protected $claim; /** * Progress bar instance. * * @var \cli\progress\Bar */ protected $progress_bar; /** * ActionScheduler_WPCLI_QueueRunner constructor. * * @param ActionScheduler_Store|null $store Store object. * @param ActionScheduler_FatalErrorMonitor|null $monitor Monitor object. * @param ActionScheduler_QueueCleaner|null $cleaner Cleaner object. * * @throws Exception When this is not run within WP CLI. */ public function __construct( ?ActionScheduler_Store $store = null, ?ActionScheduler_FatalErrorMonitor $monitor = null, ?ActionScheduler_QueueCleaner $cleaner = null ) { if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) { /* translators: %s php class name */ throw new Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) ); } parent::__construct( $store, $monitor, $cleaner ); } /** * Set up the Queue before processing. * * @param int $batch_size The batch size to process. * @param array $hooks The hooks being used to filter the actions claimed in this batch. * @param string $group The group of actions to claim with this batch. * @param bool $force Whether to force running even with too many concurrent processes. * * @return int The number of actions that will be run. * @throws \WP_CLI\ExitException When there are too many concurrent batches. */ public function setup( $batch_size, $hooks = array(), $group = '', $force = false ) { $this->run_cleanup(); $this->add_hooks(); // Check to make sure there aren't too many concurrent processes running. if ( $this->has_maximum_concurrent_batches() ) { if ( $force ) { WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) ); } else { WP_CLI::error( __( 'There are too many concurrent batches.', 'action-scheduler' ) ); } } // Stake a claim and store it. $this->claim = $this->store->stake_claim( $batch_size, null, $hooks, $group ); $this->monitor->attach( $this->claim ); $this->actions = $this->claim->get_actions(); return count( $this->actions ); } /** * Add our hooks to the appropriate actions. */ protected function add_hooks() { add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) ); add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ), 10, 2 ); add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 ); } /** * Set up the WP CLI progress bar. */ protected function setup_progress_bar() { $count = count( $this->actions ); $this->progress_bar = new ProgressBar( /* translators: %d: amount of actions */ sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), $count ), $count ); } /** * Process actions in the queue. * * @param string $context Optional runner context. Default 'WP CLI'. * * @return int The number of actions processed. */ public function run( $context = 'WP CLI' ) { do_action( 'action_scheduler_before_process_queue' ); $this->setup_progress_bar(); foreach ( $this->actions as $action_id ) { // Error if we lost the claim. if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $this->claim->get_id() ), true ) ) { WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) ); break; } $this->process_action( $action_id, $context ); $this->progress_bar->tick(); } $completed = $this->progress_bar->current(); $this->progress_bar->finish(); $this->store->release_claim( $this->claim ); do_action( 'action_scheduler_after_process_queue' ); return $completed; } /** * Handle WP CLI message when the action is starting. * * @param int $action_id Action ID. */ public function before_execute( $action_id ) { /* translators: %s refers to the action ID */ WP_CLI::log( sprintf( __( 'Started processing action %s', 'action-scheduler' ), $action_id ) ); } /** * Handle WP CLI message when the action has completed. * * @param int $action_id ActionID. * @param null|ActionScheduler_Action $action The instance of the action. Default to null for backward compatibility. */ public function after_execute( $action_id, $action = null ) { // backward compatibility. if ( null === $action ) { $action = $this->store->fetch_action( $action_id ); } /* translators: 1: action ID 2: hook name */ WP_CLI::log( sprintf( __( 'Completed processing action %1$s with hook: %2$s', 'action-scheduler' ), $action_id, $action->get_hook() ) ); } /** * Handle WP CLI message when the action has failed. * * @param int $action_id Action ID. * @param Exception $exception Exception. * @throws \WP_CLI\ExitException With failure message. */ public function action_failed( $action_id, $exception ) { WP_CLI::error( /* translators: 1: action ID 2: exception message */ sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ), false ); } /** * Sleep and help avoid hitting memory limit * * @param int $sleep_time Amount of seconds to sleep. * @deprecated 3.0.0 */ protected function stop_the_insanity( $sleep_time = 0 ) { _deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' ); ActionScheduler_DataController::free_memory(); } /** * Maybe trigger the stop_the_insanity() method to free up memory. */ protected function maybe_stop_the_insanity() { // The value returned by progress_bar->current() might be padded. Remove padding, and convert to int. $current_iteration = intval( trim( $this->progress_bar->current() ) ); if ( 0 === $current_iteration % 50 ) { $this->stop_the_insanity(); } } } woocommerce/action-scheduler/classes/WP_CLI/ProgressBar.php 0000644 00000005316 15151523434 0017740 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI; /** * WP_CLI progress bar for Action Scheduler. */ /** * Class ProgressBar * * @package Action_Scheduler\WP_CLI * * @since 3.0.0 * * @codeCoverageIgnore */ class ProgressBar { /** * Current number of ticks. * * @var integer */ protected $total_ticks; /** * Total number of ticks. * * @var integer */ protected $count; /** * Progress bar update interval. * * @var integer */ protected $interval; /** * Progress bar message. * * @var string */ protected $message; /** * Instance. * * @var \cli\progress\Bar */ protected $progress_bar; /** * ProgressBar constructor. * * @param string $message Text to display before the progress bar. * @param integer $count Total number of ticks to be performed. * @param integer $interval Optional. The interval in milliseconds between updates. Default 100. * * @throws \Exception When this is not run within WP CLI. */ public function __construct( $message, $count, $interval = 100 ) { if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) { /* translators: %s php class name */ throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) ); } $this->total_ticks = 0; $this->message = $message; $this->count = $count; $this->interval = $interval; } /** * Increment the progress bar ticks. */ public function tick() { if ( null === $this->progress_bar ) { $this->setup_progress_bar(); } $this->progress_bar->tick(); $this->total_ticks++; do_action( 'action_scheduler/progress_tick', $this->total_ticks ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Get the progress bar tick count. * * @return int */ public function current() { return $this->progress_bar ? $this->progress_bar->current() : 0; } /** * Finish the current progress bar. */ public function finish() { if ( null !== $this->progress_bar ) { $this->progress_bar->finish(); } $this->progress_bar = null; } /** * Set the message used when creating the progress bar. * * @param string $message The message to be used when the next progress bar is created. */ public function set_message( $message ) { $this->message = $message; } /** * Set the count for a new progress bar. * * @param integer $count The total number of ticks expected to complete. */ public function set_count( $count ) { $this->count = $count; $this->finish(); } /** * Set up the progress bar. */ protected function setup_progress_bar() { $this->progress_bar = \WP_CLI\Utils\make_progress_bar( $this->message, $this->count, $this->interval ); } } woocommerce/action-scheduler/classes/WP_CLI/System_Command.php 0000644 00000016105 15151523434 0020427 0 ustar 00 <?php namespace Action_Scheduler\WP_CLI; // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI. use ActionScheduler_SystemInformation; use WP_CLI; use function \WP_CLI\Utils\get_flag_value; /** * System info WP-CLI commands for Action Scheduler. */ class System_Command { /** * Data store for querying actions * * @var ActionScheduler_Store */ protected $store; /** * Construct. */ public function __construct() { $this->store = \ActionScheduler::store(); } /** * Print in-use data store class. * * @param array $args Positional args. * @param array $assoc_args Keyed args. * @return void * * @subcommand data-store */ public function datastore( array $args, array $assoc_args ) { echo $this->get_current_datastore(); } /** * Print in-use runner class. * * @param array $args Positional args. * @param array $assoc_args Keyed args. * @return void */ public function runner( array $args, array $assoc_args ) { echo $this->get_current_runner(); } /** * Get system status. * * @param array $args Positional args. * @param array $assoc_args Keyed args. * @return void */ public function status( array $args, array $assoc_args ) { /** * Get runner status. * * @link https://github.com/woocommerce/action-scheduler-disable-default-runner */ $runner_enabled = has_action( 'action_scheduler_run_queue', array( \ActionScheduler::runner(), 'run' ) ); \WP_CLI::line( sprintf( 'Data store: %s', $this->get_current_datastore() ) ); \WP_CLI::line( sprintf( 'Runner: %s%s', $this->get_current_runner(), ( $runner_enabled ? '' : ' (disabled)' ) ) ); \WP_CLI::line( sprintf( 'Version: %s', $this->get_latest_version() ) ); $rows = array(); $action_counts = $this->store->action_counts(); $oldest_and_newest = $this->get_oldest_and_newest( array_keys( $action_counts ) ); foreach ( $action_counts as $status => $count ) { $rows[] = array( 'status' => $status, 'count' => $count, 'oldest' => $oldest_and_newest[ $status ]['oldest'], 'newest' => $oldest_and_newest[ $status ]['newest'], ); } $formatter = new \WP_CLI\Formatter( $assoc_args, array( 'status', 'count', 'oldest', 'newest' ) ); $formatter->display_items( $rows ); } /** * Display the active version, or all registered versions. * * ## OPTIONS * * [--all] * : List all registered versions. * * @param array $args Positional args. * @param array $assoc_args Keyed args. * @return void */ public function version( array $args, array $assoc_args ) { $all = (bool) get_flag_value( $assoc_args, 'all' ); $latest = $this->get_latest_version(); if ( ! $all ) { echo $latest; \WP_CLI::halt( 0 ); } $instance = \ActionScheduler_Versions::instance(); $versions = $instance->get_versions(); $rows = array(); foreach ( $versions as $version => $callback ) { $active = $version === $latest; $rows[ $version ] = array( 'version' => $version, 'callback' => $callback, 'active' => $active ? 'yes' : 'no', ); } uksort( $rows, 'version_compare' ); $formatter = new \WP_CLI\Formatter( $assoc_args, array( 'version', 'callback', 'active' ) ); $formatter->display_items( $rows ); } /** * Display the current source, or all registered sources. * * ## OPTIONS * * [--all] * : List all registered sources. * * [--fullpath] * : List full path of source(s). * * @param array $args Positional args. * @param array $assoc_args Keyed args. * @uses ActionScheduler_SystemInformation::active_source_path() * @uses \WP_CLI\Formatter::display_items() * @uses $this->get_latest_version() * @return void */ public function source( array $args, array $assoc_args ) { $all = (bool) get_flag_value( $assoc_args, 'all' ); $fullpath = (bool) get_flag_value( $assoc_args, 'fullpath' ); $source = ActionScheduler_SystemInformation::active_source_path(); $path = $source; if ( ! $fullpath ) { $path = str_replace( ABSPATH, '', $path ); } if ( ! $all ) { echo $path; \WP_CLI::halt( 0 ); } $sources = ActionScheduler_SystemInformation::get_sources(); if ( empty( $sources ) ) { WP_CLI::log( __( 'Detailed information about registered sources is not currently available.', 'action-scheduler' ) ); return; } $rows = array(); foreach ( $sources as $check_source => $version ) { $active = dirname( $check_source ) === $source; $path = $check_source; if ( ! $fullpath ) { $path = str_replace( ABSPATH, '', $path ); } $rows[ $check_source ] = array( 'source' => $path, 'version' => $version, 'active' => $active ? 'yes' : 'no', ); } ksort( $rows ); \WP_CLI::log( PHP_EOL . 'Please note there can only be one unique registered instance of Action Scheduler per ' . PHP_EOL . 'version number, so this list may not include all the currently present copies of ' . PHP_EOL . 'Action Scheduler.' . PHP_EOL ); $formatter = new \WP_CLI\Formatter( $assoc_args, array( 'source', 'version', 'active' ) ); $formatter->display_items( $rows ); } /** * Get current data store. * * @return string */ protected function get_current_datastore() { return get_class( $this->store ); } /** * Get latest version. * * @param null|\ActionScheduler_Versions $instance Versions. * @return string */ protected function get_latest_version( $instance = null ) { if ( is_null( $instance ) ) { $instance = \ActionScheduler_Versions::instance(); } return $instance->latest_version(); } /** * Get current runner. * * @return string */ protected function get_current_runner() { return get_class( \ActionScheduler::runner() ); } /** * Get oldest and newest scheduled dates for a given set of statuses. * * @param array $status_keys Set of statuses to find oldest & newest action for. * @return array */ protected function get_oldest_and_newest( $status_keys ) { $oldest_and_newest = array(); foreach ( $status_keys as $status ) { $oldest_and_newest[ $status ] = array( 'oldest' => '–', '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 string */ protected function get_action_status_date( $status, $date_type = 'oldest' ) { $order = 'oldest' === $date_type ? 'ASC' : 'DESC'; $args = array( 'status' => $status, 'per_page' => 1, 'order' => $order, ); $action = $this->store->query_actions( $args ); if ( ! empty( $action ) ) { $date_object = $this->store->get_date( $action[0] ); $action_date = $date_object->format( 'Y-m-d H:i:s O' ); } else { $action_date = '–'; } return $action_date; } } woocommerce/action-scheduler/classes/ActionScheduler_QueueRunner.php 0000644 00000022770 15151523435 0022110 0 ustar 00 <?php /** * Class ActionScheduler_QueueRunner */ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner { const WP_CRON_HOOK = 'action_scheduler_run_queue'; const WP_CRON_SCHEDULE = 'every_minute'; /** * ActionScheduler_AsyncRequest_QueueRunner instance. * * @var ActionScheduler_AsyncRequest_QueueRunner */ protected $async_request; /** * ActionScheduler_QueueRunner instance. * * @var ActionScheduler_QueueRunner */ private static $runner = null; /** * Number of processed actions. * * @var int */ private $processed_actions_count = 0; /** * Get instance. * * @return ActionScheduler_QueueRunner * @codeCoverageIgnore */ public static function instance() { if ( empty( self::$runner ) ) { $class = apply_filters( 'action_scheduler_queue_runner_class', 'ActionScheduler_QueueRunner' ); self::$runner = new $class(); } return self::$runner; } /** * ActionScheduler_QueueRunner constructor. * * @param ActionScheduler_Store|null $store Store object. * @param ActionScheduler_FatalErrorMonitor|null $monitor Monitor object. * @param ActionScheduler_QueueCleaner|null $cleaner Cleaner object. * @param ActionScheduler_AsyncRequest_QueueRunner|null $async_request Async request runner object. */ public function __construct( ?ActionScheduler_Store $store = null, ?ActionScheduler_FatalErrorMonitor $monitor = null, ?ActionScheduler_QueueCleaner $cleaner = null, ?ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) { parent::__construct( $store, $monitor, $cleaner ); if ( is_null( $async_request ) ) { $async_request = new ActionScheduler_AsyncRequest_QueueRunner( $this->store ); } $this->async_request = $async_request; } /** * Initialize. * * @codeCoverageIgnore */ public function init() { add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval // Check for and remove any WP Cron hook scheduled by Action Scheduler < 3.0.0, which didn't include the $context param. $next_timestamp = wp_next_scheduled( self::WP_CRON_HOOK ); if ( $next_timestamp ) { wp_unschedule_event( $next_timestamp, self::WP_CRON_HOOK ); } $cron_context = array( 'WP Cron' ); if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) { $schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE ); wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context ); } add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) ); $this->hook_dispatch_async_request(); } /** * Hook check for dispatching an async request. */ public function hook_dispatch_async_request() { add_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) ); } /** * Unhook check for dispatching an async request. */ public function unhook_dispatch_async_request() { remove_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) ); } /** * Check if we should dispatch an async request to process actions. * * This method is attached to 'shutdown', so is called frequently. To avoid slowing down * the site, it mitigates the work performed in each request by: * 1. checking if it's in the admin context and then * 2. haven't run on the 'shutdown' hook within the lock time (60 seconds by default) * 3. haven't exceeded the number of allowed batches. * * The order of these checks is important, because they run from a check on a value: * 1. in memory - is_admin() maps to $GLOBALS or the WP_ADMIN constant * 2. in memory - transients use autoloaded options by default * 3. from a database query - has_maximum_concurrent_batches() run the query * $this->store->get_claim_count() to find the current number of claims in the DB. * * If all of these conditions are met, then we request an async runner check whether it * should dispatch a request to process pending actions. */ public function maybe_dispatch_async_request() { // Only start an async queue at most once every 60 seconds. if ( is_admin() && ! ActionScheduler::lock()->is_locked( 'async-request-runner' ) && ActionScheduler::lock()->set( 'async-request-runner' ) ) { $this->async_request->maybe_dispatch(); } } /** * Process actions in the queue. Attached to self::WP_CRON_HOOK i.e. 'action_scheduler_run_queue' * * The $context param of this method defaults to 'WP Cron', because prior to Action Scheduler 3.0.0 * that was the only context in which this method was run, and the self::WP_CRON_HOOK hook had no context * passed along with it. New code calling this method directly, or by triggering the self::WP_CRON_HOOK, * should set a context as the first parameter. For an example of this, refer to the code seen in * * @see ActionScheduler_AsyncRequest_QueueRunner::handle() * * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @return int The number of actions processed. */ public function run( $context = 'WP Cron' ) { ActionScheduler_Compatibility::raise_memory_limit(); ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() ); do_action( 'action_scheduler_before_process_queue' ); $this->run_cleanup(); $this->processed_actions_count = 0; if ( false === $this->has_maximum_concurrent_batches() ) { do { $batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 ); $processed_actions_in_batch = $this->do_batch( $batch_size, $context ); $this->processed_actions_count += $processed_actions_in_batch; } while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $this->processed_actions_count ) ); // keep going until we run out of actions, time, or memory. } do_action( 'action_scheduler_after_process_queue' ); return $this->processed_actions_count; } /** * Process a batch of actions pending in the queue. * * Actions are processed by claiming a set of pending actions then processing each one until either the batch * size is completed, or memory or time limits are reached, defined by @see $this->batch_limits_exceeded(). * * @param int $size The maximum number of actions to process in the batch. * @param string $context Optional identifier for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron' * Generally, this should be capitalised and not localised as it's a proper noun. * @return int The number of actions processed. */ protected function do_batch( $size = 100, $context = '' ) { $claim = $this->store->stake_claim( $size ); $this->monitor->attach( $claim ); $processed_actions = 0; foreach ( $claim->get_actions() as $action_id ) { // bail if we lost the claim. if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ), true ) ) { break; } $this->process_action( $action_id, $context ); $processed_actions++; if ( $this->batch_limits_exceeded( $processed_actions + $this->processed_actions_count ) ) { break; } } $this->store->release_claim( $claim ); $this->monitor->detach(); $this->clear_caches(); return $processed_actions; } /** * Flush the cache if possible (intended for use after a batch of actions has been processed). * * This is useful because running large batches can eat up memory and because invalid data can accrue in the * runtime cache, which may lead to unexpected results. */ protected function clear_caches() { /* * Calling wp_cache_flush_runtime() lets us clear the runtime cache without invalidating the external object * cache, so we will always prefer this method (as compared to calling wp_cache_flush()) when it is available. * * However, this function was only introduced in WordPress 6.0. Additionally, the preferred way of detecting if * it is supported changed in WordPress 6.1 so we use two different methods to decide if we should utilize it. */ $flushing_runtime_cache_explicitly_supported = function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ); $flushing_runtime_cache_implicitly_supported = ! function_exists( 'wp_cache_supports' ) && function_exists( 'wp_cache_flush_runtime' ); if ( $flushing_runtime_cache_explicitly_supported || $flushing_runtime_cache_implicitly_supported ) { wp_cache_flush_runtime(); } elseif ( ! wp_using_ext_object_cache() /** * When an external object cache is in use, and when wp_cache_flush_runtime() is not available, then * normally the cache will not be flushed after processing a batch of actions (to avoid a performance * penalty for other processes). * * This filter makes it possible to override this behavior and always flush the cache, even if an external * object cache is in use. * * @since 1.0 * * @param bool $flush_cache If the cache should be flushed. */ || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) { wp_cache_flush(); } } /** * Add schedule to WP cron. * * @param array<string, array<string, int|string>> $schedules Schedules. * @return array<string, array<string, int|string>> */ public function add_wp_cron_schedule( $schedules ) { $schedules['every_minute'] = array( 'interval' => 60, // in seconds. 'display' => __( 'Every minute', 'action-scheduler' ), ); return $schedules; } } woocommerce/action-scheduler/classes/ActionScheduler_wcSystemStatus.php 0000644 00000012237 15151523435 0022651 0 ustar 00 <?php /** * Class ActionScheduler_wcSystemStatus */ class ActionScheduler_wcSystemStatus { /** * The active data stores * * @var ActionScheduler_Store */ protected $store; /** * Constructor method for ActionScheduler_wcSystemStatus. * * @param ActionScheduler_Store $store Active store object. * * @return void */ public function __construct( $store ) { $this->store = $store; } /** * Display action data, including number of actions grouped by status and the oldest & newest action in each status. * * Helpful to identify issues, like a clogged queue. */ public function render() { $action_counts = $this->store->action_counts(); $status_labels = $this->store->get_status_labels(); $oldest_and_newest = $this->get_oldest_and_newest( array_keys( $status_labels ) ); $this->get_template( $status_labels, $action_counts, $oldest_and_newest ); } /** * Get oldest and newest scheduled dates for a given set of statuses. * * @param array $status_keys Set of statuses to find oldest & newest action for. * @return array */ protected function get_oldest_and_newest( $status_keys ) { $oldest_and_newest = array(); foreach ( $status_keys as $status ) { $oldest_and_newest[ $status ] = array( 'oldest' => '–', '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( '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() ); ?> <table class="wc_status_table widefat" cellspacing="0"> <thead> <tr> <th colspan="5" data-export-label="Action Scheduler"><h2><?php esc_html_e( 'Action Scheduler', 'action-scheduler' ); ?><?php echo wc_help_tip( esc_html__( 'This section shows details of Action Scheduler.', 'action-scheduler' ) ); ?></h2></th> </tr> <tr> <td colspan="2" data-export-label="Version"><?php esc_html_e( 'Version:', 'action-scheduler' ); ?></td> <td colspan="3"><?php echo esc_html( $as_version ); ?></td> </tr> <tr> <td colspan="2" data-export-label="Data store"><?php esc_html_e( 'Data store:', 'action-scheduler' ); ?></td> <td colspan="3"><?php echo esc_html( $as_datastore ); ?></td> </tr> <tr> <td><strong><?php esc_html_e( 'Action Status', 'action-scheduler' ); ?></strong></td> <td class="help"> </td> <td><strong><?php esc_html_e( 'Count', 'action-scheduler' ); ?></strong></td> <td><strong><?php esc_html_e( 'Oldest Scheduled Date', 'action-scheduler' ); ?></strong></td> <td><strong><?php esc_html_e( 'Newest Scheduled Date', 'action-scheduler' ); ?></strong></td> </tr> </thead> <tbody> <?php foreach ( $action_counts as $status => $count ) { // WC uses the 3rd column for export, so we need to display more data in that (hidden when viewed as part of the table) and add an empty 2nd column. printf( '<tr><td>%1$s</td><td> </td><td>%2$s<span style="display: none;">, Oldest: %3$s, Newest: %4$s</span></td><td>%3$s</td><td>%4$s</td></tr>', esc_html( $status_labels[ $status ] ), esc_html( number_format_i18n( $count ) ), esc_html( $oldest_and_newest[ $status ]['oldest'] ), esc_html( $oldest_and_newest[ $status ]['newest'] ) ); } ?> </tbody> </table> <?php } /** * Is triggered when invoking inaccessible methods in an object context. * * @param string $name Name of method called. * @param array $arguments Parameters to invoke the method with. * * @return mixed * @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods */ public function __call( $name, $arguments ) { switch ( $name ) { case 'print': _deprecated_function( __CLASS__ . '::print()', '2.2.4', __CLASS__ . '::render()' ); return call_user_func_array( array( $this, 'render' ), $arguments ); } return null; } } woocommerce/action-scheduler/classes/ActionScheduler_RecurringActionScheduler.php 0000644 00000006063 15151523435 0024564 0 ustar 00 <?php /** * Class ActionScheduler_RecurringActionScheduler * * This class ensures that the `action_scheduler_ensure_recurring_actions` hook is triggered on a daily interval. This * simplifies the process for other plugins to register their recurring actions without requiring each plugin to query * or schedule actions independently on every request. */ class ActionScheduler_RecurringActionScheduler { /** * @var string The hook of the scheduled recurring action that is run to trigger the * `action_scheduler_ensure_recurring_actions` hook that plugins should use. We can't directly have the * scheduled action hook be the hook plugins should use because the actions will show as failed if no plugin * was actively hooked into it. */ private const RUN_SCHEDULED_RECURRING_ACTIONS_HOOK = 'action_scheduler_run_recurring_actions_schedule_hook'; /** * Initialize the instance. Should only be run on a single instance per request. * * @return void */ public function init(): void { add_action( self::RUN_SCHEDULED_RECURRING_ACTIONS_HOOK, array( $this, 'run_recurring_scheduler_hook' ) ); if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) { add_action( 'action_scheduler_init', array( $this, 'schedule_recurring_scheduler_hook' ) ); } } /** * Schedule the recurring `action_scheduler_ensure_recurring_actions` action if not already scheduled. * * @return void */ public function schedule_recurring_scheduler_hook(): void { if ( false === wp_cache_get( 'as_is_ensure_recurring_actions_scheduled' ) ) { if ( ! as_has_scheduled_action( self::RUN_SCHEDULED_RECURRING_ACTIONS_HOOK ) ) { as_schedule_recurring_action( time(), DAY_IN_SECONDS, self::RUN_SCHEDULED_RECURRING_ACTIONS_HOOK, [], 'ActionScheduler', true, 20 ); } wp_cache_set( 'as_is_ensure_recurring_actions_scheduled', true, HOUR_IN_SECONDS ); } } /** * Trigger the hook to allow other plugins to schedule their recurring actions. * * @return void */ public function run_recurring_scheduler_hook(): void { /** * Fires to allow extensions to verify and ensure their recurring actions are scheduled. * * This action is scheduled to trigger once every 24 hrs for the purpose of having 3rd party plugins verify that * any previously scheduled recurring actions are still scheduled. Because recurring actions could stop getting * rescheduled by default due to excessive failures, database issues, or other interruptions, extensions can use * this hook to check for the existence of their recurring actions and reschedule them if necessary. * * Example usage: * * add_action('action_scheduler_ensure_recurring_actions', function() { * // Check if the recurring action is scheduled, and reschedule if missing. * if ( ! as_has_scheduled_action('my_recurring_action') ) { * as_schedule_recurring_action( time(), HOUR_IN_SECONDS, 'my_recurring_action' ); * } * }); * * @since 3.9.3 */ do_action( 'action_scheduler_ensure_recurring_actions' ); } } woocommerce/action-scheduler/classes/ActionScheduler_Exception.php 0000644 00000000317 15151523435 0021561 0 ustar 00 <?php /** * ActionScheduler Exception Interface. * * Facilitates catching Exceptions unique to Action Scheduler. * * @package ActionScheduler * @since 2.1.0 */ interface ActionScheduler_Exception {} woocommerce/action-scheduler/classes/ActionScheduler_SystemInformation.php 0000644 00000004701 15151523435 0023316 0 ustar 00 <?php /** * Provides information about active and registered instances of Action Scheduler. */ class ActionScheduler_SystemInformation { /** * Returns information about the plugin or theme which contains the current active version * of Action Scheduler. * * If this cannot be determined, or if Action Scheduler is being loaded via some other * method, then it will return an empty array. Otherwise, if populated, the array will * look like the following: * * [ * 'type' => 'plugin', # or 'theme' * 'name' => 'Name', * ] * * @return array */ public static function active_source(): array { $plugins = get_plugins(); $plugin_files = array_keys( $plugins ); foreach ( $plugin_files as $plugin_file ) { $plugin_path = trailingslashit( WP_PLUGIN_DIR ) . dirname( $plugin_file ); $plugin_file = trailingslashit( WP_PLUGIN_DIR ) . $plugin_file; if ( 0 !== strpos( dirname( __DIR__ ), $plugin_path ) ) { continue; } $plugin_data = get_plugin_data( $plugin_file ); if ( ! is_array( $plugin_data ) || empty( $plugin_data['Name'] ) ) { continue; } return array( 'type' => 'plugin', 'name' => $plugin_data['Name'], ); } $themes = (array) search_theme_directories(); foreach ( $themes as $slug => $data ) { $needle = trailingslashit( $data['theme_root'] ) . $slug . '/'; if ( 0 !== strpos( __FILE__, $needle ) ) { continue; } $theme = wp_get_theme( $slug ); if ( ! is_object( $theme ) || ! is_a( $theme, \WP_Theme::class ) ) { continue; } return array( 'type' => 'theme', // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase 'name' => $theme->Name, ); } return array(); } /** * Returns the directory path for the currently active installation of Action Scheduler. * * @return string */ public static function active_source_path(): string { return trailingslashit( dirname( __DIR__ ) ); } /** * Get registered sources. * * It is not always possible to obtain this information. For instance, if earlier versions (<=3.9.0) of * Action Scheduler register themselves first, then the necessary data about registered sources will * not be available. * * @return array<string, string> */ public static function get_sources() { $versions = ActionScheduler_Versions::instance(); return method_exists( $versions, 'get_sources' ) ? $versions->get_sources() : array(); } } woocommerce/action-scheduler/classes/ActionScheduler_OptionLock.php 0000644 00000007754 15151523435 0021720 0 ustar 00 <?php /** * Provide a way to set simple transient locks to block behaviour * for up-to a given duration. * * Class ActionScheduler_OptionLock * * @since 3.0.0 */ class ActionScheduler_OptionLock extends ActionScheduler_Lock { /** * Set a lock using options for a given amount of time (60 seconds by default). * * Using an autoloaded option avoids running database queries or other resource intensive tasks * on frequently triggered hooks, like 'init' or 'shutdown'. * * For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid * calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown', * hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count() * to find the current number of claims in the database. * * @param string $lock_type A string to identify different lock types. * @bool True if lock value has changed, false if not or if set failed. */ public function set( $lock_type ) { global $wpdb; $lock_key = $this->get_key( $lock_type ); $existing_lock_value = $this->get_existing_lock( $lock_type ); $new_lock_value = $this->new_lock_value( $lock_type ); // The lock may not exist yet, or may have been deleted. if ( empty( $existing_lock_value ) ) { return (bool) $wpdb->insert( $wpdb->options, array( 'option_name' => $lock_key, 'option_value' => $new_lock_value, 'autoload' => 'no', ) ); } if ( $this->get_expiration_from( $existing_lock_value ) >= time() ) { return false; } // Otherwise, try to obtain the lock. return (bool) $wpdb->update( $wpdb->options, array( 'option_value' => $new_lock_value ), array( 'option_name' => $lock_key, 'option_value' => $existing_lock_value, ) ); } /** * If a lock is set, return the timestamp it was set to expiry. * * @param string $lock_type A string to identify different lock types. * @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire. */ public function get_expiration( $lock_type ) { return $this->get_expiration_from( $this->get_existing_lock( $lock_type ) ); } /** * Given the lock string, derives the lock expiration timestamp (or false if it cannot be determined). * * @param string $lock_value String containing a timestamp, or pipe-separated combination of unique value and timestamp. * * @return false|int */ private function get_expiration_from( $lock_value ) { $lock_string = explode( '|', $lock_value ); // Old style lock? if ( count( $lock_string ) === 1 && is_numeric( $lock_string[0] ) ) { return (int) $lock_string[0]; } // New style lock? if ( count( $lock_string ) === 2 && is_numeric( $lock_string[1] ) ) { return (int) $lock_string[1]; } return false; } /** * Get the key to use for storing the lock in the transient * * @param string $lock_type A string to identify different lock types. * @return string */ protected function get_key( $lock_type ) { return sprintf( 'action_scheduler_lock_%s', $lock_type ); } /** * Supplies the existing lock value, or an empty string if not set. * * @param string $lock_type A string to identify different lock types. * * @return string */ private function get_existing_lock( $lock_type ) { global $wpdb; // Now grab the existing lock value, if there is one. return (string) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s", $this->get_key( $lock_type ) ) ); } /** * Supplies a lock value consisting of a unique value and the current timestamp, which are separated by a pipe * character. * * Example: (string) "649de012e6b262.09774912|1688068114" * * @param string $lock_type A string to identify different lock types. * * @return string */ private function new_lock_value( $lock_type ) { return uniqid( '', true ) . '|' . ( time() + $this->get_duration( $lock_type ) ); } } woocommerce/action-scheduler/classes/ActionScheduler_DateTime.php 0000644 00000004014 15151523435 0021315 0 ustar 00 <?php /** * ActionScheduler DateTime class. * * This is a custom extension to DateTime that */ class ActionScheduler_DateTime extends DateTime { /** * UTC offset. * * Only used when a timezone is not set. When a timezone string is * used, this will be set to 0. * * @var int */ protected $utcOffset = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase /** * Get the unix timestamp of the current object. * * Missing in PHP 5.2 so just here so it can be supported consistently. * * @return int */ #[\ReturnTypeWillChange] public function getTimestamp() { return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' ); } /** * Set the UTC offset. * * This represents a fixed offset instead of a timezone setting. * * @param string|int $offset UTC offset value. */ public function setUtcOffset( $offset ) { $this->utcOffset = intval( $offset ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } /** * Returns the timezone offset. * * @return int * @link http://php.net/manual/en/datetime.getoffset.php */ #[\ReturnTypeWillChange] public function getOffset() { return $this->utcOffset ? $this->utcOffset : parent::getOffset(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase } /** * Set the TimeZone associated with the DateTime * * @param DateTimeZone $timezone Timezone object. * * @return static * @link http://php.net/manual/en/datetime.settimezone.php */ #[\ReturnTypeWillChange] public function setTimezone( $timezone ) { $this->utcOffset = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase parent::setTimezone( $timezone ); return $this; } /** * Get the timestamp with the WordPress timezone offset added or subtracted. * * @since 3.0.0 * @return int */ public function getOffsetTimestamp() { return $this->getTimestamp() + $this->getOffset(); } } woocommerce/action-scheduler/classes/ActionScheduler_WPCommentCleaner.php 0000644 00000010661 15151523435 0022771 0 ustar 00 <?php /** * Class ActionScheduler_WPCommentCleaner * * @since 3.0.0 */ class ActionScheduler_WPCommentCleaner { /** * Post migration hook used to cleanup the WP comment table. * * @var string */ protected static $cleanup_hook = 'action_scheduler/cleanup_wp_comment_logs'; /** * An instance of the ActionScheduler_wpCommentLogger class to interact with the comments table. * * This instance should only be used as an interface. It should not be initialized. * * @var ActionScheduler_wpCommentLogger */ protected static $wp_comment_logger = null; /** * The key used to store the cached value of whether there are logs in the WP comment table. * * @var string */ protected static $has_logs_option_key = 'as_has_wp_comment_logs'; /** * Initialize the class and attach callbacks. */ public static function init() { if ( empty( self::$wp_comment_logger ) ) { self::$wp_comment_logger = new ActionScheduler_wpCommentLogger(); } add_action( self::$cleanup_hook, array( __CLASS__, 'delete_all_action_comments' ) ); // While there are orphaned logs left in the comments table, we need to attach the callbacks which filter comment counts. add_action( 'pre_get_comments', array( self::$wp_comment_logger, 'filter_comment_queries' ), 10, 1 ); add_action( 'wp_count_comments', array( self::$wp_comment_logger, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs. add_action( 'comment_feed_where', array( self::$wp_comment_logger, 'filter_comment_feed' ), 10, 2 ); // Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen. add_action( 'load-tools_page_action-scheduler', array( __CLASS__, 'register_admin_notice' ) ); add_action( 'load-woocommerce_page_wc-status', array( __CLASS__, 'register_admin_notice' ) ); } /** * Determines if there are log entries in the wp comments table. * * Uses the flag set on migration completion set by @see self::maybe_schedule_cleanup(). * * @return boolean Whether there are scheduled action comments in the comments table. */ public static function has_logs() { return 'yes' === get_option( self::$has_logs_option_key ); } /** * Schedules the WP Post comment table cleanup to run in 6 months if it's not already scheduled. * Attached to the migration complete hook 'action_scheduler/migration_complete'. */ public static function maybe_schedule_cleanup() { $has_logs = 'no'; $args = array( 'type' => ActionScheduler_wpCommentLogger::TYPE, 'number' => 1, 'fields' => 'ids', ); if ( (bool) get_comments( $args ) ) { $has_logs = 'yes'; if ( ! as_next_scheduled_action( self::$cleanup_hook ) ) { as_schedule_single_action( gmdate( 'U' ) + ( 6 * MONTH_IN_SECONDS ), self::$cleanup_hook ); } } update_option( self::$has_logs_option_key, $has_logs, true ); } /** * Delete all action comments from the WP Comments table. */ public static function delete_all_action_comments() { global $wpdb; $wpdb->delete( $wpdb->comments, array( 'comment_type' => ActionScheduler_wpCommentLogger::TYPE, 'comment_agent' => ActionScheduler_wpCommentLogger::AGENT, ) ); update_option( self::$has_logs_option_key, 'no', true ); } /** * Registers admin notices about the orphaned action logs. */ public static function register_admin_notice() { add_action( 'admin_notices', array( __CLASS__, 'print_admin_notice' ) ); } /** * Prints details about the orphaned action logs and includes information on where to learn more. */ public static function print_admin_notice() { $next_cleanup_message = ''; $next_scheduled_cleanup_hook = as_next_scheduled_action( self::$cleanup_hook ); if ( $next_scheduled_cleanup_hook ) { /* translators: %s: date interval */ $next_cleanup_message = sprintf( __( 'This data will be deleted in %s.', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $next_scheduled_cleanup_hook ) ); } $notice = sprintf( /* translators: 1: next cleanup message 2: github issue URL */ __( 'Action Scheduler has migrated data to custom tables; however, orphaned log entries exist in the WordPress Comments table. %1$s <a href="%2$s">Learn more »</a>', 'action-scheduler' ), $next_cleanup_message, 'https://github.com/woocommerce/action-scheduler/issues/368' ); echo '<div class="notice notice-warning"><p>' . wp_kses_post( $notice ) . '</p></div>'; } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_AbstractField.php 0000644 00000005020 15151523435 0024502 0 ustar 00 <?php /** * Abstract CRON expression field * * @author Michael Dowling <mtdowling@gmail.com> */ 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; } } woocommerce/action-scheduler/lib/cron-expression/LICENSE 0000644 00000002112 15151523435 0017225 0 ustar 00 Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com> and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. woocommerce/action-scheduler/lib/cron-expression/CronExpression_DayOfWeekField.php 0000644 00000007521 15151523435 0024565 0 ustar 00 <?php /** * Day of week field. Allows: * / , - ? L # * * Days of the week can be represented as a number 0-7 (0|7 = Sunday) * or as a three letter string: SUN, MON, TUE, WED, THU, FRI, SAT. * * 'L' stands for "last". It allows you to specify constructs such as * "the last Friday" of a given month. * * '#' is allowed for the day-of-week field, and must be followed by a * number between one and five. It allows you to specify constructs such as * "the second Friday" of a given month. * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_DayOfMonthField.php 0000644 00000007014 15151523435 0024754 0 ustar 00 <?php /** * Day of month field. Allows: * , / - ? L W * * 'L' stands for "last" and specifies the last day of the month. * * The 'W' character is used to specify the weekday (Monday-Friday) nearest the * given day. As an example, if you were to specify "15W" as the value for the * day-of-month field, the meaning is: "the nearest weekday to the 15th of the * month". So if the 15th is a Saturday, the trigger will fire on Friday the * 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If * the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you * specify "1W" as the value for day-of-month, and the 1st is a Saturday, the * trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary * of a month's days. The 'W' character can only be specified when the * day-of-month is a single day, not a range or list of days. * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_FieldInterface.php 0000644 00000002162 15151523435 0024643 0 ustar 00 <?php /** * CRON field interface * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } woocommerce/action-scheduler/lib/cron-expression/CronExpression_YearField.php 0000644 00000001651 15151523435 0023645 0 ustar 00 <?php /** * Year field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_FieldFactory.php 0000644 00000003321 15151523435 0024350 0 ustar 00 <?php /** * CRON field factory implementing a flyweight factory * * @author Michael Dowling <mtdowling@gmail.com> * @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]; } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_HoursField.php 0000644 00000002205 15151523435 0024041 0 ustar 00 <?php /** * Hours field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } } woocommerce/action-scheduler/lib/cron-expression/CronExpression.php 0000644 00000026537 15151523435 0021733 0 ustar 00 <?php /** * CRON expression parser that can determine whether or not a CRON expression is * due to run, the next run date and previous run date of a CRON expression. * The determinations made by this class are accurate if checked run once per * minute (seconds are dropped from date time comparisons). * * Schedule parts must map to: * minute [0-59], hour [0-23], day of month, month [1-12|JAN-DEC], day of week * [1-7|MON-SUN], and an optional year. * * @author Michael Dowling <mtdowling@gmail.com> * @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 } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_MonthField.php 0000644 00000002567 15151523435 0024041 0 ustar 00 <?php /** * Month field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } } woocommerce/action-scheduler/lib/cron-expression/CronExpression_MinutesField.php 0000644 00000001371 15151523435 0024370 0 ustar 00 <?php /** * Minutes field. Allows: * , / - * * @author Michael Dowling <mtdowling@gmail.com> */ 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); } } woocommerce/action-scheduler/lib/WP_Async_Request.php 0000644 00000007206 15151523435 0016777 0 ustar 00 <?php /** * WP Async Request * * @package WP-Background-Processing */ /* Library URI: https://github.com/deliciousbrains/wp-background-processing/blob/fbbc56f2480910d7959972ec9ec0819a13c6150a/classes/wp-async-request.php Author: Delicious Brains Inc. Author URI: https://deliciousbrains.com/ License: GNU General Public License v2.0 License URI: https://github.com/deliciousbrains/wp-background-processing/commit/126d7945dd3d39f39cb6488ca08fe1fb66cb351a */ if ( ! class_exists( 'WP_Async_Request' ) ) { /** * Abstract WP_Async_Request class. * * @abstract */ abstract class WP_Async_Request { /** * Prefix * * (default value: 'wp') * * @var string */ protected $prefix = 'wp'; /** * Action * * (default value: 'async_request') * * @var string */ protected $action = 'async_request'; /** * Identifier * * @var mixed */ protected $identifier; /** * Data * * (default value: array()) * * @var array */ protected $data = array(); /** * Initiate new async request */ public function __construct() { $this->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(); } } woocommerce/action-scheduler/action-scheduler.php 0000644 00000005717 15151523435 0016274 0 ustar 00 <?php /** * Plugin Name: Action Scheduler * Plugin URI: https://actionscheduler.org * Description: A robust scheduling library for use in WordPress plugins. * Author: Automattic * Author URI: https://automattic.com/ * Version: 3.9.3 * License: GPLv3 * Requires at least: 6.5 * Tested up to: 6.8 * Requires PHP: 7.2 * * Copyright 2019 Automattic, Inc. (https://automattic.com/contact/) * * 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 <https://www.gnu.org/licenses/>. * * @package ActionScheduler */ if ( ! function_exists( 'action_scheduler_register_3_dot_9_dot_3' ) && function_exists( 'add_action' ) ) { // WRCS: DEFINED_VERSION. if ( ! class_exists( 'ActionScheduler_Versions', false ) ) { require_once __DIR__ . '/classes/ActionScheduler_Versions.php'; add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 ); } add_action( 'plugins_loaded', 'action_scheduler_register_3_dot_9_dot_3', 0, 0 ); // WRCS: DEFINED_VERSION. // phpcs:disable Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace /** * Registers this version of Action Scheduler. */ function action_scheduler_register_3_dot_9_dot_3() { // WRCS: DEFINED_VERSION. $versions = ActionScheduler_Versions::instance(); $versions->register( '3.9.3', 'action_scheduler_initialize_3_dot_9_dot_3' ); // WRCS: DEFINED_VERSION. } // phpcs:disable Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace /** * Initializes this version of Action Scheduler. */ function action_scheduler_initialize_3_dot_9_dot_3() { // WRCS: DEFINED_VERSION. // A final safety check is required even here, because historic versions of Action Scheduler // followed a different pattern (in some unusual cases, we could reach this point and the // ActionScheduler class is already defined—so we need to guard against that). if ( ! class_exists( 'ActionScheduler', false ) ) { require_once __DIR__ . '/classes/abstracts/ActionScheduler.php'; ActionScheduler::init( __FILE__ ); } } // Support usage in themes - load this version if no plugin has loaded a version yet. if ( did_action( 'plugins_loaded' ) && ! doing_action( 'plugins_loaded' ) && ! class_exists( 'ActionScheduler', false ) ) { action_scheduler_initialize_3_dot_9_dot_3(); // WRCS: DEFINED_VERSION. do_action( 'action_scheduler_pre_theme_init' ); ActionScheduler_Versions::initialize_latest_version(); } } woocommerce/action-scheduler/license.txt 0000644 00000104515 15151523435 0014511 0 ustar 00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 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. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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 <https://www.gnu.org/licenses/>. 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: <program> Copyright (C) <year> <name of author> 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 <https://www.gnu.org/licenses/>. 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 <https://www.gnu.org/licenses/why-not-lgpl.html>. woocommerce/action-scheduler/functions.php 0000644 00000046430 15151523435 0015050 0 ustar 00 <?php /** * General API functions for scheduling actions * * @package ActionScheduler. */ /** * Enqueue an action to run one time, as soon as possible * * @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. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_enqueue_async_action( $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } /** * Provides an opportunity to short-circuit the default process for enqueuing async * 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 enqueued action ID (enqueued using some alternative process) or else * zero. * * @param int|null $pre_option The value to return instead of the option value. * @param string $hook Action hook. * @param array $args Action arguments. * @param string $group Action group. * @param int $priority Action priority. * @param bool $unique Unique action. */ $pre = apply_filters( 'pre_as_enqueue_async_action', null, $hook, $args, $group, $priority, $unique ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'async', 'hook' => $hook, 'arguments' => $args, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * 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. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_schedule_single_action( $timestamp, $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { 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. * @param int $priorities Action priority. * @param bool $unique Unique action. */ $pre = apply_filters( 'pre_as_schedule_single_action', null, $timestamp, $hook, $args, $group, $priority, $unique ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'single', 'hook' => $hook, 'arguments' => $args, 'when' => $timestamp, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * 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. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { if ( ! ActionScheduler::is_initialized( __FUNCTION__ ) ) { return 0; } $interval = (int) $interval_in_seconds; // We expect an integer and allow it to be passed using float and string types, but otherwise // should reject unexpected values. // phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison if ( ! is_numeric( $interval_in_seconds ) || $interval_in_seconds != $interval ) { _doing_it_wrong( __METHOD__, sprintf( /* translators: 1: provided value 2: provided type. */ esc_html__( 'An integer was expected but "%1$s" (%2$s) was received.', 'action-scheduler' ), esc_html( $interval_in_seconds ), esc_html( gettype( $interval_in_seconds ) ) ), '3.6.0' ); 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. * @param int $priority Action priority. * @param bool $unique Unique action. */ $pre = apply_filters( 'pre_as_schedule_recurring_action', null, $timestamp, $interval_in_seconds, $hook, $args, $group, $priority, $unique ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'recurring', 'hook' => $hook, 'arguments' => $args, 'when' => $timestamp, 'pattern' => $interval_in_seconds, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * 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. It will not be scheduled if another pending or running action has the same hook and group parameters. * @param int $priority Lower values take precedence over higher values. Defaults to 10, with acceptable values falling in the range 0-255. * * @return int The action ID. Zero if there was an error scheduling the action. */ function as_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '', $unique = false, $priority = 10 ) { 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. * @param int $priority Action priority. * @param bool $unique Unique action. */ $pre = apply_filters( 'pre_as_schedule_cron_action', null, $timestamp, $schedule, $hook, $args, $group, $priority, $unique ); if ( null !== $pre ) { return is_int( $pre ) ? $pre : 0; } return ActionScheduler::factory()->create( array( 'type' => 'cron', 'hook' => $hook, 'arguments' => $args, 'when' => $timestamp, 'pattern' => $schedule, 'group' => $group, 'unique' => $unique, 'priority' => $priority, ) ); } /** * 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: %1$s is the name of the hook to be cancelled, %2$s is the exception message. */ __( 'Caught exception while cancelling action "%1$s": %2$s', 'action-scheduler' ), $hook, $exception->getMessage() ) ); $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; } /** * Check if a specific feature is supported by the current version of Action Scheduler. * * @since 3.9.3 * * @param string $feature The feature to check support for. * * @return bool True if the feature is supported, false otherwise. */ function as_supports( string $feature ): bool { $supported_features = array( 'ensure_recurring_actions_hook' ); return in_array( $feature, $supported_features, true ); } woocommerce/action-scheduler/deprecated/ActionScheduler_Schedule_Deprecated.php 0000644 00000001500 15151523435 0024135 0 ustar 00 <?php /** * Class ActionScheduler_Abstract_Schedule */ abstract class ActionScheduler_Schedule_Deprecated implements ActionScheduler_Schedule { /** * Get the date & time this schedule was created to run, or calculate when it should be run * after a given date & time. * * @param DateTime $after DateTime to calculate against. * * @return DateTime|null */ public function next( ?DateTime $after = null ) { if ( empty( $after ) ) { $return_value = $this->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; } } woocommerce/action-scheduler/deprecated/ActionScheduler_Store_Deprecated.php 0000644 00000002043 15151523435 0023500 0 ustar 00 <?php /** * Class ActionScheduler_Store_Deprecated * * @codeCoverageIgnore */ abstract class ActionScheduler_Store_Deprecated { /** * Mark an action that failed to fetch correctly as failed. * * @since 2.2.6 * * @param int $action_id The ID of the action. */ public function mark_failed_fetch_action( $action_id ) { _deprecated_function( __METHOD__, '3.0.0', 'ActionScheduler_Store::mark_failure()' ); self::$store->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(); } } woocommerce/action-scheduler/deprecated/ActionScheduler_Abstract_QueueRunner_Deprecated.php 0000644 00000001524 15151523435 0026510 0 ustar 00 <?php /** * Abstract class with common Queue Cleaner functionality. */ abstract class ActionScheduler_Abstract_QueueRunner_Deprecated { /** * Get the maximum number of seconds a batch can run for. * * @deprecated 2.1.1 * @return int The number of seconds. */ protected function get_maximum_execution_time() { _deprecated_function( __METHOD__, '2.1.1', 'ActionScheduler_Abstract_QueueRunner::get_time_limit()' ); $maximum_execution_time = 30; // Apply deprecated filter. if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) { _deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' ); $maximum_execution_time = apply_filters( 'action_scheduler_maximum_execution_time', $maximum_execution_time ); } return absint( $maximum_execution_time ); } } woocommerce/action-scheduler/deprecated/ActionScheduler_AdminView_Deprecated.php 0000644 00000012532 15151523435 0024273 0 ustar 00 <?php /** * Class ActionScheduler_AdminView_Deprecated * * Store deprecated public functions previously found in the ActionScheduler_AdminView class. * Keeps them out of the way of the main class. * * @codeCoverageIgnore */ class ActionScheduler_AdminView_Deprecated { /** * Adjust parameters for custom post type. * * @param array $args Args. */ public function action_scheduler_post_type_args( $args ) { _deprecated_function( __METHOD__, '2.0.0' ); return $args; } /** * Customise the post status related views displayed on the Scheduled Actions administration screen. * * @param array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen. * @return array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen. */ public function list_table_views( $views ) { _deprecated_function( __METHOD__, '2.0.0' ); return $views; } /** * Do not include the "Edit" action for the Scheduled Actions administration screen. * * Hooked to the 'bulk_actions-edit-action-scheduler' filter. * * @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. * @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. */ public function bulk_actions( $actions ) { _deprecated_function( __METHOD__, '2.0.0' ); return $actions; } /** * Completely customer the columns displayed on the Scheduled Actions administration screen. * * Because we can't filter the content of the default title and date columns, we need to recreate our own * custom columns for displaying those post fields. For the column content, @see self::list_table_column_content(). * * @param array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen. * @return array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen. */ public function list_table_columns( $columns ) { _deprecated_function( __METHOD__, '2.0.0' ); return $columns; } /** * Make our custom title & date columns use defaulting title & date sorting. * * @param array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen. * @return array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen. */ public static function list_table_sortable_columns( $columns ) { _deprecated_function( __METHOD__, '2.0.0' ); return $columns; } /** * Print the content for our custom columns. * * @param string $column_name The key for the column for which we should output our content. * @param int $post_id The ID of the 'scheduled-action' post for which this row relates. */ public static function list_table_column_content( $column_name, $post_id ) { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Hide the inline "Edit" action for all 'scheduled-action' posts. * * Hooked to the 'post_row_actions' filter. * * @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. * @param WP_Post $post The 'scheduled-action' post object. * @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. */ public static function row_actions( $actions, $post ) { _deprecated_function( __METHOD__, '2.0.0' ); return $actions; } /** * Run an action when triggered from the Action Scheduler administration screen. * * @codeCoverageIgnore */ public static function maybe_execute_action() { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Convert an interval of seconds into a two part human friendly string. * * The WordPress human_time_diff() function only calculates the time difference to one degree, meaning * even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step * further to display two degrees of accuracy. * * Based on Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/ * * @return void */ public static function admin_notices() { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Filter search queries to allow searching by Claim ID (i.e. post_password). * * @param string $orderby MySQL orderby string. * @param WP_Query $query Instance of a WP_Query object. * @return void */ public function custom_orderby( $orderby, $query ) { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Filter search queries to allow searching by Claim ID (i.e. post_password). * * @param string $search MySQL search string. * @param WP_Query $query Instance of a WP_Query object. * @return void */ public function search_post_password( $search, $query ) { _deprecated_function( __METHOD__, '2.0.0' ); } /** * Change messages when a scheduled action is updated. * * @param array $messages Messages. * @return array */ public function post_updated_messages( $messages ) { _deprecated_function( __METHOD__, '2.0.0' ); return $messages; } } woocommerce/action-scheduler/deprecated/functions.php 0000644 00000012231 15151523435 0017140 0 ustar 00 <?php /** * Deprecated API functions for scheduling actions * * Functions with the wc prefix were deprecated to avoid confusion with * Action Scheduler being included in WooCommerce core, and it providing * a different set of APIs for working with the action queue. * * @package ActionScheduler */ /** * 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. * * @return string The job ID */ function wc_schedule_single_action( $timestamp, $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_single_action()' ); return as_schedule_single_action( $timestamp, $hook, $args, $group ); } /** * 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. * * @deprecated 2.1.0 * * @return string The job ID */ function wc_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_recurring_action()' ); return as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group ); } /** * Schedule an action that recurs on a cron-like schedule. * * @param int $timestamp The schedule will start on or after this time. * @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. * * @deprecated 2.1.0 * * @return string The job ID */ function wc_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_cron_action()' ); return as_schedule_cron_action( $timestamp, $schedule, $hook, $args, $group ); } /** * Cancel the next occurrence of a job. * * @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 Action's group. * * @deprecated 2.1.0 */ function wc_unschedule_action( $hook, $args = array(), $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_unschedule_action()' ); as_unschedule_action( $hook, $args, $group ); } /** * Get next scheduled action. * * @param string $hook Action's hook. * @param array $args Action's args. * @param string $group Action's group. * * @deprecated 2.1.0 * * @return int|bool The timestamp for the next occurrence, or false if nothing was found */ function wc_next_scheduled_action( $hook, $args = null, $group = '' ) { _deprecated_function( __FUNCTION__, '2.1.0', 'as_next_scheduled_action()' ); return as_next_scheduled_action( $hook, $args, $group ); } /** * 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', 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 ); } composer/LICENSE 0000644 00000002056 15151523435 0007407 0 ustar 00 Copyright (c) Nils Adermann, Jordi Boggiano Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. composer/autoload_files.php 0000644 00000001002 15151523435 0012073 0 ustar 00 <?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'da5f6548f070d3d306f90eee42dd5de6' => $vendorDir . '/donatj/phpuseragentparser/src/UserAgentParser.php', 'bcb90d312f16e4ff52a76c5aa3f98ae0' => $vendorDir . '/cmb2/cmb2/init.php', '65bb6728e4ea5a6bfba27700e81f7a00' => $baseDir . '/includes/template-tags.php', '49628becc29116377284b725833a0b5a' => $vendorDir . '/woocommerce/action-scheduler/action-scheduler.php', ); composer/ClassLoader.php 0000644 00000037304 15151523435 0011313 0 ustar 00 <?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { /** @var ?string */ private $vendorDir; // PSR-4 /** * @var array[] * @psalm-var array<string, array<string, int>> */ private $prefixLengthsPsr4 = array(); /** * @var array[] * @psalm-var array<string, array<int, string>> */ private $prefixDirsPsr4 = array(); /** * @var array[] * @psalm-var array<string, string> */ private $fallbackDirsPsr4 = array(); // PSR-0 /** * @var array[] * @psalm-var array<string, array<string, string[]>> */ private $prefixesPsr0 = array(); /** * @var array[] * @psalm-var array<string, string> */ private $fallbackDirsPsr0 = array(); /** @var bool */ private $useIncludePath = false; /** * @var string[] * @psalm-var array<string, string> */ private $classMap = array(); /** @var bool */ private $classMapAuthoritative = false; /** * @var bool[] * @psalm-var array<string, bool> */ private $missingClasses = array(); /** @var ?string */ private $apcuPrefix; /** * @var self[] */ private static $registeredLoaders = array(); /** * @param ?string $vendorDir */ public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; } /** * @return string[] */ public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } /** * @return array[] * @psalm-return array<string, array<int, string>> */ public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } /** * @return array[] * @psalm-return array<string, string> */ public function getFallbackDirs() { return $this->fallbackDirsPsr0; } /** * @return array[] * @psalm-return array<string, string> */ public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } /** * @return string[] Array of classname => path * @psalm-return array<string, string> */ public function getClassMap() { return $this->classMap; } /** * @param string[] $classMap Class to filename map * @psalm-param array<string, string> $classMap * * @return void */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param string[]|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories * * @return void */ public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param string[]|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException * * @return void */ public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param string[]|string $paths The PSR-0 base directories * * @return void */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param string[]|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException * * @return void */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath * * @return void */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative * * @return void */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix * * @return void */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not * * @return void */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); if (null === $this->vendorDir) { return; } if ($prepend) { self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; } else { unset(self::$registeredLoaders[$this->vendorDir]); self::$registeredLoaders[$this->vendorDir] = $this; } } /** * Unregisters this instance as an autoloader. * * @return void */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); if (null !== $this->vendorDir) { unset(self::$registeredLoaders[$this->vendorDir]); } } /** * Loads the given class or interface. * * @param string $class The name of the class * @return true|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { includeFile($file); return true; } return null; } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } /** * Returns the currently registered loaders indexed by their corresponding vendor directories. * * @return self[] */ public static function getRegisteredLoaders() { return self::$registeredLoaders; } /** * @param string $class * @param string $ext * @return string|false */ private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. * * @param string $file * @return void * @private */ function includeFile($file) { include $file; } composer/autoload_static.php 0000644 00000120536 15151523435 0012276 0 ustar 00 <?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitb6b9cb56b2244b2950baac041c453348 { public static $files = array ( 'da5f6548f070d3d306f90eee42dd5de6' => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgentParser.php', 'bcb90d312f16e4ff52a76c5aa3f98ae0' => __DIR__ . '/..' . '/cmb2/cmb2/init.php', '65bb6728e4ea5a6bfba27700e81f7a00' => __DIR__ . '/../..' . '/includes/template-tags.php', '49628becc29116377284b725833a0b5a' => __DIR__ . '/..' . '/woocommerce/action-scheduler/action-scheduler.php', ); public static $prefixLengthsPsr4 = array ( 'd' => array ( 'donatj\\UserAgent\\' => 17, ), 'W' => array ( 'WPMedia\\Mixpanel\\' => 17, ), ); public static $prefixDirsPsr4 = array ( 'donatj\\UserAgent\\' => array ( 0 => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgent', ), 'WPMedia\\Mixpanel\\' => array ( 0 => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src', ), ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', 'RankMath\\ACF\\ACF' => __DIR__ . '/../..' . '/includes/modules/acf/class-acf.php', 'RankMath\\Admin\\Admin' => __DIR__ . '/../..' . '/includes/admin/class-admin.php', 'RankMath\\Admin\\Admin_Breadcrumbs' => __DIR__ . '/../..' . '/includes/admin/class-admin-breadcrumbs.php', 'RankMath\\Admin\\Admin_Dashboard_Nav' => __DIR__ . '/../..' . '/includes/admin/class-admin-dashboard-nav.php', 'RankMath\\Admin\\Admin_Header' => __DIR__ . '/../..' . '/includes/admin/class-admin-header.php', 'RankMath\\Admin\\Admin_Helper' => __DIR__ . '/../..' . '/includes/admin/class-admin-helper.php', 'RankMath\\Admin\\Admin_Init' => __DIR__ . '/../..' . '/includes/admin/class-admin-init.php', 'RankMath\\Admin\\Admin_Menu' => __DIR__ . '/../..' . '/includes/admin/class-admin-menu.php', 'RankMath\\Admin\\Api' => __DIR__ . '/../..' . '/includes/admin/class-api.php', 'RankMath\\Admin\\Ask_Review' => __DIR__ . '/../..' . '/includes/admin/class-ask-review.php', 'RankMath\\Admin\\Assets' => __DIR__ . '/../..' . '/includes/admin/class-assets.php', 'RankMath\\Admin\\Bulk_Actions' => __DIR__ . '/../..' . '/includes/admin/class-bulk-actions.php', 'RankMath\\Admin\\CMB2_Fields' => __DIR__ . '/../..' . '/includes/admin/class-cmb2-fields.php', 'RankMath\\Admin\\CMB2_Options' => __DIR__ . '/../..' . '/includes/admin/class-cmb2-options.php', 'RankMath\\Admin\\Database\\Clauses' => __DIR__ . '/../..' . '/includes/admin/database/class-clauses.php', 'RankMath\\Admin\\Database\\Database' => __DIR__ . '/../..' . '/includes/admin/database/class-database.php', 'RankMath\\Admin\\Database\\Escape' => __DIR__ . '/../..' . '/includes/admin/database/class-escape.php', 'RankMath\\Admin\\Database\\GroupBy' => __DIR__ . '/../..' . '/includes/admin/database/class-groupby.php', 'RankMath\\Admin\\Database\\Joins' => __DIR__ . '/../..' . '/includes/admin/database/class-joins.php', 'RankMath\\Admin\\Database\\OrderBy' => __DIR__ . '/../..' . '/includes/admin/database/class-orderby.php', 'RankMath\\Admin\\Database\\Query_Builder' => __DIR__ . '/../..' . '/includes/admin/database/class-query-builder.php', 'RankMath\\Admin\\Database\\Select' => __DIR__ . '/../..' . '/includes/admin/database/class-select.php', 'RankMath\\Admin\\Database\\Translate' => __DIR__ . '/../..' . '/includes/admin/database/class-translate.php', 'RankMath\\Admin\\Database\\Where' => __DIR__ . '/../..' . '/includes/admin/database/class-where.php', 'RankMath\\Admin\\Import_Export' => __DIR__ . '/../..' . '/includes/admin/class-import-export.php', 'RankMath\\Admin\\Importers\\AIOSEO' => __DIR__ . '/../..' . '/includes/admin/importers/class-aioseo.php', 'RankMath\\Admin\\Importers\\AIO_Rich_Snippet' => __DIR__ . '/../..' . '/includes/admin/importers/class-aio-rich-snippet.php', 'RankMath\\Admin\\Importers\\Detector' => __DIR__ . '/../..' . '/includes/admin/importers/class-detector.php', 'RankMath\\Admin\\Importers\\Plugin_Importer' => __DIR__ . '/../..' . '/includes/admin/importers/class-plugin-importer.php', 'RankMath\\Admin\\Importers\\Redirections' => __DIR__ . '/../..' . '/includes/admin/importers/class-redirections.php', 'RankMath\\Admin\\Importers\\SEOPress' => __DIR__ . '/../..' . '/includes/admin/importers/class-seopress.php', 'RankMath\\Admin\\Importers\\Status' => __DIR__ . '/../..' . '/includes/admin/importers/class-status.php', 'RankMath\\Admin\\Importers\\WP_Schema_Pro' => __DIR__ . '/../..' . '/includes/admin/importers/class-wp-schema-pro.php', 'RankMath\\Admin\\Importers\\Yoast' => __DIR__ . '/../..' . '/includes/admin/importers/class-yoast.php', 'RankMath\\Admin\\List_Table' => __DIR__ . '/../..' . '/includes/admin/class-list-table.php', 'RankMath\\Admin\\Lock_Modified_Date' => __DIR__ . '/../..' . '/includes/admin/class-lock-modified-date.php', 'RankMath\\Admin\\Metabox\\IScreen' => __DIR__ . '/../..' . '/includes/admin/metabox/interface-screen.php', 'RankMath\\Admin\\Metabox\\Metabox' => __DIR__ . '/../..' . '/includes/admin/metabox/class-metabox.php', 'RankMath\\Admin\\Metabox\\Post_Screen' => __DIR__ . '/../..' . '/includes/admin/metabox/class-post-screen.php', 'RankMath\\Admin\\Metabox\\Screen' => __DIR__ . '/../..' . '/includes/admin/metabox/class-screen.php', 'RankMath\\Admin\\Metabox\\Taxonomy_Screen' => __DIR__ . '/../..' . '/includes/admin/metabox/class-taxonomy-screen.php', 'RankMath\\Admin\\Metabox\\User_Screen' => __DIR__ . '/../..' . '/includes/admin/metabox/class-user-screen.php', 'RankMath\\Admin\\Notices' => __DIR__ . '/../..' . '/includes/admin/class-notices.php', 'RankMath\\Admin\\Notifications\\Notification' => __DIR__ . '/../..' . '/includes/admin/notifications/class-notification.php', 'RankMath\\Admin\\Notifications\\Notification_Center' => __DIR__ . '/../..' . '/includes/admin/notifications/class-notification-center.php', 'RankMath\\Admin\\Option_Center' => __DIR__ . '/../..' . '/includes/admin/class-option-center.php', 'RankMath\\Admin\\Options' => __DIR__ . '/../..' . '/includes/admin/class-options.php', 'RankMath\\Admin\\Page' => __DIR__ . '/../..' . '/includes/admin/class-page.php', 'RankMath\\Admin\\Post_Columns' => __DIR__ . '/../..' . '/includes/admin/class-post-columns.php', 'RankMath\\Admin\\Post_Filters' => __DIR__ . '/../..' . '/includes/admin/class-post-filters.php', 'RankMath\\Admin\\Pro_Notice' => __DIR__ . '/../..' . '/includes/admin/class-pro-notice.php', 'RankMath\\Admin\\Register_Options_Page' => __DIR__ . '/../..' . '/includes/admin/class-register-options-page.php', 'RankMath\\Admin\\Registration' => __DIR__ . '/../..' . '/includes/admin/class-registration.php', 'RankMath\\Admin\\Sanitize_Settings' => __DIR__ . '/../..' . '/includes/admin/class-sanitize-settings.php', 'RankMath\\Admin\\Setup_Wizard' => __DIR__ . '/../..' . '/includes/admin/class-setup-wizard.php', 'RankMath\\Admin\\Watcher' => __DIR__ . '/../..' . '/includes/admin/watcher/class-watcher.php', 'RankMath\\Admin_Bar_Menu' => __DIR__ . '/../..' . '/includes/admin/class-admin-bar-menu.php', 'RankMath\\Analytics\\AJAX' => __DIR__ . '/../..' . '/includes/modules/analytics/class-ajax.php', 'RankMath\\Analytics\\Analytics' => __DIR__ . '/../..' . '/includes/modules/analytics/class-analytics.php', 'RankMath\\Analytics\\Analytics_Common' => __DIR__ . '/../..' . '/includes/modules/analytics/class-analytics-common.php', 'RankMath\\Analytics\\Analytics_Stats' => __DIR__ . '/../..' . '/includes/modules/analytics/class-analytics-stats.php', 'RankMath\\Analytics\\DB' => __DIR__ . '/../..' . '/includes/modules/analytics/class-db.php', 'RankMath\\Analytics\\Email_Reports' => __DIR__ . '/../..' . '/includes/modules/analytics/class-email-reports.php', 'RankMath\\Analytics\\GTag' => __DIR__ . '/../..' . '/includes/modules/analytics/class-gtag.php', 'RankMath\\Analytics\\Keywords' => __DIR__ . '/../..' . '/includes/modules/analytics/class-keywords.php', 'RankMath\\Analytics\\Objects' => __DIR__ . '/../..' . '/includes/modules/analytics/class-objects.php', 'RankMath\\Analytics\\Posts' => __DIR__ . '/../..' . '/includes/modules/analytics/class-posts.php', 'RankMath\\Analytics\\Rest' => __DIR__ . '/../..' . '/includes/modules/analytics/rest/class-rest.php', 'RankMath\\Analytics\\Stats' => __DIR__ . '/../..' . '/includes/modules/analytics/class-stats.php', 'RankMath\\Analytics\\Summary' => __DIR__ . '/../..' . '/includes/modules/analytics/class-summary.php', 'RankMath\\Analytics\\Url_Inspection' => __DIR__ . '/../..' . '/includes/modules/analytics/class-url-inspection.php', 'RankMath\\Analytics\\Watcher' => __DIR__ . '/../..' . '/includes/modules/analytics/class-watcher.php', 'RankMath\\Analytics\\Workflow\\Base' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-base.php', 'RankMath\\Analytics\\Workflow\\Console' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-console.php', 'RankMath\\Analytics\\Workflow\\Inspections' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-inspections.php', 'RankMath\\Analytics\\Workflow\\Jobs' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-jobs.php', 'RankMath\\Analytics\\Workflow\\OAuth' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-oauth.php', 'RankMath\\Analytics\\Workflow\\Objects' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-objects.php', 'RankMath\\Analytics\\Workflow\\Workflow' => __DIR__ . '/../..' . '/includes/modules/analytics/workflows/class-workflow.php', 'RankMath\\Auto_Updater' => __DIR__ . '/../..' . '/includes/class-auto-updater.php', 'RankMath\\Beta_Optin' => __DIR__ . '/../..' . '/includes/modules/version-control/class-beta-optin.php', 'RankMath\\BuddyPress\\Admin' => __DIR__ . '/../..' . '/includes/modules/buddypress/class-admin.php', 'RankMath\\BuddyPress\\BuddyPress' => __DIR__ . '/../..' . '/includes/modules/buddypress/class-buddypress.php', 'RankMath\\CLI\\Commands' => __DIR__ . '/../..' . '/includes/cli/class-commands.php', 'RankMath\\CMB2' => __DIR__ . '/../..' . '/includes/class-cmb2.php', 'RankMath\\Common' => __DIR__ . '/../..' . '/includes/class-common.php', 'RankMath\\Compatibility' => __DIR__ . '/../..' . '/includes/class-compatibility.php', 'RankMath\\ContentAI\\Admin' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-admin.php', 'RankMath\\ContentAI\\Assets' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-assets.php', 'RankMath\\ContentAI\\Block_Command' => __DIR__ . '/../..' . '/includes/modules/content-ai/blocks/command/class-block-command.php', 'RankMath\\ContentAI\\Bulk_Actions' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-bulk-actions.php', 'RankMath\\ContentAI\\Bulk_Edit_SEO_Meta' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-bulk-edit-seo-meta.php', 'RankMath\\ContentAI\\Bulk_Image_Alt' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-bulk-image-alt.php', 'RankMath\\ContentAI\\Content_AI' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-content-ai.php', 'RankMath\\ContentAI\\Content_AI_Page' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-content-ai-page.php', 'RankMath\\ContentAI\\Event_Scheduler' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-event-scheduler.php', 'RankMath\\ContentAI\\Rest' => __DIR__ . '/../..' . '/includes/modules/content-ai/class-rest.php', 'RankMath\\Dashboard_Widget' => __DIR__ . '/../..' . '/includes/admin/class-dashboard-widget.php', 'RankMath\\Data_Encryption' => __DIR__ . '/../..' . '/includes/class-data-encryption.php', 'RankMath\\Defaults' => __DIR__ . '/../..' . '/includes/class-defaults.php', 'RankMath\\Divi\\Divi' => __DIR__ . '/../..' . '/includes/3rdparty/divi/class-divi.php', 'RankMath\\Divi\\Divi_Admin' => __DIR__ . '/../..' . '/includes/3rdparty/divi/class-divi-admin.php', 'RankMath\\Elementor\\Elementor' => __DIR__ . '/../..' . '/includes/3rdparty/elementor/class-elementor.php', 'RankMath\\Frontend\\Breadcrumbs' => __DIR__ . '/../..' . '/includes/frontend/class-breadcrumbs.php', 'RankMath\\Frontend\\Comments' => __DIR__ . '/../..' . '/includes/frontend/class-comments.php', 'RankMath\\Frontend\\Frontend' => __DIR__ . '/../..' . '/includes/frontend/class-frontend.php', 'RankMath\\Frontend\\Head' => __DIR__ . '/../..' . '/includes/frontend/class-head.php', 'RankMath\\Frontend\\Link_Attributes' => __DIR__ . '/../..' . '/includes/frontend/class-link-attributes.php', 'RankMath\\Frontend\\Redirection' => __DIR__ . '/../..' . '/includes/frontend/class-redirection.php', 'RankMath\\Frontend\\Shortcodes' => __DIR__ . '/../..' . '/includes/frontend/class-shortcodes.php', 'RankMath\\Frontend_SEO_Score' => __DIR__ . '/../..' . '/includes/class-frontend-seo-score.php', 'RankMath\\Google\\Analytics' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-analytics.php', 'RankMath\\Google\\Api' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-api.php', 'RankMath\\Google\\Authentication' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-authentication.php', 'RankMath\\Google\\Console' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-console.php', 'RankMath\\Google\\Permissions' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-permissions.php', 'RankMath\\Google\\Request' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-request.php', 'RankMath\\Google\\Url_Inspection' => __DIR__ . '/../..' . '/includes/modules/analytics/google/class-url-inspection.php', 'RankMath\\Helper' => __DIR__ . '/../..' . '/includes/class-helper.php', 'RankMath\\Helpers\\Analytics' => __DIR__ . '/../..' . '/includes/helpers/class-analytics.php', 'RankMath\\Helpers\\Api' => __DIR__ . '/../..' . '/includes/helpers/class-api.php', 'RankMath\\Helpers\\Arr' => __DIR__ . '/../..' . '/includes/helpers/class-arr.php', 'RankMath\\Helpers\\Attachment' => __DIR__ . '/../..' . '/includes/helpers/class-attachment.php', 'RankMath\\Helpers\\Choices' => __DIR__ . '/../..' . '/includes/helpers/class-choices.php', 'RankMath\\Helpers\\Conditional' => __DIR__ . '/../..' . '/includes/helpers/class-conditional.php', 'RankMath\\Helpers\\Content_AI' => __DIR__ . '/../..' . '/includes/helpers/class-content-ai.php', 'RankMath\\Helpers\\DB' => __DIR__ . '/../..' . '/includes/helpers/class-db.php', 'RankMath\\Helpers\\Editor' => __DIR__ . '/../..' . '/includes/helpers/class-editor.php', 'RankMath\\Helpers\\HTML' => __DIR__ . '/../..' . '/includes/helpers/class-html.php', 'RankMath\\Helpers\\Locale' => __DIR__ . '/../..' . '/includes/helpers/class-locale.php', 'RankMath\\Helpers\\Options' => __DIR__ . '/../..' . '/includes/helpers/class-options.php', 'RankMath\\Helpers\\Param' => __DIR__ . '/../..' . '/includes/helpers/class-param.php', 'RankMath\\Helpers\\Post_Type' => __DIR__ . '/../..' . '/includes/helpers/class-post-type.php', 'RankMath\\Helpers\\Schedule' => __DIR__ . '/../..' . '/includes/helpers/class-schedule.php', 'RankMath\\Helpers\\Schema' => __DIR__ . '/../..' . '/includes/helpers/class-schema.php', 'RankMath\\Helpers\\Security' => __DIR__ . '/../..' . '/includes/helpers/class-security.php', 'RankMath\\Helpers\\Sitepress' => __DIR__ . '/../..' . '/includes/helpers/class-sitepress.php', 'RankMath\\Helpers\\Str' => __DIR__ . '/../..' . '/includes/helpers/class-str.php', 'RankMath\\Helpers\\Taxonomy' => __DIR__ . '/../..' . '/includes/helpers/class-taxonomy.php', 'RankMath\\Helpers\\Url' => __DIR__ . '/../..' . '/includes/helpers/class-url.php', 'RankMath\\Helpers\\WordPress' => __DIR__ . '/../..' . '/includes/helpers/class-wordpress.php', 'RankMath\\Image_Seo\\Add_Attributes' => __DIR__ . '/../..' . '/includes/modules/image-seo/class-add-attributes.php', 'RankMath\\Image_Seo\\Admin' => __DIR__ . '/../..' . '/includes/modules/image-seo/class-admin.php', 'RankMath\\Image_Seo\\Image_Seo' => __DIR__ . '/../..' . '/includes/modules/image-seo/class-image-seo.php', 'RankMath\\Installer' => __DIR__ . '/../..' . '/includes/class-installer.php', 'RankMath\\Instant_Indexing\\Api' => __DIR__ . '/../..' . '/includes/modules/instant-indexing/class-api.php', 'RankMath\\Instant_Indexing\\Instant_Indexing' => __DIR__ . '/../..' . '/includes/modules/instant-indexing/class-instant-indexing.php', 'RankMath\\Instant_Indexing\\Rest' => __DIR__ . '/../..' . '/includes/modules/instant-indexing/class-rest.php', 'RankMath\\Json_Manager' => __DIR__ . '/../..' . '/includes/class-json-manager.php', 'RankMath\\KB' => __DIR__ . '/../..' . '/includes/class-kb.php', 'RankMath\\LLMS\\LLMS_Txt' => __DIR__ . '/../..' . '/includes/modules/llms/class-llms-txt.php', 'RankMath\\Links\\ContentProcessor' => __DIR__ . '/../..' . '/includes/modules/links/class-contentprocessor.php', 'RankMath\\Links\\Link' => __DIR__ . '/../..' . '/includes/modules/links/class-link.php', 'RankMath\\Links\\Links' => __DIR__ . '/../..' . '/includes/modules/links/class-links.php', 'RankMath\\Links\\Storage' => __DIR__ . '/../..' . '/includes/modules/links/class-storage.php', 'RankMath\\Local_Seo\\KML_File' => __DIR__ . '/../..' . '/includes/modules/local-seo/class-kml-file.php', 'RankMath\\Local_Seo\\Local_Seo' => __DIR__ . '/../..' . '/includes/modules/local-seo/class-local-seo.php', 'RankMath\\Metadata' => __DIR__ . '/../..' . '/includes/class-metadata.php', 'RankMath\\Module\\Base' => __DIR__ . '/../..' . '/includes/module/class-base.php', 'RankMath\\Module\\Manager' => __DIR__ . '/../..' . '/includes/module/class-manager.php', 'RankMath\\Module\\Module' => __DIR__ . '/../..' . '/includes/module/class-module.php', 'RankMath\\Monitor\\Admin' => __DIR__ . '/../..' . '/includes/modules/404-monitor/class-admin.php', 'RankMath\\Monitor\\DB' => __DIR__ . '/../..' . '/includes/modules/404-monitor/class-db.php', 'RankMath\\Monitor\\Monitor' => __DIR__ . '/../..' . '/includes/modules/404-monitor/class-monitor.php', 'RankMath\\Monitor\\Table' => __DIR__ . '/../..' . '/includes/modules/404-monitor/class-table.php', 'RankMath\\OpenGraph\\Facebook' => __DIR__ . '/../..' . '/includes/opengraph/class-facebook.php', 'RankMath\\OpenGraph\\Facebook_Locale' => __DIR__ . '/../..' . '/includes/opengraph/class-facebook-locale.php', 'RankMath\\OpenGraph\\Image' => __DIR__ . '/../..' . '/includes/opengraph/class-image.php', 'RankMath\\OpenGraph\\OpenGraph' => __DIR__ . '/../..' . '/includes/opengraph/class-opengraph.php', 'RankMath\\OpenGraph\\Slack' => __DIR__ . '/../..' . '/includes/opengraph/class-slack.php', 'RankMath\\OpenGraph\\Twitter' => __DIR__ . '/../..' . '/includes/opengraph/class-twitter.php', 'RankMath\\Paper\\Archive' => __DIR__ . '/../..' . '/includes/frontend/paper/class-archive.php', 'RankMath\\Paper\\Author' => __DIR__ . '/../..' . '/includes/frontend/paper/class-author.php', 'RankMath\\Paper\\BP_Group' => __DIR__ . '/../..' . '/includes/modules/buddypress/paper/class-bp-group.php', 'RankMath\\Paper\\BP_User' => __DIR__ . '/../..' . '/includes/modules/buddypress/paper/class-bp-user.php', 'RankMath\\Paper\\Blog' => __DIR__ . '/../..' . '/includes/frontend/paper/class-blog.php', 'RankMath\\Paper\\Date' => __DIR__ . '/../..' . '/includes/frontend/paper/class-date.php', 'RankMath\\Paper\\Error_404' => __DIR__ . '/../..' . '/includes/frontend/paper/class-error-404.php', 'RankMath\\Paper\\IPaper' => __DIR__ . '/../..' . '/includes/frontend/paper/interface-paper.php', 'RankMath\\Paper\\Misc' => __DIR__ . '/../..' . '/includes/frontend/paper/class-misc.php', 'RankMath\\Paper\\Paper' => __DIR__ . '/../..' . '/includes/frontend/paper/class-paper.php', 'RankMath\\Paper\\Search' => __DIR__ . '/../..' . '/includes/frontend/paper/class-search.php', 'RankMath\\Paper\\Shop' => __DIR__ . '/../..' . '/includes/frontend/paper/class-shop.php', 'RankMath\\Paper\\Singular' => __DIR__ . '/../..' . '/includes/frontend/paper/class-singular.php', 'RankMath\\Paper\\Taxonomy' => __DIR__ . '/../..' . '/includes/frontend/paper/class-taxonomy.php', 'RankMath\\Post' => __DIR__ . '/../..' . '/includes/class-post.php', 'RankMath\\Redirections\\Admin' => __DIR__ . '/../..' . '/includes/modules/redirections/class-admin.php', 'RankMath\\Redirections\\Cache' => __DIR__ . '/../..' . '/includes/modules/redirections/class-cache.php', 'RankMath\\Redirections\\DB' => __DIR__ . '/../..' . '/includes/modules/redirections/class-db.php', 'RankMath\\Redirections\\Debugger' => __DIR__ . '/../..' . '/includes/modules/redirections/class-debugger.php', 'RankMath\\Redirections\\Export' => __DIR__ . '/../..' . '/includes/modules/redirections/class-export.php', 'RankMath\\Redirections\\Import_Export' => __DIR__ . '/../..' . '/includes/modules/redirections/class-import-export.php', 'RankMath\\Redirections\\Metabox' => __DIR__ . '/../..' . '/includes/modules/redirections/class-metabox.php', 'RankMath\\Redirections\\Redirection' => __DIR__ . '/../..' . '/includes/modules/redirections/class-redirection.php', 'RankMath\\Redirections\\Redirections' => __DIR__ . '/../..' . '/includes/modules/redirections/class-redirections.php', 'RankMath\\Redirections\\Redirector' => __DIR__ . '/../..' . '/includes/modules/redirections/class-redirector.php', 'RankMath\\Redirections\\Table' => __DIR__ . '/../..' . '/includes/modules/redirections/class-table.php', 'RankMath\\Redirections\\Watcher' => __DIR__ . '/../..' . '/includes/modules/redirections/class-watcher.php', 'RankMath\\Replace_Variables\\Advanced_Variables' => __DIR__ . '/../..' . '/includes/replace-variables/class-advanced-variables.php', 'RankMath\\Replace_Variables\\Author_Variables' => __DIR__ . '/../..' . '/includes/replace-variables/class-author-variables.php', 'RankMath\\Replace_Variables\\Base' => __DIR__ . '/../..' . '/includes/replace-variables/class-base.php', 'RankMath\\Replace_Variables\\Basic_Variables' => __DIR__ . '/../..' . '/includes/replace-variables/class-basic-variables.php', 'RankMath\\Replace_Variables\\Cache' => __DIR__ . '/../..' . '/includes/replace-variables/class-cache.php', 'RankMath\\Replace_Variables\\Manager' => __DIR__ . '/../..' . '/includes/replace-variables/class-manager.php', 'RankMath\\Replace_Variables\\Post_Variables' => __DIR__ . '/../..' . '/includes/replace-variables/class-post-variables.php', 'RankMath\\Replace_Variables\\Replacer' => __DIR__ . '/../..' . '/includes/replace-variables/class-replacer.php', 'RankMath\\Replace_Variables\\Term_Variables' => __DIR__ . '/../..' . '/includes/replace-variables/class-term-variables.php', 'RankMath\\Replace_Variables\\Variable' => __DIR__ . '/../..' . '/includes/replace-variables/class-variable.php', 'RankMath\\Rest\\Admin' => __DIR__ . '/../..' . '/includes/rest/class-admin.php', 'RankMath\\Rest\\Front' => __DIR__ . '/../..' . '/includes/rest/class-front.php', 'RankMath\\Rest\\Headless' => __DIR__ . '/../..' . '/includes/rest/class-headless.php', 'RankMath\\Rest\\Post' => __DIR__ . '/../..' . '/includes/rest/class-post.php', 'RankMath\\Rest\\Rest_Helper' => __DIR__ . '/../..' . '/includes/rest/class-rest-helper.php', 'RankMath\\Rest\\Sanitize' => __DIR__ . '/../..' . '/includes/rest/class-sanitize.php', 'RankMath\\Rest\\Setup_Wizard' => __DIR__ . '/../..' . '/includes/rest/class-setup-wizard.php', 'RankMath\\Rest\\Shared' => __DIR__ . '/../..' . '/includes/rest/class-shared.php', 'RankMath\\Rewrite' => __DIR__ . '/../..' . '/includes/class-rewrite.php', 'RankMath\\Robots_Txt' => __DIR__ . '/../..' . '/includes/modules/robots-txt/class-robots-txt.php', 'RankMath\\Role_Manager\\Capability_Manager' => __DIR__ . '/../..' . '/includes/modules/role-manager/class-capability-manager.php', 'RankMath\\Role_Manager\\Members' => __DIR__ . '/../..' . '/includes/modules/role-manager/class-members.php', 'RankMath\\Role_Manager\\Role_Manager' => __DIR__ . '/../..' . '/includes/modules/role-manager/class-role-manager.php', 'RankMath\\Role_Manager\\User_Role_Editor' => __DIR__ . '/../..' . '/includes/modules/role-manager/class-user-role-editor.php', 'RankMath\\Rollback_Version' => __DIR__ . '/../..' . '/includes/modules/version-control/class-rollback-version.php', 'RankMath\\Runner' => __DIR__ . '/../..' . '/includes/interface-runner.php', 'RankMath\\SEO_Analysis\\Admin' => __DIR__ . '/../..' . '/includes/modules/seo-analysis/class-admin.php', 'RankMath\\SEO_Analysis\\Result' => __DIR__ . '/../..' . '/includes/modules/seo-analysis/class-result.php', 'RankMath\\SEO_Analysis\\SEO_Analysis' => __DIR__ . '/../..' . '/includes/modules/seo-analysis/class-seo-analysis.php', 'RankMath\\SEO_Analysis\\SEO_Analyzer' => __DIR__ . '/../..' . '/includes/modules/seo-analysis/class-seo-analyzer.php', 'RankMath\\Schema\\Admin' => __DIR__ . '/../..' . '/includes/modules/schema/class-admin.php', 'RankMath\\Schema\\Article' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-article.php', 'RankMath\\Schema\\Author' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-author.php', 'RankMath\\Schema\\Block' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/class-block.php', 'RankMath\\Schema\\Block_FAQ' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/faq/class-block-faq.php', 'RankMath\\Schema\\Block_HowTo' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/howto/class-block-howto.php', 'RankMath\\Schema\\Block_Parser' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/class-block-parser.php', 'RankMath\\Schema\\Block_Schema' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/schema/class-block-schema.php', 'RankMath\\Schema\\Block_TOC' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/toc/class-block-toc.php', 'RankMath\\Schema\\Blocks' => __DIR__ . '/../..' . '/includes/modules/schema/class-blocks.php', 'RankMath\\Schema\\Blocks\\Admin' => __DIR__ . '/../..' . '/includes/modules/schema/blocks/class-admin.php', 'RankMath\\Schema\\Breadcrumbs' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-breadcrumbs.php', 'RankMath\\Schema\\DB' => __DIR__ . '/../..' . '/includes/modules/schema/class-db.php', 'RankMath\\Schema\\Frontend' => __DIR__ . '/../..' . '/includes/modules/schema/class-frontend.php', 'RankMath\\Schema\\JsonLD' => __DIR__ . '/../..' . '/includes/modules/schema/class-jsonld.php', 'RankMath\\Schema\\Opengraph' => __DIR__ . '/../..' . '/includes/modules/schema/class-opengraph.php', 'RankMath\\Schema\\PrimaryImage' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-primaryimage.php', 'RankMath\\Schema\\Product' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-product.php', 'RankMath\\Schema\\Product_Edd' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-product-edd.php', 'RankMath\\Schema\\Product_WooCommerce' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-product-woocommerce.php', 'RankMath\\Schema\\Products_Page' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-products-page.php', 'RankMath\\Schema\\Publisher' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-publisher.php', 'RankMath\\Schema\\Schema' => __DIR__ . '/../..' . '/includes/modules/schema/class-schema.php', 'RankMath\\Schema\\Singular' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-singular.php', 'RankMath\\Schema\\Snippet' => __DIR__ . '/../..' . '/includes/modules/schema/interface-snippet.php', 'RankMath\\Schema\\Snippet_Shortcode' => __DIR__ . '/../..' . '/includes/modules/schema/class-snippet-shortcode.php', 'RankMath\\Schema\\WC_Attributes' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-wc-attributes.php', 'RankMath\\Schema\\Webpage' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-webpage.php', 'RankMath\\Schema\\Website' => __DIR__ . '/../..' . '/includes/modules/schema/snippets/class-website.php', 'RankMath\\Settings' => __DIR__ . '/../..' . '/includes/class-settings.php', 'RankMath\\Sitemap\\Admin' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-admin.php', 'RankMath\\Sitemap\\Cache' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-cache.php', 'RankMath\\Sitemap\\Cache_Watcher' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-cache-watcher.php', 'RankMath\\Sitemap\\Classifier' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-classifier.php', 'RankMath\\Sitemap\\Generator' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-generator.php', 'RankMath\\Sitemap\\Html\\Authors' => __DIR__ . '/../..' . '/includes/modules/sitemap/html-sitemap/class-authors.php', 'RankMath\\Sitemap\\Html\\Posts' => __DIR__ . '/../..' . '/includes/modules/sitemap/html-sitemap/class-posts.php', 'RankMath\\Sitemap\\Html\\Sitemap' => __DIR__ . '/../..' . '/includes/modules/sitemap/html-sitemap/class-sitemap.php', 'RankMath\\Sitemap\\Html\\Terms' => __DIR__ . '/../..' . '/includes/modules/sitemap/html-sitemap/class-terms.php', 'RankMath\\Sitemap\\Image_Parser' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-image-parser.php', 'RankMath\\Sitemap\\Providers\\Author' => __DIR__ . '/../..' . '/includes/modules/sitemap/providers/class-author.php', 'RankMath\\Sitemap\\Providers\\Post_Type' => __DIR__ . '/../..' . '/includes/modules/sitemap/providers/class-post-type.php', 'RankMath\\Sitemap\\Providers\\Provider' => __DIR__ . '/../..' . '/includes/modules/sitemap/providers/interface-provider.php', 'RankMath\\Sitemap\\Providers\\Taxonomy' => __DIR__ . '/../..' . '/includes/modules/sitemap/providers/class-taxonomy.php', 'RankMath\\Sitemap\\Redirect_Core_Sitemaps' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-redirect-core-sitemaps.php', 'RankMath\\Sitemap\\Router' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-router.php', 'RankMath\\Sitemap\\Sitemap' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-sitemap.php', 'RankMath\\Sitemap\\Sitemap_Index' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-sitemap-index.php', 'RankMath\\Sitemap\\Sitemap_XML' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-sitemap-xml.php', 'RankMath\\Sitemap\\Stylesheet' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-stylesheet.php', 'RankMath\\Sitemap\\Timezone' => __DIR__ . '/../..' . '/includes/modules/sitemap/class-timezone.php', 'RankMath\\Sitemap\\XML' => __DIR__ . '/../..' . '/includes/modules/sitemap/abstract-xml.php', 'RankMath\\Status\\Backup' => __DIR__ . '/../..' . '/includes/modules/status/class-backup.php', 'RankMath\\Status\\Error_Log' => __DIR__ . '/../..' . '/includes/modules/status/class-error-log.php', 'RankMath\\Status\\Import_Export_Settings' => __DIR__ . '/../..' . '/includes/modules/status/class-import-export-settings.php', 'RankMath\\Status\\Rest' => __DIR__ . '/../..' . '/includes/modules/status/class-rest.php', 'RankMath\\Status\\Status' => __DIR__ . '/../..' . '/includes/modules/status/class-status.php', 'RankMath\\Status\\System_Status' => __DIR__ . '/../..' . '/includes/modules/status/class-system-status.php', 'RankMath\\Term' => __DIR__ . '/../..' . '/includes/class-term.php', 'RankMath\\ThirdParty\\Loco\\Loco_I18n_Inline' => __DIR__ . '/../..' . '/includes/3rdparty/loco/class-loco-i18n-inline.php', 'RankMath\\ThirdParty\\WPML' => __DIR__ . '/../..' . '/includes/3rdparty/wpml/class-wpml.php', 'RankMath\\Thumbnail_Overlay' => __DIR__ . '/../..' . '/includes/class-thumbnail-overlay.php', 'RankMath\\Tools\\AIOSEO_Blocks' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-aioseo-blocks.php', 'RankMath\\Tools\\AIOSEO_TOC_Converter' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-aioseo-toc-converter.php', 'RankMath\\Tools\\Database_Tools' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-database-tools.php', 'RankMath\\Tools\\Update_Score' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-update-score.php', 'RankMath\\Tools\\Yoast_Blocks' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-yoast-blocks.php', 'RankMath\\Tools\\Yoast_FAQ_Converter' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-yoast-faq-converter.php', 'RankMath\\Tools\\Yoast_HowTo_Converter' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-yoast-howto-converter.php', 'RankMath\\Tools\\Yoast_Local_Converter' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-yoast-local-converter.php', 'RankMath\\Tools\\Yoast_TOC_Converter' => __DIR__ . '/../..' . '/includes/modules/database-tools/class-yoast-toc-converter.php', 'RankMath\\Tracking' => __DIR__ . '/../..' . '/includes/class-tracking.php', 'RankMath\\Traits\\Ajax' => __DIR__ . '/../..' . '/includes/traits/class-ajax.php', 'RankMath\\Traits\\Cache' => __DIR__ . '/../..' . '/includes/traits/class-cache.php', 'RankMath\\Traits\\Hooker' => __DIR__ . '/../..' . '/includes/traits/class-hooker.php', 'RankMath\\Traits\\Meta' => __DIR__ . '/../..' . '/includes/traits/class-meta.php', 'RankMath\\Traits\\Shortcode' => __DIR__ . '/../..' . '/includes/traits/class-shortcode.php', 'RankMath\\Traits\\Wizard' => __DIR__ . '/../..' . '/includes/traits/class-wizard.php', 'RankMath\\Update_Email' => __DIR__ . '/../..' . '/includes/class-update-email.php', 'RankMath\\Updates' => __DIR__ . '/../..' . '/includes/class-updates.php', 'RankMath\\User' => __DIR__ . '/../..' . '/includes/class-user.php', 'RankMath\\Version_Control' => __DIR__ . '/../..' . '/includes/modules/version-control/class-version-control.php', 'RankMath\\Web_Stories\\Web_Stories' => __DIR__ . '/../..' . '/includes/modules/web-stories/class-web-stories.php', 'RankMath\\Wizard\\Compatibility' => __DIR__ . '/../..' . '/includes/admin/wizard/class-compatibility.php', 'RankMath\\Wizard\\Import' => __DIR__ . '/../..' . '/includes/admin/wizard/class-import.php', 'RankMath\\Wizard\\Monitor_Redirection' => __DIR__ . '/../..' . '/includes/admin/wizard/class-monitor-redirection.php', 'RankMath\\Wizard\\Optimization' => __DIR__ . '/../..' . '/includes/admin/wizard/class-optimization.php', 'RankMath\\Wizard\\Ready' => __DIR__ . '/../..' . '/includes/admin/wizard/class-ready.php', 'RankMath\\Wizard\\Role' => __DIR__ . '/../..' . '/includes/admin/wizard/class-role.php', 'RankMath\\Wizard\\Schema_Markup' => __DIR__ . '/../..' . '/includes/admin/wizard/class-schema-markup.php', 'RankMath\\Wizard\\Search_Console' => __DIR__ . '/../..' . '/includes/admin/wizard/class-search-console.php', 'RankMath\\Wizard\\Sitemap' => __DIR__ . '/../..' . '/includes/admin/wizard/class-sitemap.php', 'RankMath\\Wizard\\Wizard_Step' => __DIR__ . '/../..' . '/includes/admin/wizard/interface-wizard-step.php', 'RankMath\\Wizard\\Your_Site' => __DIR__ . '/../..' . '/includes/admin/wizard/class-your-site.php', 'RankMath\\WooCommerce\\Admin' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-admin.php', 'RankMath\\WooCommerce\\Base' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-base.php', 'RankMath\\WooCommerce\\Opengraph' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-opengraph.php', 'RankMath\\WooCommerce\\Permalink_Watcher' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-permalink-watcher.php', 'RankMath\\WooCommerce\\Product_Redirection' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-product-redirection.php', 'RankMath\\WooCommerce\\Sitemap' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-sitemap.php', 'RankMath\\WooCommerce\\WC_Vars' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-wc-vars.php', 'RankMath\\WooCommerce\\WooCommerce' => __DIR__ . '/../..' . '/includes/modules/woocommerce/class-woocommerce.php', 'WPMedia\\Mixpanel\\Optin' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Optin.php', 'WPMedia\\Mixpanel\\Tracking' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Tracking.php', 'WPMedia\\Mixpanel\\TrackingPlugin' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/TrackingPlugin.php', 'WPMedia\\Mixpanel\\WPConsumer' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/WPConsumer.php', 'WPMedia_Base_MixpanelBase' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/Base/MixpanelBase.php', 'WPMedia_ConsumerStrategies_AbstractConsumer' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/AbstractConsumer.php', 'WPMedia_ConsumerStrategies_CurlConsumer' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/CurlConsumer.php', 'WPMedia_ConsumerStrategies_FileConsumer' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/FileConsumer.php', 'WPMedia_ConsumerStrategies_SocketConsumer' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/SocketConsumer.php', 'WPMedia_Mixpanel' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/Mixpanel.php', 'WPMedia_Producers_MixpanelBaseProducer' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelBaseProducer.php', 'WPMedia_Producers_MixpanelEvents' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelEvents.php', 'WPMedia_Producers_MixpanelGroups' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelGroups.php', 'WPMedia_Producers_MixpanelPeople' => __DIR__ . '/..' . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelPeople.php', 'WP_Async_Request' => __DIR__ . '/..' . '/a5hleyrich/wp-background-processing/classes/wp-async-request.php', 'WP_Background_Process' => __DIR__ . '/..' . '/a5hleyrich/wp-background-processing/classes/wp-background-process.php', 'donatj\\UserAgent\\Browsers' => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgent/Browsers.php', 'donatj\\UserAgent\\Platforms' => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgent/Platforms.php', 'donatj\\UserAgent\\UserAgent' => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgent/UserAgent.php', 'donatj\\UserAgent\\UserAgentInterface' => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgent/UserAgentInterface.php', 'donatj\\UserAgent\\UserAgentParser' => __DIR__ . '/..' . '/donatj/phpuseragentparser/src/UserAgent/UserAgentParser.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInitb6b9cb56b2244b2950baac041c453348::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInitb6b9cb56b2244b2950baac041c453348::$prefixDirsPsr4; $loader->classMap = ComposerStaticInitb6b9cb56b2244b2950baac041c453348::$classMap; }, null, ClassLoader::class); } } composer/installed.php 0000644 00000005245 15151523435 0011075 0 ustar 00 <?php return array( 'root' => array( 'name' => 'rankmath/seo-by-rank-math', 'pretty_version' => 'v1.0.264.1', 'version' => '1.0.264.1', 'reference' => '95dc1773109e16a693e9ccbc692843e9527dfa2d', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev' => false, ), 'versions' => array( 'a5hleyrich/wp-background-processing' => array( 'pretty_version' => '1.4.0', 'version' => '1.4.0.0', 'reference' => '7ca7cc3504333db3a291bbab7f1917124fba4816', 'type' => 'library', 'install_path' => __DIR__ . '/../a5hleyrich/wp-background-processing', 'aliases' => array(), 'dev_requirement' => false, ), 'cmb2/cmb2' => array( 'pretty_version' => 'v2.11.0', 'version' => '2.11.0.0', 'reference' => '2847828b5cce1b48d09427ee13e6f7c752704468', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../cmb2/cmb2', 'aliases' => array(), 'dev_requirement' => false, ), 'donatj/phpuseragentparser' => array( 'pretty_version' => 'v1.11.0', 'version' => '1.11.0.0', 'reference' => 'c98541c5198bb75564d7db4a8971773bc848361e', 'type' => 'library', 'install_path' => __DIR__ . '/../donatj/phpuseragentparser', 'aliases' => array(), 'dev_requirement' => false, ), 'rankmath/seo-by-rank-math' => array( 'pretty_version' => 'v1.0.264.1', 'version' => '1.0.264.1', 'reference' => '95dc1773109e16a693e9ccbc692843e9527dfa2d', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev_requirement' => false, ), 'woocommerce/action-scheduler' => array( 'pretty_version' => '3.9.3', 'version' => '3.9.3.0', 'reference' => 'c58cdbab17651303d406cd3b22cf9d75c71c986c', 'type' => 'wordpress-plugin', 'install_path' => __DIR__ . '/../woocommerce/action-scheduler', 'aliases' => array(), 'dev_requirement' => false, ), 'wp-media/wp-mixpanel' => array( 'pretty_version' => 'v1.4.0', 'version' => '1.4.0.0', 'reference' => 'dfedab2014e816a1040c57d544a6180f1d446624', 'type' => 'library', 'install_path' => __DIR__ . '/../wp-media/wp-mixpanel', 'aliases' => array(), 'dev_requirement' => false, ), ), ); composer/platform_check.php 0000644 00000001633 15151523435 0012074 0 ustar 00 <?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID > 70400)) { $issues[] = 'Your Composer dependencies require a PHP version "> 7.4.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } trigger_error( 'Composer detected issues in your platform: ' . implode(' ', $issues), E_USER_ERROR ); } composer/installed.json 0000644 00000027054 15151523435 0011261 0 ustar 00 { "packages": [ { "name": "a5hleyrich/wp-background-processing", "version": "1.4.0", "version_normalized": "1.4.0.0", "source": { "type": "git", "url": "https://github.com/deliciousbrains/wp-background-processing.git", "reference": "7ca7cc3504333db3a291bbab7f1917124fba4816" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/deliciousbrains/wp-background-processing/zipball/7ca7cc3504333db3a291bbab7f1917124fba4816", "reference": "7ca7cc3504333db3a291bbab7f1917124fba4816", "shasum": "" }, "require": { "php": ">=7.0" }, "require-dev": { "phpcompatibility/phpcompatibility-wp": "*", "phpunit/phpunit": "^8.0", "spryker/code-sniffer": "^0.17.18", "wp-coding-standards/wpcs": "^2.3", "yoast/phpunit-polyfills": "^1.0" }, "suggest": { "coenjacobs/mozart": "Easily wrap this library with your own prefix, to prevent collisions when multiple plugins use this library" }, "time": "2024-12-17T14:04:30+00:00", "type": "library", "installation-source": "dist", "autoload": { "classmap": [ "classes/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "GPL-2.0-or-later" ], "authors": [ { "name": "Delicious Brains", "email": "nom@deliciousbrains.com" } ], "description": "WP Background Processing can be used to fire off non-blocking asynchronous requests or as a background processing tool, allowing you to queue tasks.", "support": { "issues": "https://github.com/deliciousbrains/wp-background-processing/issues", "source": "https://github.com/deliciousbrains/wp-background-processing/tree/1.4.0" }, "install-path": "../a5hleyrich/wp-background-processing" }, { "name": "cmb2/cmb2", "version": "v2.11.0", "version_normalized": "2.11.0.0", "source": { "type": "git", "url": "https://github.com/CMB2/CMB2.git", "reference": "2847828b5cce1b48d09427ee13e6f7c752704468" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/CMB2/CMB2/zipball/2847828b5cce1b48d09427ee13e6f7c752704468", "reference": "2847828b5cce1b48d09427ee13e6f7c752704468", "shasum": "" }, "require": { "php": ">7.4" }, "require-dev": { "apigen/apigen": "4.1.2", "awesomemotive/am-cli-tools": ">=1.3.7", "nette/utils": "2.5.3", "phpunit/phpunit": "^6.5", "yoast/phpunit-polyfills": "^1.1" }, "suggest": { "composer/installers": "~1.0" }, "time": "2024-04-02T19:30:07+00:00", "type": "wordpress-plugin", "installation-source": "dist", "notification-url": "https://packagist.org/downloads/", "license": [ "GPL-2.0-or-later" ], "authors": [ { "name": "Justin Sternberg", "email": "justin@dsgnwrks.pro", "homepage": "https://dsgnwrks.pro", "role": "Developer" }, { "name": "WebDevStudios", "email": "contact@webdevstudios.com", "homepage": "https://github.com/WebDevStudios", "role": "Developer" } ], "description": "CMB2 is a metabox, custom fields, and forms library for WordPress that will blow your mind.", "homepage": "https://github.com/CMB2/CMB2", "keywords": [ "metabox", "plugin", "wordpress" ], "support": { "issues": "https://github.com/CMB2/CMB2/issues", "source": "http://wordpress.org/support/plugin/cmb2" }, "install-path": "../cmb2/cmb2" }, { "name": "donatj/phpuseragentparser", "version": "v1.11.0", "version_normalized": "1.11.0.0", "source": { "type": "git", "url": "https://github.com/donatj/PhpUserAgent.git", "reference": "c98541c5198bb75564d7db4a8971773bc848361e" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/donatj/PhpUserAgent/zipball/c98541c5198bb75564d7db4a8971773bc848361e", "reference": "c98541c5198bb75564d7db4a8971773bc848361e", "shasum": "" }, "require": { "ext-ctype": "*", "php": ">=5.4.0" }, "require-dev": { "camspiers/json-pretty": "~1.0", "donatj/drop": "*", "ext-json": "*", "phpunit/phpunit": "~4.8|~9" }, "time": "2025-09-10T21:58:40+00:00", "type": "library", "installation-source": "dist", "autoload": { "files": [ "src/UserAgentParser.php" ], "psr-4": { "donatj\\UserAgent\\": "src/UserAgent" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jesse G. Donat", "email": "donatj@gmail.com", "homepage": "https://donatstudios.com", "role": "Developer" } ], "description": "Lightning fast, minimalist PHP UserAgent string parser.", "homepage": "https://donatstudios.com/PHP-Parser-HTTP_USER_AGENT", "keywords": [ "browser", "browser detection", "parser", "user agent", "useragent" ], "support": { "issues": "https://github.com/donatj/PhpUserAgent/issues", "source": "https://github.com/donatj/PhpUserAgent/tree/v1.11.0" }, "funding": [ { "url": "https://www.paypal.me/donatj/15", "type": "custom" }, { "url": "https://github.com/donatj", "type": "github" }, { "url": "https://ko-fi.com/donatj", "type": "ko_fi" } ], "install-path": "../donatj/phpuseragentparser" }, { "name": "woocommerce/action-scheduler", "version": "3.9.3", "version_normalized": "3.9.3.0", "source": { "type": "git", "url": "https://github.com/woocommerce/action-scheduler.git", "reference": "c58cdbab17651303d406cd3b22cf9d75c71c986c" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/woocommerce/action-scheduler/zipball/c58cdbab17651303d406cd3b22cf9d75c71c986c", "reference": "c58cdbab17651303d406cd3b22cf9d75c71c986c", "shasum": "" }, "require": { "php": ">=7.2" }, "require-dev": { "phpunit/phpunit": "^8.5", "woocommerce/woocommerce-sniffs": "0.1.0", "wp-cli/wp-cli": "~2.5.0", "yoast/phpunit-polyfills": "^2.0" }, "time": "2025-07-15T09:32:30+00:00", "type": "wordpress-plugin", "extra": { "scripts-description": { "test": "Run unit tests", "phpcs": "Analyze code against the WordPress coding standards with PHP_CodeSniffer", "phpcbf": "Fix coding standards warnings/errors automatically with PHP Code Beautifier" } }, "installation-source": "dist", "notification-url": "https://packagist.org/downloads/", "license": [ "GPL-3.0-or-later" ], "description": "Action Scheduler for WordPress and WooCommerce", "homepage": "https://actionscheduler.org/", "support": { "issues": "https://github.com/woocommerce/action-scheduler/issues", "source": "https://github.com/woocommerce/action-scheduler/tree/3.9.3" }, "install-path": "../woocommerce/action-scheduler" }, { "name": "wp-media/wp-mixpanel", "version": "v1.4.0", "version_normalized": "1.4.0.0", "source": { "type": "git", "url": "https://github.com/wp-media/wp-mixpanel.git", "reference": "dfedab2014e816a1040c57d544a6180f1d446624" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/wp-media/wp-mixpanel/zipball/dfedab2014e816a1040c57d544a6180f1d446624", "reference": "dfedab2014e816a1040c57d544a6180f1d446624", "shasum": "" }, "require": { "php": ">=7.3" }, "require-dev": { "php-stubs/wordpress-tests-stubs": "^6.5", "phpcompatibility/phpcompatibility-wp": "^2.0", "phpstan/extension-installer": "^1.3", "phpstan/phpstan-mockery": "^2.0", "phpstan/phpstan-phpunit": "^2.0", "roave/security-advisories": "dev-master", "szepeviktor/phpstan-wordpress": "^2.0", "wp-coding-standards/wpcs": "^3", "wp-media/phpunit": "^3" }, "time": "2025-11-12T09:51:35+00:00", "type": "library", "installation-source": "dist", "autoload": { "psr-4": { "WPMedia\\Mixpanel\\": "src/" }, "classmap": [ "src/Classes/" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "GPL-3.0-or-later" ], "authors": [ { "name": "WP Media", "homepage": "https://github.com/wp-media/wp-mixpanel", "role": "Developer" } ], "description": "WordPress Mixpanel Integration", "support": { "issues": "https://github.com/wp-media/wp-mixpanel/issues", "source": "https://github.com/wp-media/wp-mixpanel/tree/v1.4.0" }, "install-path": "../wp-media/wp-mixpanel" } ], "dev": false, "dev-package-names": [] } composer/autoload_psr4.php 0000644 00000000460 15151523435 0011670 0 ustar 00 <?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'donatj\\UserAgent\\' => array($vendorDir . '/donatj/phpuseragentparser/src/UserAgent'), 'WPMedia\\Mixpanel\\' => array($vendorDir . '/wp-media/wp-mixpanel/src'), ); composer/InstalledVersions.php 0000644 00000035335 15151523435 0012571 0 ustar 00 <?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Autoload\ClassLoader; use Composer\Semver\VersionParser; /** * This class is copied in every Composer installed project and available to all * * See also https://getcomposer.org/doc/07-runtime.md#installed-versions * * To require its presence, you can require `composer-runtime-api ^2.0` * * @final */ class InstalledVersions { /** * @var mixed[]|null * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null */ private static $installed; /** * @var bool|null */ private static $canGetVendors; /** * @var array[] * @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ private static $installedByVendor = array(); /** * Returns a list of all package names which are present, either by being installed, replaced or provided * * @return string[] * @psalm-return list<string> */ public static function getInstalledPackages() { $packages = array(); foreach (self::getInstalled() as $installed) { $packages[] = array_keys($installed['versions']); } if (1 === \count($packages)) { return $packages[0]; } return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); } /** * Returns a list of all package names with a specific type e.g. 'library' * * @param string $type * @return string[] * @psalm-return list<string> */ public static function getInstalledPackagesByType($type) { $packagesByType = array(); foreach (self::getInstalled() as $installed) { foreach ($installed['versions'] as $name => $package) { if (isset($package['type']) && $package['type'] === $type) { $packagesByType[] = $name; } } } return $packagesByType; } /** * Checks whether the given package is installed * * This also returns true if the package name is provided or replaced by another package * * @param string $packageName * @param bool $includeDevRequirements * @return bool */ public static function isInstalled($packageName, $includeDevRequirements = true) { foreach (self::getInstalled() as $installed) { if (isset($installed['versions'][$packageName])) { return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); } } return false; } /** * Checks whether the given package satisfies a version constraint * * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: * * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') * * @param VersionParser $parser Install composer/semver to have access to this class and functionality * @param string $packageName * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package * @return bool */ public static function satisfies(VersionParser $parser, $packageName, $constraint) { $constraint = $parser->parseConstraints($constraint); $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); return $provided->matches($constraint); } /** * Returns a version constraint representing all the range(s) which are installed for a given package * * It is easier to use this via isInstalled() with the $constraint argument if you need to check * whether a given version of a package is installed, and not just whether it exists * * @param string $packageName * @return string Version constraint usable with composer/semver */ public static function getVersionRanges($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } $ranges = array(); if (isset($installed['versions'][$packageName]['pretty_version'])) { $ranges[] = $installed['versions'][$packageName]['pretty_version']; } if (array_key_exists('aliases', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); } if (array_key_exists('replaced', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); } if (array_key_exists('provided', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); } return implode(' || ', $ranges); } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['version'])) { return null; } return $installed['versions'][$packageName]['version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getPrettyVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['pretty_version'])) { return null; } return $installed['versions'][$packageName]['pretty_version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference */ public static function getReference($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['reference'])) { return null; } return $installed['versions'][$packageName]['reference']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. */ public static function getInstallPath($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @return array * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} */ public static function getRootPackage() { $installed = self::getInstalled(); return $installed[0]['root']; } /** * Returns the raw installed.php data for custom implementations * * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. * @return array[] * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} */ public static function getRawData() { @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { self::$installed = include __DIR__ . '/installed.php'; } else { self::$installed = array(); } } return self::$installed; } /** * Returns the raw data of all installed.php which are currently loaded for custom implementations * * @return array[] * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ public static function getAllRawData() { return self::getInstalled(); } /** * Lets you reload the static array from another file * * This is only useful for complex integrations in which a project needs to use * this class but then also needs to execute another project's autoloader in process, * and wants to ensure both projects have access to their version of installed.php. * * A typical case would be PHPUnit, where it would need to make sure it reads all * the data it needs from this class, then call reload() with * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure * the project in which it runs can then also use this class safely, without * interference between PHPUnit's dependencies and the project's dependencies. * * @param array[] $data A vendor/composer/installed.php data set * @return void * * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data */ public static function reload($data) { self::$installed = $data; self::$installedByVendor = array(); } /** * @return array[] * @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}> */ private static function getInstalled() { if (null === self::$canGetVendors) { self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); } $installed = array(); if (self::$canGetVendors) { foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { if (isset(self::$installedByVendor[$vendorDir])) { $installed[] = self::$installedByVendor[$vendorDir]; } elseif (is_file($vendorDir.'/composer/installed.php')) { $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { self::$installed = $installed[count($installed) - 1]; } } } } if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { self::$installed = require __DIR__ . '/installed.php'; } else { self::$installed = array(); } } $installed[] = self::$installed; return $installed; } } composer/autoload_classmap.php 0000644 00000104203 15151523435 0012603 0 ustar 00 <?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'RankMath\\ACF\\ACF' => $baseDir . '/includes/modules/acf/class-acf.php', 'RankMath\\Admin\\Admin' => $baseDir . '/includes/admin/class-admin.php', 'RankMath\\Admin\\Admin_Breadcrumbs' => $baseDir . '/includes/admin/class-admin-breadcrumbs.php', 'RankMath\\Admin\\Admin_Dashboard_Nav' => $baseDir . '/includes/admin/class-admin-dashboard-nav.php', 'RankMath\\Admin\\Admin_Header' => $baseDir . '/includes/admin/class-admin-header.php', 'RankMath\\Admin\\Admin_Helper' => $baseDir . '/includes/admin/class-admin-helper.php', 'RankMath\\Admin\\Admin_Init' => $baseDir . '/includes/admin/class-admin-init.php', 'RankMath\\Admin\\Admin_Menu' => $baseDir . '/includes/admin/class-admin-menu.php', 'RankMath\\Admin\\Api' => $baseDir . '/includes/admin/class-api.php', 'RankMath\\Admin\\Ask_Review' => $baseDir . '/includes/admin/class-ask-review.php', 'RankMath\\Admin\\Assets' => $baseDir . '/includes/admin/class-assets.php', 'RankMath\\Admin\\Bulk_Actions' => $baseDir . '/includes/admin/class-bulk-actions.php', 'RankMath\\Admin\\CMB2_Fields' => $baseDir . '/includes/admin/class-cmb2-fields.php', 'RankMath\\Admin\\CMB2_Options' => $baseDir . '/includes/admin/class-cmb2-options.php', 'RankMath\\Admin\\Database\\Clauses' => $baseDir . '/includes/admin/database/class-clauses.php', 'RankMath\\Admin\\Database\\Database' => $baseDir . '/includes/admin/database/class-database.php', 'RankMath\\Admin\\Database\\Escape' => $baseDir . '/includes/admin/database/class-escape.php', 'RankMath\\Admin\\Database\\GroupBy' => $baseDir . '/includes/admin/database/class-groupby.php', 'RankMath\\Admin\\Database\\Joins' => $baseDir . '/includes/admin/database/class-joins.php', 'RankMath\\Admin\\Database\\OrderBy' => $baseDir . '/includes/admin/database/class-orderby.php', 'RankMath\\Admin\\Database\\Query_Builder' => $baseDir . '/includes/admin/database/class-query-builder.php', 'RankMath\\Admin\\Database\\Select' => $baseDir . '/includes/admin/database/class-select.php', 'RankMath\\Admin\\Database\\Translate' => $baseDir . '/includes/admin/database/class-translate.php', 'RankMath\\Admin\\Database\\Where' => $baseDir . '/includes/admin/database/class-where.php', 'RankMath\\Admin\\Import_Export' => $baseDir . '/includes/admin/class-import-export.php', 'RankMath\\Admin\\Importers\\AIOSEO' => $baseDir . '/includes/admin/importers/class-aioseo.php', 'RankMath\\Admin\\Importers\\AIO_Rich_Snippet' => $baseDir . '/includes/admin/importers/class-aio-rich-snippet.php', 'RankMath\\Admin\\Importers\\Detector' => $baseDir . '/includes/admin/importers/class-detector.php', 'RankMath\\Admin\\Importers\\Plugin_Importer' => $baseDir . '/includes/admin/importers/class-plugin-importer.php', 'RankMath\\Admin\\Importers\\Redirections' => $baseDir . '/includes/admin/importers/class-redirections.php', 'RankMath\\Admin\\Importers\\SEOPress' => $baseDir . '/includes/admin/importers/class-seopress.php', 'RankMath\\Admin\\Importers\\Status' => $baseDir . '/includes/admin/importers/class-status.php', 'RankMath\\Admin\\Importers\\WP_Schema_Pro' => $baseDir . '/includes/admin/importers/class-wp-schema-pro.php', 'RankMath\\Admin\\Importers\\Yoast' => $baseDir . '/includes/admin/importers/class-yoast.php', 'RankMath\\Admin\\List_Table' => $baseDir . '/includes/admin/class-list-table.php', 'RankMath\\Admin\\Lock_Modified_Date' => $baseDir . '/includes/admin/class-lock-modified-date.php', 'RankMath\\Admin\\Metabox\\IScreen' => $baseDir . '/includes/admin/metabox/interface-screen.php', 'RankMath\\Admin\\Metabox\\Metabox' => $baseDir . '/includes/admin/metabox/class-metabox.php', 'RankMath\\Admin\\Metabox\\Post_Screen' => $baseDir . '/includes/admin/metabox/class-post-screen.php', 'RankMath\\Admin\\Metabox\\Screen' => $baseDir . '/includes/admin/metabox/class-screen.php', 'RankMath\\Admin\\Metabox\\Taxonomy_Screen' => $baseDir . '/includes/admin/metabox/class-taxonomy-screen.php', 'RankMath\\Admin\\Metabox\\User_Screen' => $baseDir . '/includes/admin/metabox/class-user-screen.php', 'RankMath\\Admin\\Notices' => $baseDir . '/includes/admin/class-notices.php', 'RankMath\\Admin\\Notifications\\Notification' => $baseDir . '/includes/admin/notifications/class-notification.php', 'RankMath\\Admin\\Notifications\\Notification_Center' => $baseDir . '/includes/admin/notifications/class-notification-center.php', 'RankMath\\Admin\\Option_Center' => $baseDir . '/includes/admin/class-option-center.php', 'RankMath\\Admin\\Options' => $baseDir . '/includes/admin/class-options.php', 'RankMath\\Admin\\Page' => $baseDir . '/includes/admin/class-page.php', 'RankMath\\Admin\\Post_Columns' => $baseDir . '/includes/admin/class-post-columns.php', 'RankMath\\Admin\\Post_Filters' => $baseDir . '/includes/admin/class-post-filters.php', 'RankMath\\Admin\\Pro_Notice' => $baseDir . '/includes/admin/class-pro-notice.php', 'RankMath\\Admin\\Register_Options_Page' => $baseDir . '/includes/admin/class-register-options-page.php', 'RankMath\\Admin\\Registration' => $baseDir . '/includes/admin/class-registration.php', 'RankMath\\Admin\\Sanitize_Settings' => $baseDir . '/includes/admin/class-sanitize-settings.php', 'RankMath\\Admin\\Setup_Wizard' => $baseDir . '/includes/admin/class-setup-wizard.php', 'RankMath\\Admin\\Watcher' => $baseDir . '/includes/admin/watcher/class-watcher.php', 'RankMath\\Admin_Bar_Menu' => $baseDir . '/includes/admin/class-admin-bar-menu.php', 'RankMath\\Analytics\\AJAX' => $baseDir . '/includes/modules/analytics/class-ajax.php', 'RankMath\\Analytics\\Analytics' => $baseDir . '/includes/modules/analytics/class-analytics.php', 'RankMath\\Analytics\\Analytics_Common' => $baseDir . '/includes/modules/analytics/class-analytics-common.php', 'RankMath\\Analytics\\Analytics_Stats' => $baseDir . '/includes/modules/analytics/class-analytics-stats.php', 'RankMath\\Analytics\\DB' => $baseDir . '/includes/modules/analytics/class-db.php', 'RankMath\\Analytics\\Email_Reports' => $baseDir . '/includes/modules/analytics/class-email-reports.php', 'RankMath\\Analytics\\GTag' => $baseDir . '/includes/modules/analytics/class-gtag.php', 'RankMath\\Analytics\\Keywords' => $baseDir . '/includes/modules/analytics/class-keywords.php', 'RankMath\\Analytics\\Objects' => $baseDir . '/includes/modules/analytics/class-objects.php', 'RankMath\\Analytics\\Posts' => $baseDir . '/includes/modules/analytics/class-posts.php', 'RankMath\\Analytics\\Rest' => $baseDir . '/includes/modules/analytics/rest/class-rest.php', 'RankMath\\Analytics\\Stats' => $baseDir . '/includes/modules/analytics/class-stats.php', 'RankMath\\Analytics\\Summary' => $baseDir . '/includes/modules/analytics/class-summary.php', 'RankMath\\Analytics\\Url_Inspection' => $baseDir . '/includes/modules/analytics/class-url-inspection.php', 'RankMath\\Analytics\\Watcher' => $baseDir . '/includes/modules/analytics/class-watcher.php', 'RankMath\\Analytics\\Workflow\\Base' => $baseDir . '/includes/modules/analytics/workflows/class-base.php', 'RankMath\\Analytics\\Workflow\\Console' => $baseDir . '/includes/modules/analytics/workflows/class-console.php', 'RankMath\\Analytics\\Workflow\\Inspections' => $baseDir . '/includes/modules/analytics/workflows/class-inspections.php', 'RankMath\\Analytics\\Workflow\\Jobs' => $baseDir . '/includes/modules/analytics/workflows/class-jobs.php', 'RankMath\\Analytics\\Workflow\\OAuth' => $baseDir . '/includes/modules/analytics/workflows/class-oauth.php', 'RankMath\\Analytics\\Workflow\\Objects' => $baseDir . '/includes/modules/analytics/workflows/class-objects.php', 'RankMath\\Analytics\\Workflow\\Workflow' => $baseDir . '/includes/modules/analytics/workflows/class-workflow.php', 'RankMath\\Auto_Updater' => $baseDir . '/includes/class-auto-updater.php', 'RankMath\\Beta_Optin' => $baseDir . '/includes/modules/version-control/class-beta-optin.php', 'RankMath\\BuddyPress\\Admin' => $baseDir . '/includes/modules/buddypress/class-admin.php', 'RankMath\\BuddyPress\\BuddyPress' => $baseDir . '/includes/modules/buddypress/class-buddypress.php', 'RankMath\\CLI\\Commands' => $baseDir . '/includes/cli/class-commands.php', 'RankMath\\CMB2' => $baseDir . '/includes/class-cmb2.php', 'RankMath\\Common' => $baseDir . '/includes/class-common.php', 'RankMath\\Compatibility' => $baseDir . '/includes/class-compatibility.php', 'RankMath\\ContentAI\\Admin' => $baseDir . '/includes/modules/content-ai/class-admin.php', 'RankMath\\ContentAI\\Assets' => $baseDir . '/includes/modules/content-ai/class-assets.php', 'RankMath\\ContentAI\\Block_Command' => $baseDir . '/includes/modules/content-ai/blocks/command/class-block-command.php', 'RankMath\\ContentAI\\Bulk_Actions' => $baseDir . '/includes/modules/content-ai/class-bulk-actions.php', 'RankMath\\ContentAI\\Bulk_Edit_SEO_Meta' => $baseDir . '/includes/modules/content-ai/class-bulk-edit-seo-meta.php', 'RankMath\\ContentAI\\Bulk_Image_Alt' => $baseDir . '/includes/modules/content-ai/class-bulk-image-alt.php', 'RankMath\\ContentAI\\Content_AI' => $baseDir . '/includes/modules/content-ai/class-content-ai.php', 'RankMath\\ContentAI\\Content_AI_Page' => $baseDir . '/includes/modules/content-ai/class-content-ai-page.php', 'RankMath\\ContentAI\\Event_Scheduler' => $baseDir . '/includes/modules/content-ai/class-event-scheduler.php', 'RankMath\\ContentAI\\Rest' => $baseDir . '/includes/modules/content-ai/class-rest.php', 'RankMath\\Dashboard_Widget' => $baseDir . '/includes/admin/class-dashboard-widget.php', 'RankMath\\Data_Encryption' => $baseDir . '/includes/class-data-encryption.php', 'RankMath\\Defaults' => $baseDir . '/includes/class-defaults.php', 'RankMath\\Divi\\Divi' => $baseDir . '/includes/3rdparty/divi/class-divi.php', 'RankMath\\Divi\\Divi_Admin' => $baseDir . '/includes/3rdparty/divi/class-divi-admin.php', 'RankMath\\Elementor\\Elementor' => $baseDir . '/includes/3rdparty/elementor/class-elementor.php', 'RankMath\\Frontend\\Breadcrumbs' => $baseDir . '/includes/frontend/class-breadcrumbs.php', 'RankMath\\Frontend\\Comments' => $baseDir . '/includes/frontend/class-comments.php', 'RankMath\\Frontend\\Frontend' => $baseDir . '/includes/frontend/class-frontend.php', 'RankMath\\Frontend\\Head' => $baseDir . '/includes/frontend/class-head.php', 'RankMath\\Frontend\\Link_Attributes' => $baseDir . '/includes/frontend/class-link-attributes.php', 'RankMath\\Frontend\\Redirection' => $baseDir . '/includes/frontend/class-redirection.php', 'RankMath\\Frontend\\Shortcodes' => $baseDir . '/includes/frontend/class-shortcodes.php', 'RankMath\\Frontend_SEO_Score' => $baseDir . '/includes/class-frontend-seo-score.php', 'RankMath\\Google\\Analytics' => $baseDir . '/includes/modules/analytics/google/class-analytics.php', 'RankMath\\Google\\Api' => $baseDir . '/includes/modules/analytics/google/class-api.php', 'RankMath\\Google\\Authentication' => $baseDir . '/includes/modules/analytics/google/class-authentication.php', 'RankMath\\Google\\Console' => $baseDir . '/includes/modules/analytics/google/class-console.php', 'RankMath\\Google\\Permissions' => $baseDir . '/includes/modules/analytics/google/class-permissions.php', 'RankMath\\Google\\Request' => $baseDir . '/includes/modules/analytics/google/class-request.php', 'RankMath\\Google\\Url_Inspection' => $baseDir . '/includes/modules/analytics/google/class-url-inspection.php', 'RankMath\\Helper' => $baseDir . '/includes/class-helper.php', 'RankMath\\Helpers\\Analytics' => $baseDir . '/includes/helpers/class-analytics.php', 'RankMath\\Helpers\\Api' => $baseDir . '/includes/helpers/class-api.php', 'RankMath\\Helpers\\Arr' => $baseDir . '/includes/helpers/class-arr.php', 'RankMath\\Helpers\\Attachment' => $baseDir . '/includes/helpers/class-attachment.php', 'RankMath\\Helpers\\Choices' => $baseDir . '/includes/helpers/class-choices.php', 'RankMath\\Helpers\\Conditional' => $baseDir . '/includes/helpers/class-conditional.php', 'RankMath\\Helpers\\Content_AI' => $baseDir . '/includes/helpers/class-content-ai.php', 'RankMath\\Helpers\\DB' => $baseDir . '/includes/helpers/class-db.php', 'RankMath\\Helpers\\Editor' => $baseDir . '/includes/helpers/class-editor.php', 'RankMath\\Helpers\\HTML' => $baseDir . '/includes/helpers/class-html.php', 'RankMath\\Helpers\\Locale' => $baseDir . '/includes/helpers/class-locale.php', 'RankMath\\Helpers\\Options' => $baseDir . '/includes/helpers/class-options.php', 'RankMath\\Helpers\\Param' => $baseDir . '/includes/helpers/class-param.php', 'RankMath\\Helpers\\Post_Type' => $baseDir . '/includes/helpers/class-post-type.php', 'RankMath\\Helpers\\Schedule' => $baseDir . '/includes/helpers/class-schedule.php', 'RankMath\\Helpers\\Schema' => $baseDir . '/includes/helpers/class-schema.php', 'RankMath\\Helpers\\Security' => $baseDir . '/includes/helpers/class-security.php', 'RankMath\\Helpers\\Sitepress' => $baseDir . '/includes/helpers/class-sitepress.php', 'RankMath\\Helpers\\Str' => $baseDir . '/includes/helpers/class-str.php', 'RankMath\\Helpers\\Taxonomy' => $baseDir . '/includes/helpers/class-taxonomy.php', 'RankMath\\Helpers\\Url' => $baseDir . '/includes/helpers/class-url.php', 'RankMath\\Helpers\\WordPress' => $baseDir . '/includes/helpers/class-wordpress.php', 'RankMath\\Image_Seo\\Add_Attributes' => $baseDir . '/includes/modules/image-seo/class-add-attributes.php', 'RankMath\\Image_Seo\\Admin' => $baseDir . '/includes/modules/image-seo/class-admin.php', 'RankMath\\Image_Seo\\Image_Seo' => $baseDir . '/includes/modules/image-seo/class-image-seo.php', 'RankMath\\Installer' => $baseDir . '/includes/class-installer.php', 'RankMath\\Instant_Indexing\\Api' => $baseDir . '/includes/modules/instant-indexing/class-api.php', 'RankMath\\Instant_Indexing\\Instant_Indexing' => $baseDir . '/includes/modules/instant-indexing/class-instant-indexing.php', 'RankMath\\Instant_Indexing\\Rest' => $baseDir . '/includes/modules/instant-indexing/class-rest.php', 'RankMath\\Json_Manager' => $baseDir . '/includes/class-json-manager.php', 'RankMath\\KB' => $baseDir . '/includes/class-kb.php', 'RankMath\\LLMS\\LLMS_Txt' => $baseDir . '/includes/modules/llms/class-llms-txt.php', 'RankMath\\Links\\ContentProcessor' => $baseDir . '/includes/modules/links/class-contentprocessor.php', 'RankMath\\Links\\Link' => $baseDir . '/includes/modules/links/class-link.php', 'RankMath\\Links\\Links' => $baseDir . '/includes/modules/links/class-links.php', 'RankMath\\Links\\Storage' => $baseDir . '/includes/modules/links/class-storage.php', 'RankMath\\Local_Seo\\KML_File' => $baseDir . '/includes/modules/local-seo/class-kml-file.php', 'RankMath\\Local_Seo\\Local_Seo' => $baseDir . '/includes/modules/local-seo/class-local-seo.php', 'RankMath\\Metadata' => $baseDir . '/includes/class-metadata.php', 'RankMath\\Module\\Base' => $baseDir . '/includes/module/class-base.php', 'RankMath\\Module\\Manager' => $baseDir . '/includes/module/class-manager.php', 'RankMath\\Module\\Module' => $baseDir . '/includes/module/class-module.php', 'RankMath\\Monitor\\Admin' => $baseDir . '/includes/modules/404-monitor/class-admin.php', 'RankMath\\Monitor\\DB' => $baseDir . '/includes/modules/404-monitor/class-db.php', 'RankMath\\Monitor\\Monitor' => $baseDir . '/includes/modules/404-monitor/class-monitor.php', 'RankMath\\Monitor\\Table' => $baseDir . '/includes/modules/404-monitor/class-table.php', 'RankMath\\OpenGraph\\Facebook' => $baseDir . '/includes/opengraph/class-facebook.php', 'RankMath\\OpenGraph\\Facebook_Locale' => $baseDir . '/includes/opengraph/class-facebook-locale.php', 'RankMath\\OpenGraph\\Image' => $baseDir . '/includes/opengraph/class-image.php', 'RankMath\\OpenGraph\\OpenGraph' => $baseDir . '/includes/opengraph/class-opengraph.php', 'RankMath\\OpenGraph\\Slack' => $baseDir . '/includes/opengraph/class-slack.php', 'RankMath\\OpenGraph\\Twitter' => $baseDir . '/includes/opengraph/class-twitter.php', 'RankMath\\Paper\\Archive' => $baseDir . '/includes/frontend/paper/class-archive.php', 'RankMath\\Paper\\Author' => $baseDir . '/includes/frontend/paper/class-author.php', 'RankMath\\Paper\\BP_Group' => $baseDir . '/includes/modules/buddypress/paper/class-bp-group.php', 'RankMath\\Paper\\BP_User' => $baseDir . '/includes/modules/buddypress/paper/class-bp-user.php', 'RankMath\\Paper\\Blog' => $baseDir . '/includes/frontend/paper/class-blog.php', 'RankMath\\Paper\\Date' => $baseDir . '/includes/frontend/paper/class-date.php', 'RankMath\\Paper\\Error_404' => $baseDir . '/includes/frontend/paper/class-error-404.php', 'RankMath\\Paper\\IPaper' => $baseDir . '/includes/frontend/paper/interface-paper.php', 'RankMath\\Paper\\Misc' => $baseDir . '/includes/frontend/paper/class-misc.php', 'RankMath\\Paper\\Paper' => $baseDir . '/includes/frontend/paper/class-paper.php', 'RankMath\\Paper\\Search' => $baseDir . '/includes/frontend/paper/class-search.php', 'RankMath\\Paper\\Shop' => $baseDir . '/includes/frontend/paper/class-shop.php', 'RankMath\\Paper\\Singular' => $baseDir . '/includes/frontend/paper/class-singular.php', 'RankMath\\Paper\\Taxonomy' => $baseDir . '/includes/frontend/paper/class-taxonomy.php', 'RankMath\\Post' => $baseDir . '/includes/class-post.php', 'RankMath\\Redirections\\Admin' => $baseDir . '/includes/modules/redirections/class-admin.php', 'RankMath\\Redirections\\Cache' => $baseDir . '/includes/modules/redirections/class-cache.php', 'RankMath\\Redirections\\DB' => $baseDir . '/includes/modules/redirections/class-db.php', 'RankMath\\Redirections\\Debugger' => $baseDir . '/includes/modules/redirections/class-debugger.php', 'RankMath\\Redirections\\Export' => $baseDir . '/includes/modules/redirections/class-export.php', 'RankMath\\Redirections\\Import_Export' => $baseDir . '/includes/modules/redirections/class-import-export.php', 'RankMath\\Redirections\\Metabox' => $baseDir . '/includes/modules/redirections/class-metabox.php', 'RankMath\\Redirections\\Redirection' => $baseDir . '/includes/modules/redirections/class-redirection.php', 'RankMath\\Redirections\\Redirections' => $baseDir . '/includes/modules/redirections/class-redirections.php', 'RankMath\\Redirections\\Redirector' => $baseDir . '/includes/modules/redirections/class-redirector.php', 'RankMath\\Redirections\\Table' => $baseDir . '/includes/modules/redirections/class-table.php', 'RankMath\\Redirections\\Watcher' => $baseDir . '/includes/modules/redirections/class-watcher.php', 'RankMath\\Replace_Variables\\Advanced_Variables' => $baseDir . '/includes/replace-variables/class-advanced-variables.php', 'RankMath\\Replace_Variables\\Author_Variables' => $baseDir . '/includes/replace-variables/class-author-variables.php', 'RankMath\\Replace_Variables\\Base' => $baseDir . '/includes/replace-variables/class-base.php', 'RankMath\\Replace_Variables\\Basic_Variables' => $baseDir . '/includes/replace-variables/class-basic-variables.php', 'RankMath\\Replace_Variables\\Cache' => $baseDir . '/includes/replace-variables/class-cache.php', 'RankMath\\Replace_Variables\\Manager' => $baseDir . '/includes/replace-variables/class-manager.php', 'RankMath\\Replace_Variables\\Post_Variables' => $baseDir . '/includes/replace-variables/class-post-variables.php', 'RankMath\\Replace_Variables\\Replacer' => $baseDir . '/includes/replace-variables/class-replacer.php', 'RankMath\\Replace_Variables\\Term_Variables' => $baseDir . '/includes/replace-variables/class-term-variables.php', 'RankMath\\Replace_Variables\\Variable' => $baseDir . '/includes/replace-variables/class-variable.php', 'RankMath\\Rest\\Admin' => $baseDir . '/includes/rest/class-admin.php', 'RankMath\\Rest\\Front' => $baseDir . '/includes/rest/class-front.php', 'RankMath\\Rest\\Headless' => $baseDir . '/includes/rest/class-headless.php', 'RankMath\\Rest\\Post' => $baseDir . '/includes/rest/class-post.php', 'RankMath\\Rest\\Rest_Helper' => $baseDir . '/includes/rest/class-rest-helper.php', 'RankMath\\Rest\\Sanitize' => $baseDir . '/includes/rest/class-sanitize.php', 'RankMath\\Rest\\Setup_Wizard' => $baseDir . '/includes/rest/class-setup-wizard.php', 'RankMath\\Rest\\Shared' => $baseDir . '/includes/rest/class-shared.php', 'RankMath\\Rewrite' => $baseDir . '/includes/class-rewrite.php', 'RankMath\\Robots_Txt' => $baseDir . '/includes/modules/robots-txt/class-robots-txt.php', 'RankMath\\Role_Manager\\Capability_Manager' => $baseDir . '/includes/modules/role-manager/class-capability-manager.php', 'RankMath\\Role_Manager\\Members' => $baseDir . '/includes/modules/role-manager/class-members.php', 'RankMath\\Role_Manager\\Role_Manager' => $baseDir . '/includes/modules/role-manager/class-role-manager.php', 'RankMath\\Role_Manager\\User_Role_Editor' => $baseDir . '/includes/modules/role-manager/class-user-role-editor.php', 'RankMath\\Rollback_Version' => $baseDir . '/includes/modules/version-control/class-rollback-version.php', 'RankMath\\Runner' => $baseDir . '/includes/interface-runner.php', 'RankMath\\SEO_Analysis\\Admin' => $baseDir . '/includes/modules/seo-analysis/class-admin.php', 'RankMath\\SEO_Analysis\\Result' => $baseDir . '/includes/modules/seo-analysis/class-result.php', 'RankMath\\SEO_Analysis\\SEO_Analysis' => $baseDir . '/includes/modules/seo-analysis/class-seo-analysis.php', 'RankMath\\SEO_Analysis\\SEO_Analyzer' => $baseDir . '/includes/modules/seo-analysis/class-seo-analyzer.php', 'RankMath\\Schema\\Admin' => $baseDir . '/includes/modules/schema/class-admin.php', 'RankMath\\Schema\\Article' => $baseDir . '/includes/modules/schema/snippets/class-article.php', 'RankMath\\Schema\\Author' => $baseDir . '/includes/modules/schema/snippets/class-author.php', 'RankMath\\Schema\\Block' => $baseDir . '/includes/modules/schema/blocks/class-block.php', 'RankMath\\Schema\\Block_FAQ' => $baseDir . '/includes/modules/schema/blocks/faq/class-block-faq.php', 'RankMath\\Schema\\Block_HowTo' => $baseDir . '/includes/modules/schema/blocks/howto/class-block-howto.php', 'RankMath\\Schema\\Block_Parser' => $baseDir . '/includes/modules/schema/blocks/class-block-parser.php', 'RankMath\\Schema\\Block_Schema' => $baseDir . '/includes/modules/schema/blocks/schema/class-block-schema.php', 'RankMath\\Schema\\Block_TOC' => $baseDir . '/includes/modules/schema/blocks/toc/class-block-toc.php', 'RankMath\\Schema\\Blocks' => $baseDir . '/includes/modules/schema/class-blocks.php', 'RankMath\\Schema\\Blocks\\Admin' => $baseDir . '/includes/modules/schema/blocks/class-admin.php', 'RankMath\\Schema\\Breadcrumbs' => $baseDir . '/includes/modules/schema/snippets/class-breadcrumbs.php', 'RankMath\\Schema\\DB' => $baseDir . '/includes/modules/schema/class-db.php', 'RankMath\\Schema\\Frontend' => $baseDir . '/includes/modules/schema/class-frontend.php', 'RankMath\\Schema\\JsonLD' => $baseDir . '/includes/modules/schema/class-jsonld.php', 'RankMath\\Schema\\Opengraph' => $baseDir . '/includes/modules/schema/class-opengraph.php', 'RankMath\\Schema\\PrimaryImage' => $baseDir . '/includes/modules/schema/snippets/class-primaryimage.php', 'RankMath\\Schema\\Product' => $baseDir . '/includes/modules/schema/snippets/class-product.php', 'RankMath\\Schema\\Product_Edd' => $baseDir . '/includes/modules/schema/snippets/class-product-edd.php', 'RankMath\\Schema\\Product_WooCommerce' => $baseDir . '/includes/modules/schema/snippets/class-product-woocommerce.php', 'RankMath\\Schema\\Products_Page' => $baseDir . '/includes/modules/schema/snippets/class-products-page.php', 'RankMath\\Schema\\Publisher' => $baseDir . '/includes/modules/schema/snippets/class-publisher.php', 'RankMath\\Schema\\Schema' => $baseDir . '/includes/modules/schema/class-schema.php', 'RankMath\\Schema\\Singular' => $baseDir . '/includes/modules/schema/snippets/class-singular.php', 'RankMath\\Schema\\Snippet' => $baseDir . '/includes/modules/schema/interface-snippet.php', 'RankMath\\Schema\\Snippet_Shortcode' => $baseDir . '/includes/modules/schema/class-snippet-shortcode.php', 'RankMath\\Schema\\WC_Attributes' => $baseDir . '/includes/modules/schema/snippets/class-wc-attributes.php', 'RankMath\\Schema\\Webpage' => $baseDir . '/includes/modules/schema/snippets/class-webpage.php', 'RankMath\\Schema\\Website' => $baseDir . '/includes/modules/schema/snippets/class-website.php', 'RankMath\\Settings' => $baseDir . '/includes/class-settings.php', 'RankMath\\Sitemap\\Admin' => $baseDir . '/includes/modules/sitemap/class-admin.php', 'RankMath\\Sitemap\\Cache' => $baseDir . '/includes/modules/sitemap/class-cache.php', 'RankMath\\Sitemap\\Cache_Watcher' => $baseDir . '/includes/modules/sitemap/class-cache-watcher.php', 'RankMath\\Sitemap\\Classifier' => $baseDir . '/includes/modules/sitemap/class-classifier.php', 'RankMath\\Sitemap\\Generator' => $baseDir . '/includes/modules/sitemap/class-generator.php', 'RankMath\\Sitemap\\Html\\Authors' => $baseDir . '/includes/modules/sitemap/html-sitemap/class-authors.php', 'RankMath\\Sitemap\\Html\\Posts' => $baseDir . '/includes/modules/sitemap/html-sitemap/class-posts.php', 'RankMath\\Sitemap\\Html\\Sitemap' => $baseDir . '/includes/modules/sitemap/html-sitemap/class-sitemap.php', 'RankMath\\Sitemap\\Html\\Terms' => $baseDir . '/includes/modules/sitemap/html-sitemap/class-terms.php', 'RankMath\\Sitemap\\Image_Parser' => $baseDir . '/includes/modules/sitemap/class-image-parser.php', 'RankMath\\Sitemap\\Providers\\Author' => $baseDir . '/includes/modules/sitemap/providers/class-author.php', 'RankMath\\Sitemap\\Providers\\Post_Type' => $baseDir . '/includes/modules/sitemap/providers/class-post-type.php', 'RankMath\\Sitemap\\Providers\\Provider' => $baseDir . '/includes/modules/sitemap/providers/interface-provider.php', 'RankMath\\Sitemap\\Providers\\Taxonomy' => $baseDir . '/includes/modules/sitemap/providers/class-taxonomy.php', 'RankMath\\Sitemap\\Redirect_Core_Sitemaps' => $baseDir . '/includes/modules/sitemap/class-redirect-core-sitemaps.php', 'RankMath\\Sitemap\\Router' => $baseDir . '/includes/modules/sitemap/class-router.php', 'RankMath\\Sitemap\\Sitemap' => $baseDir . '/includes/modules/sitemap/class-sitemap.php', 'RankMath\\Sitemap\\Sitemap_Index' => $baseDir . '/includes/modules/sitemap/class-sitemap-index.php', 'RankMath\\Sitemap\\Sitemap_XML' => $baseDir . '/includes/modules/sitemap/class-sitemap-xml.php', 'RankMath\\Sitemap\\Stylesheet' => $baseDir . '/includes/modules/sitemap/class-stylesheet.php', 'RankMath\\Sitemap\\Timezone' => $baseDir . '/includes/modules/sitemap/class-timezone.php', 'RankMath\\Sitemap\\XML' => $baseDir . '/includes/modules/sitemap/abstract-xml.php', 'RankMath\\Status\\Backup' => $baseDir . '/includes/modules/status/class-backup.php', 'RankMath\\Status\\Error_Log' => $baseDir . '/includes/modules/status/class-error-log.php', 'RankMath\\Status\\Import_Export_Settings' => $baseDir . '/includes/modules/status/class-import-export-settings.php', 'RankMath\\Status\\Rest' => $baseDir . '/includes/modules/status/class-rest.php', 'RankMath\\Status\\Status' => $baseDir . '/includes/modules/status/class-status.php', 'RankMath\\Status\\System_Status' => $baseDir . '/includes/modules/status/class-system-status.php', 'RankMath\\Term' => $baseDir . '/includes/class-term.php', 'RankMath\\ThirdParty\\Loco\\Loco_I18n_Inline' => $baseDir . '/includes/3rdparty/loco/class-loco-i18n-inline.php', 'RankMath\\ThirdParty\\WPML' => $baseDir . '/includes/3rdparty/wpml/class-wpml.php', 'RankMath\\Thumbnail_Overlay' => $baseDir . '/includes/class-thumbnail-overlay.php', 'RankMath\\Tools\\AIOSEO_Blocks' => $baseDir . '/includes/modules/database-tools/class-aioseo-blocks.php', 'RankMath\\Tools\\AIOSEO_TOC_Converter' => $baseDir . '/includes/modules/database-tools/class-aioseo-toc-converter.php', 'RankMath\\Tools\\Database_Tools' => $baseDir . '/includes/modules/database-tools/class-database-tools.php', 'RankMath\\Tools\\Update_Score' => $baseDir . '/includes/modules/database-tools/class-update-score.php', 'RankMath\\Tools\\Yoast_Blocks' => $baseDir . '/includes/modules/database-tools/class-yoast-blocks.php', 'RankMath\\Tools\\Yoast_FAQ_Converter' => $baseDir . '/includes/modules/database-tools/class-yoast-faq-converter.php', 'RankMath\\Tools\\Yoast_HowTo_Converter' => $baseDir . '/includes/modules/database-tools/class-yoast-howto-converter.php', 'RankMath\\Tools\\Yoast_Local_Converter' => $baseDir . '/includes/modules/database-tools/class-yoast-local-converter.php', 'RankMath\\Tools\\Yoast_TOC_Converter' => $baseDir . '/includes/modules/database-tools/class-yoast-toc-converter.php', 'RankMath\\Tracking' => $baseDir . '/includes/class-tracking.php', 'RankMath\\Traits\\Ajax' => $baseDir . '/includes/traits/class-ajax.php', 'RankMath\\Traits\\Cache' => $baseDir . '/includes/traits/class-cache.php', 'RankMath\\Traits\\Hooker' => $baseDir . '/includes/traits/class-hooker.php', 'RankMath\\Traits\\Meta' => $baseDir . '/includes/traits/class-meta.php', 'RankMath\\Traits\\Shortcode' => $baseDir . '/includes/traits/class-shortcode.php', 'RankMath\\Traits\\Wizard' => $baseDir . '/includes/traits/class-wizard.php', 'RankMath\\Update_Email' => $baseDir . '/includes/class-update-email.php', 'RankMath\\Updates' => $baseDir . '/includes/class-updates.php', 'RankMath\\User' => $baseDir . '/includes/class-user.php', 'RankMath\\Version_Control' => $baseDir . '/includes/modules/version-control/class-version-control.php', 'RankMath\\Web_Stories\\Web_Stories' => $baseDir . '/includes/modules/web-stories/class-web-stories.php', 'RankMath\\Wizard\\Compatibility' => $baseDir . '/includes/admin/wizard/class-compatibility.php', 'RankMath\\Wizard\\Import' => $baseDir . '/includes/admin/wizard/class-import.php', 'RankMath\\Wizard\\Monitor_Redirection' => $baseDir . '/includes/admin/wizard/class-monitor-redirection.php', 'RankMath\\Wizard\\Optimization' => $baseDir . '/includes/admin/wizard/class-optimization.php', 'RankMath\\Wizard\\Ready' => $baseDir . '/includes/admin/wizard/class-ready.php', 'RankMath\\Wizard\\Role' => $baseDir . '/includes/admin/wizard/class-role.php', 'RankMath\\Wizard\\Schema_Markup' => $baseDir . '/includes/admin/wizard/class-schema-markup.php', 'RankMath\\Wizard\\Search_Console' => $baseDir . '/includes/admin/wizard/class-search-console.php', 'RankMath\\Wizard\\Sitemap' => $baseDir . '/includes/admin/wizard/class-sitemap.php', 'RankMath\\Wizard\\Wizard_Step' => $baseDir . '/includes/admin/wizard/interface-wizard-step.php', 'RankMath\\Wizard\\Your_Site' => $baseDir . '/includes/admin/wizard/class-your-site.php', 'RankMath\\WooCommerce\\Admin' => $baseDir . '/includes/modules/woocommerce/class-admin.php', 'RankMath\\WooCommerce\\Base' => $baseDir . '/includes/modules/woocommerce/class-base.php', 'RankMath\\WooCommerce\\Opengraph' => $baseDir . '/includes/modules/woocommerce/class-opengraph.php', 'RankMath\\WooCommerce\\Permalink_Watcher' => $baseDir . '/includes/modules/woocommerce/class-permalink-watcher.php', 'RankMath\\WooCommerce\\Product_Redirection' => $baseDir . '/includes/modules/woocommerce/class-product-redirection.php', 'RankMath\\WooCommerce\\Sitemap' => $baseDir . '/includes/modules/woocommerce/class-sitemap.php', 'RankMath\\WooCommerce\\WC_Vars' => $baseDir . '/includes/modules/woocommerce/class-wc-vars.php', 'RankMath\\WooCommerce\\WooCommerce' => $baseDir . '/includes/modules/woocommerce/class-woocommerce.php', 'WPMedia\\Mixpanel\\Optin' => $vendorDir . '/wp-media/wp-mixpanel/src/Optin.php', 'WPMedia\\Mixpanel\\Tracking' => $vendorDir . '/wp-media/wp-mixpanel/src/Tracking.php', 'WPMedia\\Mixpanel\\TrackingPlugin' => $vendorDir . '/wp-media/wp-mixpanel/src/TrackingPlugin.php', 'WPMedia\\Mixpanel\\WPConsumer' => $vendorDir . '/wp-media/wp-mixpanel/src/WPConsumer.php', 'WPMedia_Base_MixpanelBase' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/Base/MixpanelBase.php', 'WPMedia_ConsumerStrategies_AbstractConsumer' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/AbstractConsumer.php', 'WPMedia_ConsumerStrategies_CurlConsumer' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/CurlConsumer.php', 'WPMedia_ConsumerStrategies_FileConsumer' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/FileConsumer.php', 'WPMedia_ConsumerStrategies_SocketConsumer' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/SocketConsumer.php', 'WPMedia_Mixpanel' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/Mixpanel.php', 'WPMedia_Producers_MixpanelBaseProducer' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelBaseProducer.php', 'WPMedia_Producers_MixpanelEvents' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelEvents.php', 'WPMedia_Producers_MixpanelGroups' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelGroups.php', 'WPMedia_Producers_MixpanelPeople' => $vendorDir . '/wp-media/wp-mixpanel/src/Classes/Producers/MixpanelPeople.php', 'WP_Async_Request' => $vendorDir . '/a5hleyrich/wp-background-processing/classes/wp-async-request.php', 'WP_Background_Process' => $vendorDir . '/a5hleyrich/wp-background-processing/classes/wp-background-process.php', 'donatj\\UserAgent\\Browsers' => $vendorDir . '/donatj/phpuseragentparser/src/UserAgent/Browsers.php', 'donatj\\UserAgent\\Platforms' => $vendorDir . '/donatj/phpuseragentparser/src/UserAgent/Platforms.php', 'donatj\\UserAgent\\UserAgent' => $vendorDir . '/donatj/phpuseragentparser/src/UserAgent/UserAgent.php', 'donatj\\UserAgent\\UserAgentInterface' => $vendorDir . '/donatj/phpuseragentparser/src/UserAgent/UserAgentInterface.php', 'donatj\\UserAgent\\UserAgentParser' => $vendorDir . '/donatj/phpuseragentparser/src/UserAgent/UserAgentParser.php', ); composer/autoload_namespaces.php 0000644 00000000213 15151523435 0013113 0 ustar 00 <?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( ); composer/autoload_real.php 0000644 00000003312 15151523435 0011722 0 ustar 00 <?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitb6b9cb56b2244b2950baac041c453348 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } require __DIR__ . '/platform_check.php'; spl_autoload_register(array('ComposerAutoloaderInitb6b9cb56b2244b2950baac041c453348', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitb6b9cb56b2244b2950baac041c453348', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitb6b9cb56b2244b2950baac041c453348::getInitializer($loader)); $loader->register(true); $includeFiles = \Composer\Autoload\ComposerStaticInitb6b9cb56b2244b2950baac041c453348::$files; foreach ($includeFiles as $fileIdentifier => $file) { composerRequireb6b9cb56b2244b2950baac041c453348($fileIdentifier, $file); } return $loader; } } /** * @param string $fileIdentifier * @param string $file * @return void */ function composerRequireb6b9cb56b2244b2950baac041c453348($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } } wp-media/wp-mixpanel/src/TrackingPlugin.php 0000644 00000006422 15151523435 0014741 0 ustar 00 <?php declare(strict_types=1); namespace WPMedia\Mixpanel; class TrackingPlugin extends Tracking { /** * Plugin name & version * * @var string */ private $plugin; /** * Brand name * * @var string */ private $brand; /** * Application name * * @var string */ private $app; /** * Constructor * * @param string $mixpanel_token Mixpanel token. * @param string $plugin Plugin name. * @param string $brand Brand name. * @param string $app Application name. */ public function __construct( string $mixpanel_token, string $plugin, string $brand = '', string $app = '' ) { $options = [ 'consumer' => 'wp', 'consumers' => [ 'wp' => 'WPMedia\\Mixpanel\\WPConsumer', ], ]; parent::__construct( $mixpanel_token, $options ); $this->plugin = $plugin; $this->brand = $brand; $this->app = $app; } /** * Track an event in Mixpanel with plugin context * * @param string $event Event name. * @param mixed[] $properties Event properties. * @param string $event_capability The capability required to track the event. * * @return void */ public function track( string $event, array $properties, string $event_capability = '' ): void { /** * Filter the default capability required to track a specific event. * * @param string $capability The capability required to track the event. * @param string $event The event name. * @param string $app The application name. */ $default = apply_filters( 'wp_mixpanel_event_capability', 'manage_options', $event, $this->app ); if ( empty( $event_capability ) ) { $event_capability = $default; } if ( ! current_user_can( $event_capability ) ) { return; } $this->track_direct( $event, $properties ); } /** * Track an event directly in Mixpanel, bypassing capability checks. * * @param string $event Event name. * @param mixed[] $properties Event properties. * * @return void */ public function track_direct( string $event, array $properties ): void { $host = wp_parse_url( get_home_url(), PHP_URL_HOST ); if ( ! $host ) { $host = ''; } $defaults = [ 'domain' => $this->hash( $host ), 'wp_version' => $this->get_wp_version(), 'php_version' => $this->get_php_version(), 'plugin' => strtolower( $this->plugin ), 'brand' => strtolower( $this->brand ), 'application' => strtolower( $this->app ), ]; $properties = array_merge( $properties, $defaults ); parent::track( ucfirst( $event ), $properties ); } /** * Track opt-in status change in Mixpanel * * @param bool $status Opt-in status. * * @return void */ public function track_optin( $status ): void { $this->track( 'WordPress Plugin Data Consent Changed', [ 'opt_in_status' => $status, ] ); } /** * Add the Mixpanel script & initialize it */ public function add_script(): void { /** * Filter the default capability required to track with JS. * * @param string $capability The capability required to track the event. * @param string $app The application name. */ $capability = apply_filters( 'wp_mixpanel_js_track_capability', 'manage_options', $this->app ); if ( ! current_user_can( $capability ) ) { return; } parent::add_script(); } } wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/CurlConsumer.php 0000644 00000015716 15151523435 0021672 0 ustar 00 <?php /** * Consumes messages and sends them to a host/endpoint using cURL */ class WPMedia_ConsumerStrategies_CurlConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer { /** * @var string the host to connect to (e.g. api.mixpanel.com) */ protected $_host; /** * @var string the host-relative endpoint to write to (e.g. /engage) */ protected $_endpoint; /** * @var int connect_timeout The number of seconds to wait while trying to connect. Default is 5 seconds. */ protected $_connect_timeout; /** * @var int timeout The maximum number of seconds to allow cURL call to execute. Default is 30 seconds. */ protected $_timeout; /** * @var string the protocol to use for the cURL connection */ protected $_protocol; /** * @var bool|null true to fork the cURL process (using exec) or false to use PHP's cURL extension. false by default */ protected $_fork = null; /** * @var int number of cURL requests to run in parallel. 1 by default */ protected $_num_threads; /** * Creates a new CurlConsumer and assigns properties from the $options array * @param array $options * @throws Exception */ function __construct($options) { parent::__construct($options); $this->_host = $options['host']; $this->_endpoint = $options['endpoint']; $this->_connect_timeout = isset($options['connect_timeout']) ? $options['connect_timeout'] : 5; $this->_timeout = isset($options['timeout']) ? $options['timeout'] : 30; $this->_protocol = isset($options['use_ssl']) && $options['use_ssl'] == true ? "https" : "http"; $this->_fork = isset($options['fork']) ? ($options['fork'] == true) : false; $this->_num_threads = isset($options['num_threads']) ? max(1, intval($options['num_threads'])) : 1; // ensure the environment is workable for the given settings if ($this->_fork == true) { $exists = function_exists('exec'); if (!$exists) { throw new Exception('The "exec" function must exist to use the cURL consumer in "fork" mode. Try setting fork = false or use another consumer.'); } $disabled = explode(', ', ini_get('disable_functions')); $enabled = !in_array('exec', $disabled); if (!$enabled) { throw new Exception('The "exec" function must be enabled to use the cURL consumer in "fork" mode. Try setting fork = false or use another consumer.'); } } else { if (!function_exists('curl_init')) { throw new Exception('The cURL PHP extension is required to use the cURL consumer with fork = false. Try setting fork = true or use another consumer.'); } } } /** * Write to the given host/endpoint using either a forked cURL process or using PHP's cURL extension * @param array $batch * @return bool */ public function persist($batch) { if (count($batch) > 0) { $url = $this->_protocol . "://" . $this->_host . $this->_endpoint; if ($this->_fork) { $data = "data=" . $this->_encode($batch); return $this->_execute_forked($url, $data); } else { return $this->_execute($url, $batch); } } else { return true; } } /** * Write using the cURL php extension * @param $url * @param $batch * @return bool */ protected function _execute($url, $batch) { if ($this->_debug()) { $this->_log("Making blocking cURL call to $url"); } $mh = curl_multi_init(); $chs = array(); $batch_size = ceil(count($batch) / $this->_num_threads); for ($i=0; $i<$this->_num_threads && !empty($batch); $i++) { $ch = curl_init(); $chs[] = $ch; $data = "data=" . $this->_encode(array_splice($batch, 0, $batch_size)); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_connect_timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_multi_add_handle($mh,$ch); } $running = 0; do { curl_multi_exec($mh, $running); curl_multi_select($mh); } while ($running > 0); $info = curl_multi_info_read($mh); $error = false; foreach ($chs as $ch) { $response = curl_multi_getcontent($ch); if (false === $response) { $this->_handleError(curl_errno($ch), curl_error($ch)); $error = true; } elseif ("1" != trim($response)) { $this->_handleError(0, $response); $error = true; } curl_multi_remove_handle($mh, $ch); } if (CURLE_OK != $info['result']) { $this->_handleError($info['result'], "cURL error with code=".$info['result']); $error = true; } curl_multi_close($mh); return !$error; } /** * Write using a forked cURL process * @param $url * @param $data * @return bool */ protected function _execute_forked($url, $data) { if ($this->_debug()) { $this->_log("Making forked cURL call to $url"); } $exec = 'curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d ' . $data . ' "' . $url . '"'; if(!$this->_debug()) { $exec .= " >/dev/null 2>&1 &"; } exec($exec, $output, $return_var); if ($return_var != 0) { $this->_handleError($return_var, $output); } return $return_var == 0; } /** * @return int */ public function getConnectTimeout() { return $this->_connect_timeout; } /** * @return string */ public function getEndpoint() { return $this->_endpoint; } /** * @return bool|null */ public function getFork() { return $this->_fork; } /** * @return string */ public function getHost() { return $this->_host; } /** * @return array */ public function getOptions() { return $this->_options; } /** * @return string */ public function getProtocol() { return $this->_protocol; } /** * @return int */ public function getTimeout() { return $this->_timeout; } /** * Number of requests/batches that will be processed in parallel using curl_multi_exec. * @return int */ public function getNumThreads() { return $this->_num_threads; } } wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/FileConsumer.php 0000644 00000001704 15151523435 0021634 0 ustar 00 <?php /** * Consumes messages and writes them to a file */ class WPMedia_ConsumerStrategies_FileConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer { /** * @var string path to a file that we want to write the messages to */ private $_file; /** * Creates a new FileConsumer and assigns properties from the $options array * @param array $options */ function __construct($options) { parent::__construct($options); // what file to write to? $this->_file = isset($options['file']) ? $options['file'] : dirname(__FILE__)."/../../messages.txt"; } /** * Append $batch to a file * @param array $batch * @return bool */ public function persist($batch) { if (count($batch) > 0) { return file_put_contents($this->_file, json_encode($batch)."\n", FILE_APPEND | LOCK_EX) !== false; } else { return true; } } } wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/SocketConsumer.php 0000644 00000021767 15151523435 0022220 0 ustar 00 <?php /** * Portions of this class were borrowed from * https://github.com/segmentio/analytics-php/blob/master/lib/Analytics/Consumer/Socket.php. * Thanks for the work! * * WWWWWW||WWWWWW * W W W||W W W * || * ( OO )__________ * / | \ * /o o| MIT \ * \___/||_||__||_|| * * || || || || * _||_|| _||_|| * (__|__|(__|__| * (The MIT License) * * Copyright (c) 2013 Segment.io Inc. friends@segment.io * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ require_once(dirname(__FILE__) . "/AbstractConsumer.php"); /** * Consumes messages and writes them to host/endpoint using a persistent socket */ class WPMedia_ConsumerStrategies_SocketConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer { /** * @var string the host to connect to (e.g. api.mixpanel.com) */ private $_host; /** * @var string the host-relative endpoint to write to (e.g. /engage) */ private $_endpoint; /** * @var int connect_timeout the socket connection timeout in seconds */ private $_connect_timeout; /** * @var string the protocol to use for the socket connection */ private $_protocol; /** * @var resource holds the socket resource */ private $_socket; /** * @var bool whether or not to wait for a response */ private $_async; /** * @var int the port to use for the socket connection */ private $_port; /** * Creates a new SocketConsumer and assigns properties from the $options array * @param array $options */ public function __construct($options = array()) { parent::__construct($options); $this->_host = $options['host']; $this->_endpoint = $options['endpoint']; $this->_connect_timeout = isset($options['connect_timeout']) ? $options['connect_timeout'] : 5; $this->_async = isset($options['async']) && $options['async'] === false ? false : true; if (array_key_exists('use_ssl', $options) && $options['use_ssl'] == true) { $this->_protocol = "ssl"; $this->_port = 443; } else { $this->_protocol = "tcp"; $this->_port = 80; } } /** * Write using a persistent socket connection. * @param array $batch * @return bool */ public function persist($batch) { $socket = $this->_getSocket(); if (!is_resource($socket)) { return false; } $data = "data=".$this->_encode($batch); $body = ""; $body.= "POST ".$this->_endpoint." HTTP/1.1\r\n"; $body.= "Host: " . $this->_host . "\r\n"; $body.= "Content-Type: application/x-www-form-urlencoded\r\n"; $body.= "Accept: application/json\r\n"; $body.= "Content-length: " . strlen($data) . "\r\n"; $body.= "\r\n"; $body.= $data; return $this->_write($socket, $body); } /** * Return cached socket if open or create a new persistent socket * @return bool|resource */ private function _getSocket() { if(is_resource($this->_socket)) { if ($this->_debug()) { $this->_log("Using existing socket"); } return $this->_socket; } else { if ($this->_debug()) { $this->_log("Creating new socket at ".time()); } return $this->_createSocket(); } } /** * Attempt to open a new socket connection, cache it, and return the resource * @param bool $retry * @return bool|resource */ private function _createSocket($retry = true) { try { $socket = pfsockopen($this->_protocol . "://" . $this->_host, $this->_port, $err_no, $err_msg, $this->_connect_timeout); if ($this->_debug()) { $this->_log("Opening socket connection to " . $this->_protocol . "://" . $this->_host . ":" . $this->_port); } if ($err_no != 0) { $this->_handleError($err_no, $err_msg); return $retry == true ? $this->_createSocket(false) : false; } else { // cache the socket $this->_socket = $socket; return $socket; } } catch (Exception $e) { $this->_handleError($e->getCode(), $e->getMessage()); return $retry == true ? $this->_createSocket(false) : false; } } /** * Attempt to close and dereference a socket resource */ private function _destroySocket() { $socket = $this->_socket; $this->_socket = null; fclose($socket); } /** * Write $data through the given $socket * @param $socket * @param $data * @param bool $retry * @return bool */ private function _write($socket, $data, $retry = true) { $bytes_sent = 0; $bytes_total = strlen($data); $socket_closed = false; $success = true; $max_bytes_per_write = 8192; // if we have no data to write just return true if ($bytes_total == 0) { return true; } // try to write the data while (!$socket_closed && $bytes_sent < $bytes_total) { try { $bytes = fwrite($socket, $data, $max_bytes_per_write); if ($this->_debug()) { $this->_log("Socket wrote ".$bytes." bytes"); } // if we actually wrote data, then remove the written portion from $data left to write if ($bytes > 0) { $data = substr($data, $max_bytes_per_write); } } catch (Exception $e) { $this->_handleError($e->getCode(), $e->getMessage()); $socket_closed = true; } if (isset($bytes) && $bytes) { $bytes_sent += $bytes; } else { $socket_closed = true; } } // create a new socket if the current one is closed and retry the message if ($socket_closed) { $this->_destroySocket(); if ($retry) { if ($this->_debug()) { $this->_log("Retrying socket write..."); } $socket = $this->_getSocket(); if ($socket) return $this->_write($socket, $data, false); } return false; } // only wait for the response in debug mode or if we explicitly want to be synchronous if ($this->_debug() || !$this->_async) { $res = $this->handleResponse(fread($socket, 2048)); if ($res["status"] != "200") { $this->_handleError($res["status"], $res["body"]); $success = false; } } return $success; } /** * Parse the response from a socket write (only used for debugging) * @param $response * @return array */ private function handleResponse($response) { $lines = explode("\n", $response); // extract headers $headers = array(); foreach($lines as $line) { $kvsplit = explode(":", $line); if (count($kvsplit) == 2) { $header = $kvsplit[0]; $value = $kvsplit[1]; $headers[$header] = trim($value); } } // extract status $line_one_exploded = explode(" ", $lines[0]); $status = $line_one_exploded[1]; // extract body $body = $lines[count($lines) - 1]; // if the connection has been closed lets kill the socket if (isset($headers["Connection"]) and $headers['Connection'] == "close") { $this->_destroySocket(); if ($this->_debug()) { $this->_log("Server told us connection closed so lets destroy the socket so it'll reconnect on next call"); } } $ret = array( "status" => $status, "body" => $body, ); return $ret; } } wp-media/wp-mixpanel/src/Classes/ConsumerStrategies/AbstractConsumer.php 0000644 00000003145 15151523435 0022521 0 ustar 00 <?php /** * Provides some base methods for use by a Consumer implementation */ abstract class WPMedia_ConsumerStrategies_AbstractConsumer extends WPMedia_Base_MixpanelBase { /** * Creates a new AbstractConsumer * @param array $options */ function __construct($options = array()) { parent::__construct($options); if ($this->_debug()) { $this->_log("Instantiated new Consumer"); } } /** * Encode an array to be persisted * @param array $params * @return string */ protected function _encode($params) { return base64_encode(json_encode($params)); } /** * Handles errors that occur in a consumer * @param $code * @param $msg */ protected function _handleError($code, $msg) { if (isset($this->_options['error_callback'])) { $handler = $this->_options['error_callback']; call_user_func($handler, $code, $msg); } if ($this->_debug()) { $arr = debug_backtrace(); $class = get_class($arr[0]['object']); $line = $arr[0]['line']; error_log ( "[ $class - line $line ] : " . print_r($msg, true) ); } } /** * Number of requests/batches that will be processed in parallel. * @return int */ public function getNumThreads() { return 1; } /** * Persist a batch of messages in whatever way the implementer sees fit * @param array $batch an array of messages to consume * @return boolean success or fail */ abstract function persist($batch); } wp-media/wp-mixpanel/src/Classes/Mixpanel.php 0000644 00000022042 15151523435 0015166 0 ustar 00 <?php /** * This is the main class for the Mixpanel PHP Library which provides all of the methods you need to track events, * create/update profiles and group profiles. * * Architecture * ------------- * * This library is built such that all messages are buffered in an in-memory "queue" * The queue will be automatically flushed at the end of every request. Alternatively, you can call "flush()" manually * at any time. Flushed messages will be passed to a Consumer's "persist" method. The library comes with a handful of * Consumers. The "CurlConsumer" is used by default which will send the messages to Mixpanel using forked cURL processes. * You can implement your own custom Consumer to customize how a message is sent to Mixpanel. This can be useful when * you want to put messages onto a distributed queue (such as ActiveMQ or Kestrel) instead of writing to Mixpanel in * the user thread. * * Options * ------------- * * <table width="100%" cellpadding="5"> * <tr> * <th>Option</th> * <th>Description</th> * <th>Default</th> * </tr> * <tr> * <td>max_queue_size</td> * <td>The maximum number of items to buffer in memory before flushing</td> * <td>1000</td> * </tr> * <tr> * <td>debug</td> * <td>Enable/disable debug mode</td> * <td>false</td> * </tr> * <tr> * <td>consumer</td> * <td>The consumer to use for writing messages</td> * <td>curl</td> * </tr> * <tr> * <td>consumers</td> * <td>An array of custom consumers in the format array(consumer_key => class_name)</td> * <td>null</td> * </tr> * <tr> * <td>host</td> * <td>The host name for api calls (used by some consumers)</td> * <td>api.mixpanel.com</td> * </tr> * <tr> * <td>events_endpoint</td> * <td>The endpoint for tracking events (relative to the host)</td> * <td>/events</td> * </tr> * <tr> * <td>people_endpoint</td> * <td>The endpoint for making people updates (relative to the host)</td> * <td>/engage</td> * </tr> * <tr> * <td>use_ssl</td> * <td>Tell the consumer whether or not to use ssl (when available)</td> * <td>true</td> * </tr> * <tr> * <td>error_callback</td> * <td>The name of a function to be called on consumption failures</td> * <td>null</td> * </tr> * <tr> * <td>connect_timeout</td> * <td>In both the SocketConsumer and CurlConsumer, this is used for the connection timeout (i.e. How long it has take to actually make a connection). * <td>5</td> * </tr> * <tr> * <td>timeout</td> * <td>In the CurlConsumer (non-forked), it is used to determine how long the cURL call has to execute. * <td>30</td> * </tr> * </table> * * Example: Tracking an Event * ------------- * * $mp = Mixpanel::getInstance("MY_TOKEN"); * * $mp->track("My Event"); * * Example: Setting Profile Properties * ------------- * * $mp = Mixpanel::getInstance("MY_TOKEN", array("use_ssl" => false)); * * $mp->people->set(12345, array( * '$first_name' => "John", * '$last_name' => "Doe", * '$email' => "john.doe@example.com", * '$phone' => "5555555555", * 'Favorite Color' => "red" * )); * */ class WPMedia_Mixpanel extends WPMedia_Base_MixpanelBase { /** * An instance of the MixpanelPeople class (used to create/update profiles) * @var WPMedia_Producers_MixpanelPeople */ public $people; /** * An instance of the MixpanelEvents class * @var WPMedia_Producers_MixpanelEvents */ private $_events; /** * An instance of the MixpanelGroups class (used to create/update group profiles) * @var WPMedia_Producers_MixpanelPeople */ public $group; /** * Instances' list of the Mixpanel class (for singleton use, splitted by token) * @var WPMedia_Mixpanel[] */ private static $_instances = array(); /** * Instantiates a new Mixpanel instance. * @param $token * @param array $options */ public function __construct($token, $options = array()) { parent::__construct($options); $this->people = new WPMedia_Producers_MixpanelPeople($token, $options); $this->_events = new WPMedia_Producers_MixpanelEvents($token, $options); $this->group = new WPMedia_Producers_MixpanelGroups($token, $options); } /** * Returns a singleton instance of Mixpanel * @param $token * @param array $options * @return WPMedia_Mixpanel */ public static function getInstance($token, $options = array()) { if(!isset(self::$_instances[$token])) { self::$_instances[$token] = new WPMedia_Mixpanel($token, $options); } return self::$_instances[$token]; } /** * Add an array representing a message to be sent to Mixpanel to the in-memory queue. * @param array $message */ public function enqueue($message = array()) { $this->_events->enqueue($message); } /** * Add an array representing a list of messages to be sent to Mixpanel to a queue. * @param array $messages */ public function enqueueAll($messages = array()) { $this->_events->enqueueAll($messages); } /** * Flush the events queue * @param int $desired_batch_size */ public function flush($desired_batch_size = 50) { $this->_events->flush($desired_batch_size); } /** * Empty the events queue */ public function reset() { $this->_events->reset(); } /** * Identify the user you want to associate to tracked events. The $anon_id must be UUID v4 format and not already merged to an $identified_id. * All identify calls with a new and valid $anon_id will trigger a track $identify event, and merge to the $identified_id. * @param string|int $user_id * @param string|int $anon_id [optional] */ public function identify($user_id, $anon_id = null) { $this->_events->identify($user_id, $anon_id); } /** * Track an event defined by $event associated with metadata defined by $properties * @param string $event * @param array $properties */ public function track($event, $properties = array()) { $this->_events->track($event, $properties); } /** * Register a property to be sent with every event. * * If the property has already been registered, it will be * overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class instance. * @param string $property * @param mixed $value */ public function register($property, $value) { $this->_events->register($property, $value); } /** * Register multiple properties to be sent with every event. * * If any of the properties have already been registered, * they will be overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class * instance. * @param array $props_and_vals */ public function registerAll($props_and_vals = array()) { $this->_events->registerAll($props_and_vals); } /** * Register a property to be sent with every event. * * If the property has already been registered, it will NOT be * overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class instance. * @param $property * @param $value */ public function registerOnce($property, $value) { $this->_events->registerOnce($property, $value); } /** * Register multiple properties to be sent with every event. * * If any of the properties have already been registered, * they will NOT be overwritten. NOTE: Registered properties are only persisted for the life of the Mixpanel class * instance. * @param array $props_and_vals */ public function registerAllOnce($props_and_vals = array()) { $this->_events->registerAllOnce($props_and_vals); } /** * Un-register an property to be sent with every event. * @param string $property */ public function unregister($property) { $this->_events->unregister($property); } /** * Un-register a list of properties to be sent with every event. * @param array $properties */ public function unregisterAll($properties) { $this->_events->unregisterAll($properties); } /** * Get a property that is set to be sent with every event * @param string $property * @return mixed */ public function getProperty($property) { return $this->_events->getProperty($property); } /** * An alias to be merged with the distinct_id. Each alias can only map to one distinct_id. * This is helpful when you want to associate a generated id (such as a session id) to a user id or username. * @param string|int $distinct_id * @param string|int $alias */ public function createAlias($distinct_id, $alias) { $this->_events->createAlias($distinct_id, $alias); } } wp-media/wp-mixpanel/src/Classes/Producers/MixpanelGroups.php 0000644 00000013155 15151523435 0020341 0 ustar 00 <?php /** * Provides an API to create/update group profiles on Mixpanel */ class WPMedia_Producers_MixpanelGroups extends WPMedia_Producers_MixpanelBaseProducer { /** * Internal method to prepare a message given the message data * @param $group_key * @param $group_id * @param $operation * @param $value * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group Profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @return array */ private function _constructPayload($group_key, $group_id, $operation, $value, $ignore_time = false) { $payload = array( '$token' => $this->_token, '$group_key' => $group_key, '$group_id' => $group_id, '$time' => microtime(true), $operation => $value ); if ($ignore_time === true) $payload['$ignore_time'] = true; return $payload; } /** * Set properties on a group profile. If the group profile does not exist, it creates it with these properties. * If it does exist, it sets the properties to these values, overwriting existing values. * @param string|int $group_key the group_key used for groups in Project Settings * @param string|int $group_id the group id used for the group profile * @param array $props associative array of properties to set on the group profile * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time */ public function set($group_key, $group_id, $props, $ignore_time = false) { $payload = $this->_constructPayload($group_key, $group_id, '$set', $props, $ignore_time); $this->enqueue($payload); } /** * Set properties on a group profile. If the Group profile does not exist, it creates it with these properties. * If it does exist, it sets the properties to these values but WILL NOT overwrite existing values. * @param string|int $group_key the group_key used for groups in Project Settings * @param string|int $group_id the group id used for the group profile * @param array $props associative array of properties to set on the group profile * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time */ public function setOnce($group_key, $group_id, $props, $ignore_time = false) { $payload = $this->_constructPayload($group_key, $group_id, '$set_once', $props, $ignore_time); $this->enqueue($payload); } /** * Unset properties on a group profile. If the group does not exist, it creates it with no properties. * If it does exist, it unsets these properties. NOTE: In other libraries we use 'unset' which is * a reserved word in PHP. * @param string|int $group_key the group_key used for groups in Project Settings * @param string|int $group_id the group id used for the group profile * @param array $props associative array of properties to unset on the group profile * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time */ public function remove($group_key, $group_id, $props, $ignore_time = false) { $payload = $this->_constructPayload($group_key, $group_id, '$remove', $props, $ignore_time); $this->enqueue($payload); } /** * Adds $val to a list located at $prop. If the property does not exist, it will be created. If $val is a string * and the list is empty or does not exist, a new list with one value will be created. * @param string|int $group_key the group_key used for groups in Project Settings * @param string|int $group_id the group id used for the group profile * @param string $prop the property that holds the list * @param string|array $val items to add to the list * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the group profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time */ public function union($group_key, $group_id, $prop, $val, $ignore_time = false) { $payload = $this->_constructPayload($group_key, $group_id, '$union', array("$prop" => $val), $ignore_time); $this->enqueue($payload); } /** * Delete this group profile from Mixpanel * @param string|int $group_key the group_key used for groups in Project Settings * @param string|int $group_id the group id used for the group profile * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time */ public function deleteGroup($group_key, $group_id, $ignore_time = false) { $payload = $this->_constructPayload($group_key, $group_id, '$delete', "", $ignore_time); $this->enqueue($payload); } /** * Returns the "groups" endpoint * @return string */ function _getEndpoint() { return $this->_options['groups_endpoint']; } } wp-media/wp-mixpanel/src/Classes/Producers/MixpanelBaseProducer.php 0000644 00000013700 15151523436 0021435 0 ustar 00 <?php if (!function_exists('json_encode')) { throw new Exception('The JSON PHP extension is required.'); } /** * Provides some base methods for use by a message Producer */ abstract class WPMedia_Producers_MixpanelBaseProducer extends WPMedia_Base_MixpanelBase { /** * @var string a token associated to a Mixpanel project */ protected $_token; /** * @var array a queue to hold messages in memory before flushing in batches */ private $_queue = array(); /** * @var WPMedia_ConsumerStrategies_AbstractConsumer the consumer to use when flushing messages */ private $_consumer = null; /** * @var array The list of available consumers */ private $_consumers = array( "file" => "WPMedia_ConsumerStrategies_FileConsumer", "curl" => "WPMedia_ConsumerStrategies_CurlConsumer", "socket" => "WPMedia_ConsumerStrategies_SocketConsumer", ); /** * If the queue reaches this size we'll auto-flush to prevent out of memory errors * @var int */ protected $_max_queue_size = 1000; /** * Creates a new MixpanelBaseProducer, assings Mixpanel project token, registers custom Consumers, and instantiates * the desired consumer * @param $token * @param array $options */ public function __construct($token, $options = array()) { parent::__construct($options); // register any customer consumers if (isset($options["consumers"])) { $this->_consumers = array_merge($this->_consumers, $options['consumers']); } // set max queue size if (isset($options["max_queue_size"])) { $this->_max_queue_size = $options['max_queue_size']; } // associate token $this->_token = $token; if ($this->_debug()) { $this->_log("Using token: ".$this->_token); } // instantiate the chosen consumer $this->_consumer = $this->_getConsumer(); } /** * Flush the queue when we destruct the client with retries */ public function __destruct() { $attempts = 0; $max_attempts = 10; $success = false; while (!$success && $attempts < $max_attempts) { if ($this->_debug()) { $this->_log("destruct flush attempt #".($attempts+1)); } $success = $this->flush(); $attempts++; } } /** * Iterate the queue and write in batches using the instantiated Consumer Strategy * @param int $desired_batch_size * @return bool whether or not the flush was successful */ public function flush($desired_batch_size = 50) { $queue_size = count($this->_queue); $succeeded = true; $num_threads = $this->_consumer->getNumThreads(); if ($this->_debug()) { $this->_log("Flush called - queue size: ".$queue_size); } while($queue_size > 0 && $succeeded) { $batch_size = min(array($queue_size, $desired_batch_size*$num_threads, $this->_options['max_batch_size']*$num_threads)); $batch = array_splice($this->_queue, 0, $batch_size); $succeeded = $this->_persist($batch); if (!$succeeded) { if ($this->_debug()) { $this->_log("Batch consumption failed!"); } $this->_queue = array_merge($batch, $this->_queue); if ($this->_debug()) { $this->_log("added batch back to queue, queue size is now $queue_size"); } } $queue_size = count($this->_queue); if ($this->_debug()) { $this->_log("Batch of $batch_size consumed, queue size is now $queue_size"); } } return $succeeded; } /** * Empties the queue without persisting any of the messages */ public function reset() { $this->_queue = array(); } /** * Returns the in-memory queue * @return array */ public function getQueue() { return $this->_queue; } /** * Returns the current Mixpanel project token * @return string */ public function getToken() { return $this->_token; } /** * Given a strategy type, return a new PersistenceStrategy object * @return WPMedia_ConsumerStrategies_AbstractConsumer */ protected function _getConsumer() { $key = $this->_options['consumer']; $Strategy = $this->_consumers[$key]; if ($this->_debug()) { $this->_log("Using consumer: " . $key . " -> " . $Strategy); } $this->_options['endpoint'] = $this->_getEndpoint(); return new $Strategy($this->_options); } /** * Add an array representing a message to be sent to Mixpanel to a queue. * @param array $message */ public function enqueue($message = array()) { array_push($this->_queue, $message); // force a flush if we've reached our threshold if (count($this->_queue) > $this->_max_queue_size) { $this->flush(); } if ($this->_debug()) { $this->_log("Queued message: ".json_encode($message)); } } /** * Add an array representing a list of messages to be sent to Mixpanel to a queue. * @param array $messages */ public function enqueueAll($messages = array()) { foreach($messages as $message) { $this->enqueue($message); } } /** * Given an array of messages, persist it with the instantiated Persistence Strategy * @param $message * @return mixed */ protected function _persist($message) { return $this->_consumer->persist($message); } /** * Return the endpoint that should be used by a consumer that consumes messages produced by this producer. * @return string */ abstract function _getEndpoint(); } wp-media/wp-mixpanel/src/Classes/Producers/MixpanelPeople.php 0000644 00000025333 15151523436 0020310 0 ustar 00 <?php /** * Provides an API to create/update profiles on Mixpanel */ class WPMedia_Producers_MixpanelPeople extends WPMedia_Producers_MixpanelBaseProducer { /** * Internal method to prepare a message given the message data * @param $distinct_id * @param $operation * @param $value * @param null $ip * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found * @return array */ private function _constructPayload($distinct_id, $operation, $value, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = array( '$token' => $this->_token, '$distinct_id' => $distinct_id, '$time' => microtime(true), $operation => $value ); if ($ip !== null) $payload['$ip'] = $ip; if ($ignore_time === true) $payload['$ignore_time'] = true; if ($ignore_alias === true) $payload['$ignore_alias'] = true; return $payload; } /** * Set properties on a user record. If the profile does not exist, it creates it with these properties. * If it does exist, it sets the properties to these values, overwriting existing values. * @param string|int $distinct_id the distinct_id or alias of a user * @param array $props associative array of properties to set on the profile * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function set($distinct_id, $props, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = $this->_constructPayload($distinct_id, '$set', $props, $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Set properties on a user record. If the profile does not exist, it creates it with these properties. * If it does exist, it sets the properties to these values but WILL NOT overwrite existing values. * @param string|int $distinct_id the distinct_id or alias of a user * @param array $props associative array of properties to set on the profile * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function setOnce($distinct_id, $props, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = $this->_constructPayload($distinct_id, '$set_once', $props, $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Unset properties on a user record. If the profile does not exist, it creates it with no properties. * If it does exist, it unsets these properties. NOTE: In other libraries we use 'unset' which is * a reserved word in PHP. * @param string|int $distinct_id the distinct_id or alias of a user * @param array $props associative array of properties to unset on the profile * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function remove($distinct_id, $props, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = $this->_constructPayload($distinct_id, '$unset', $props, $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Increments the value of a property on a user record. If the profile does not exist, it creates it and sets the * property to the increment value. * @param string|int $distinct_id the distinct_id or alias of a user * @param $prop string the property to increment * @param int $val the amount to increment the property by * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function increment($distinct_id, $prop, $val, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = $this->_constructPayload($distinct_id, '$add', array("$prop" => $val), $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Adds $val to a list located at $prop. If the property does not exist, it will be created. If $val is a string * and the list is empty or does not exist, a new list with one value will be created. * @param string|int $distinct_id the distinct_id or alias of a user * @param string $prop the property that holds the list * @param string|array $val items to add to the list * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function append($distinct_id, $prop, $val, $ip = null, $ignore_time = false, $ignore_alias = false) { $operation = gettype($val) == "array" ? '$union' : '$append'; $payload = $this->_constructPayload($distinct_id, $operation, array("$prop" => $val), $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Adds a transaction to the user's profile for revenue tracking * @param string|int $distinct_id the distinct_id or alias of a user * @param string $amount the transaction amount e.g. "20.50" * @param null $timestamp the timestamp of when the transaction occurred (default to current timestamp) * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function trackCharge($distinct_id, $amount, $timestamp = null, $ip = null, $ignore_time = false, $ignore_alias = false) { $timestamp = $timestamp == null ? time() : $timestamp; $date_iso = date("c", $timestamp); $transaction = array( '$time' => $date_iso, '$amount' => $amount ); $val = array('$transactions' => $transaction); $payload = $this->_constructPayload($distinct_id, '$append', $val, $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Clear all transactions stored on a user's profile * @param string|int $distinct_id the distinct_id or alias of a user * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function clearCharges($distinct_id, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = $this->_constructPayload($distinct_id, '$set', array('$transactions' => array()), $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Delete this profile from Mixpanel * @param string|int $distinct_id the distinct_id or alias of a user * @param string|null $ip the ip address of the client (used for geo-location) * @param boolean $ignore_time If the $ignore_time property is true, Mixpanel will not automatically update the "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated with the current time * @param boolean $ignore_alias If the $ignore_alias property is true, an alias look up will not be performed after ingestion. Otherwise, a lookup for the distinct ID will be performed, and replaced if a match is found */ public function deleteUser($distinct_id, $ip = null, $ignore_time = false, $ignore_alias = false) { $payload = $this->_constructPayload($distinct_id, '$delete', "", $ip, $ignore_time, $ignore_alias); $this->enqueue($payload); } /** * Returns the "engage" endpoint * @return string */ function _getEndpoint() { return $this->_options['people_endpoint']; } } wp-media/wp-mixpanel/src/Classes/Producers/MixpanelEvents.php 0000644 00000014376 15151523436 0020335 0 ustar 00 <?php /** * Provides an API to track events on Mixpanel */ class WPMedia_Producers_MixpanelEvents extends WPMedia_Producers_MixpanelBaseProducer { /** * An array of properties to attach to every tracked event * @var array */ private $_super_properties = array("mp_lib" => "php"); /** * Track an event defined by $event associated with metadata defined by $properties * @param string $event * @param array $properties */ public function track($event, $properties = array()) { // if no token is passed in, use current token if (!isset($properties["token"])) $properties['token'] = $this->_token; // if no time is passed in, use the current time if (!isset($properties["time"])) $properties['time'] = microtime(true); $params['event'] = $event; $params['properties'] = array_merge($this->_super_properties, $properties); $this->enqueue($params); } /** * Register a property to be sent with every event. If the property has already been registered, it will be * overwritten. * @param string $property * @param mixed $value */ public function register($property, $value) { $this->_super_properties[$property] = $value; } /** * Register multiple properties to be sent with every event. If any of the properties have already been registered, * they will be overwritten. * @param array $props_and_vals */ public function registerAll($props_and_vals = array()) { foreach($props_and_vals as $property => $value) { $this->register($property, $value); } } /** * Register a property to be sent with every event. If the property has already been registered, it will NOT be * overwritten. * @param $property * @param $value */ public function registerOnce($property, $value) { if (!isset($this->_super_properties[$property])) { $this->register($property, $value); } } /** * Register multiple properties to be sent with every event. If any of the properties have already been registered, * they will NOT be overwritten. * @param array $props_and_vals */ public function registerAllOnce($props_and_vals = array()) { foreach($props_and_vals as $property => $value) { if (!isset($this->_super_properties[$property])) { $this->register($property, $value); } } } /** * Un-register an property to be sent with every event. * @param string $property */ public function unregister($property) { unset($this->_super_properties[$property]); } /** * Un-register a list of properties to be sent with every event. * @param array $properties */ public function unregisterAll($properties) { foreach($properties as $property) { $this->unregister($property); } } /** * Get a property that is set to be sent with every event * @param string $property * @return mixed */ public function getProperty($property) { return $this->_super_properties[$property]; } /** * Identify the user you want to associate to tracked events. The $anon_id must be UUID v4 format (optionally with the * prefix '$device:') and not already merged to an $identified_id. All identify calls with a new and valid $anon_id will * trigger a track $identify event, and merge to the $identified_id. * @param string|int $user_id * @param string|int $anon_id [optional] */ public function identify($user_id, $anon_id = null) { $this->register("distinct_id", $user_id); $UUIDv4 = '/^(\$device:)?[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*$/i'; if (!empty($anon_id)) { if (preg_match($UUIDv4, $anon_id) !== 1) { /* not a valid uuid */ error_log("Running Identify method (identified_id: $user_id, anon_id: $anon_id) failed, anon_id not in UUID v4 format"); } else { $this->track('$identify', array( '$identified_id' => $user_id, '$anon_id' => $anon_id )); } } } /** * An alias to be merged with the distinct_id. Each alias can only map to one distinct_id. * This is helpful when you want to associate a generated id (such as a session id) to a user id or username. * * Because aliasing can be extremely vulnerable to race conditions and ordering issues, we'll make a synchronous * call directly to Mixpanel when this method is called. If it fails we'll throw an Exception as subsequent * events are likely to be incorrectly tracked. * @param string|int $distinct_id * @param string|int $alias * @return array $msg * @throws Exception */ public function createAlias($distinct_id, $alias) { $msg = array( "event" => '$create_alias', "properties" => array("distinct_id" => $distinct_id, "alias" => $alias, "token" => $this->_token) ); // Save the current fork/async options $old_fork = isset($this->_options['fork']) ? $this->_options['fork'] : false; $old_async = isset($this->_options['async']) ? $this->_options['async'] : false; // Override fork/async to make the new consumer synchronous $this->_options['fork'] = false; $this->_options['async'] = false; // The name is ambiguous, but this creates a new consumer with current $this->_options $consumer = $this->_getConsumer(); $success = $consumer->persist(array($msg)); // Restore the original fork/async settings $this->_options['fork'] = $old_fork; $this->_options['async'] = $old_async; if (!$success) { error_log("Creating Mixpanel Alias (distinct id: $distinct_id, alias: $alias) failed"); throw new Exception("Tried to create an alias but the call was not successful"); } else { return $msg; } } /** * Returns the "events" endpoint * @return string */ function _getEndpoint() { return $this->_options['events_endpoint']; } } wp-media/wp-mixpanel/src/Classes/Base/MixpanelBase.php 0000644 00000004072 15151523436 0016637 0 ustar 00 <?php /** * This a Base class which all Mixpanel classes extend from to provide some very basic * debugging and logging functionality. It also serves to persist $_options across the library. * */ class WPMedia_Base_MixpanelBase { /** * Default options that can be overridden via the $options constructor arg * @var array */ private $_defaults = array( "max_batch_size" => 50, // the max batch size Mixpanel will accept is 50, "max_queue_size" => 1000, // the max num of items to hold in memory before flushing "debug" => false, // enable/disable debug mode "consumer" => "curl", // which consumer to use "host" => "api.mixpanel.com", // the host name for api calls "events_endpoint" => "/track", // host relative endpoint for events "people_endpoint" => "/engage", // host relative endpoint for people updates "groups_endpoint" => "/groups", // host relative endpoint for groups updates "use_ssl" => true, // use ssl when available "error_callback" => null // callback to use on consumption failures ); /** * An array of options to be used by the Mixpanel library. * @var array */ protected $_options = array(); /** * Construct a new MixpanelBase object and merge custom options with defaults * @param array $options */ public function __construct($options = array()) { $options = array_merge($this->_defaults, $options); $this->_options = $options; } /** * Log a message to PHP's error log * @param $msg */ protected function _log($msg) { $arr = debug_backtrace(); $class = $arr[0]['class']; $line = $arr[0]['line']; error_log ( "[ $class - line $line ] : " . $msg ); } /** * Returns true if in debug mode, false if in production mode * @return bool */ protected function _debug() { return isset($this->_options["debug"]) && $this->_options["debug"] == true; } } wp-media/wp-mixpanel/src/Optin.php 0000644 00000003574 15151523436 0013117 0 ustar 00 <?php declare(strict_types=1); namespace WPMedia\Mixpanel; class Optin { /** * The plugin slug. * * @var string */ private $plugin_slug; /** * The capability required to enable/disable the opt-in. * * @var string */ private $capability; /** * Constructor. * * @param string $plugin_slug The plugin slug. * @param string $capability The capability required to enable/disable the opt-in. */ public function __construct( string $plugin_slug, string $capability ) { $this->plugin_slug = $plugin_slug; $this->capability = $capability; } /** * Check if the opt-in is enabled. * * @return bool True if the opt-in is enabled, false otherwise. */ public function is_enabled(): bool { if ( ! current_user_can( $this->capability ) ) { return false; } $optin = get_option( $this->plugin_slug . '_mixpanel_optin', false ); if ( ! $optin ) { return false; } return true; } /** * Check if tracking is allowed. * * @return bool */ public function can_track(): bool { return (bool) get_option( $this->plugin_slug . '_mixpanel_optin', false ); } /** * Enable the opt-in. * * @return void */ public function enable(): void { if ( $this->is_enabled() ) { return; } update_option( $this->plugin_slug . '_mixpanel_optin', true ); /** * Fires when the Mixpanel opt-in status changes to enabled. * * @param bool $status The opt-in status. */ do_action( $this->plugin_slug . '_mixpanel_optin_changed', true ); } /** * Disable the opt-in. * * @return void */ public function disable(): void { if ( ! $this->is_enabled() ) { return; } delete_option( $this->plugin_slug . '_mixpanel_optin' ); /** * Fires when the Mixpanel opt-in status changes to disabled. * * @param bool $status The opt-in status. */ do_action( $this->plugin_slug . '_mixpanel_optin_changed', false ); } } wp-media/wp-mixpanel/src/Tracking.php 0000644 00000015024 15151523436 0013561 0 ustar 00 <?php declare(strict_types=1); namespace WPMedia\Mixpanel; use WPMedia_Mixpanel; class Tracking { const HOST = 'mixpanel-tracking-proxy-prod.public-default.live2-k8s-cph3.ingress.k8s.g1i.one'; /** * Mixpanel instance * * @var WPMedia_Mixpanel */ private $mixpanel; /** * Mixpanel token * * @var string */ protected $token; /** * Constructor * * @param string $mixpanel_token Mixpanel token. * @param mixed[] $options Options for Mixpanel instance. */ public function __construct( string $mixpanel_token, array $options = [] ) { $mixpanel_options = array_merge( [ 'host' => self::HOST, 'events_endpoint' => '/track/?ip=0', ], $options ); $this->token = $mixpanel_token; $this->mixpanel = WPMedia_Mixpanel::getInstance( $this->token, $mixpanel_options ); } /** * Check if debug mode is enabled * * @return bool */ private function is_debug(): bool { $debug = ( defined( 'WP_DEBUG' ) ? constant( 'WP_DEBUG' ) : false ) && ( defined( 'WP_DEBUG_LOG' ) ? constant( 'WP_DEBUG_LOG' ) : false ); /** * Filters whether Mixpanel debug mode is enabled. * * @param bool $debug Debug mode value. */ return apply_filters( 'wp_media_mixpanel_debug', $debug ); } /** * Log event to error log if debug mode is enabled * * @param string $event Event name. * @param mixed[] $properties Event properties. */ private function log_event( string $event, array $properties ): void { if ( ! $this->is_debug() ) { return; } error_log( 'Mixpanel event: ' . $event . ' ' . var_export( $properties, true ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_var_export } /** * Track an event in Mixpanel * * @param string $event Event name. * @param mixed[] $properties Event properties. */ public function track( string $event, array $properties ): void { $this->log_event( $event, $properties ); $this->mixpanel->track( $event, $properties ); } /** * Identify a user in Mixpanel * * @param string $user_id User ID. * * @return void */ public function identify( string $user_id ): void { $this->mixpanel->identify( $this->hash( $user_id ) ); } /** * Set a user property in Mixpanel * * @param string $user_id User ID. * @param string $property Property name. * @param mixed $value Property value. */ public function set_user_property( string $user_id, string $property, $value ): void { $this->mixpanel->people->set( $user_id, [ $property => $value, ], '0' ); } /** * Hash a value using sha224 * * @param string $value Value to hash. * * @return string */ public function hash( string $value ): string { return hash( 'sha224', $value ); } /** * Get the WordPress version * * @return string */ public function get_wp_version(): string { $version = preg_replace( '@^(\d\.\d+).*@', '\1', get_bloginfo( 'version' ) ); if ( null === $version ) { $version = '0.0'; } return $version; } /** * Get the PHP version * * @return string */ public function get_php_version(): string { $version = preg_replace( '@^(\d\.\d+).*@', '\1', phpversion() ); if ( null === $version ) { $version = '0.0'; } return $version; } /** * Get the active theme * * @return string */ public function get_current_theme(): string { $theme = wp_get_theme(); return $theme->get( 'Name' ); } /** * Get list of active plugins names * * @return string[] */ public function get_active_plugins(): array { $plugins = []; $active_plugins = (array) get_option( 'active_plugins', [] ); $all_plugins = get_plugins(); foreach ( $active_plugins as $plugin_path ) { if ( ! is_string( $plugin_path ) ) { continue; } if ( ! isset( $all_plugins[ $plugin_path ] ) ) { continue; } $plugins[] = $all_plugins[ $plugin_path ]['Name']; } return $plugins; } /** * Get the Mixpanel token * * @return string */ public function get_token(): string { return $this->token; } /** * Add the Mixpanel script & initialize it */ public function add_script(): void { ?> <!-- start Mixpanel --><script> const MIXPANEL_CUSTOM_LIB_URL = "https://<?php echo esc_js( self::HOST ); ?>/lib.min.js"; (function (f, b) { if (!b.__SV) { var e, g, i, h; window.mixpanel = b; b._i = []; b.init = function (e, f, c) { function g(a, d) { var b = d.split("."); 2 == b.length && ((a = a[b[0]]), (d = b[1])); a[d] = function () { a.push([d].concat(Array.prototype.slice.call(arguments, 0))); }; } var a = b; "undefined" !== typeof c ? (a = b[c] = []) : (c = "mixpanel"); a.people = a.people || []; a.toString = function (a) { var d = "mixpanel"; "mixpanel" !== c && (d += "." + c); a || (d += " (stub)"); return d; }; a.people.toString = function () { return a.toString(1) + ".people (stub)"; }; i = "disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking start_batch_senders people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split( " "); for (h = 0; h < i.length; h++) g(a, i[h]); var j = "set set_once union unset remove delete".split(" "); a.get_group = function () { function b(c) { d[c] = function () { call2_args = arguments; call2 = [c].concat(Array.prototype.slice.call(call2_args, 0)); a.push([e, call2]); }; } for ( var d = {}, e = ["get_group"].concat( Array.prototype.slice.call(arguments, 0)), c = 0; c < j.length; c++) b(j[c]); return d; }; b._i.push([e, f, c]); }; b.__SV = 1.2; e = f.createElement("script"); e.type = "text/javascript"; e.async = !0; e.src = "undefined" !== typeof MIXPANEL_CUSTOM_LIB_URL ? MIXPANEL_CUSTOM_LIB_URL : "file:" === f.location.protocol && "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//) ? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js" : "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"; g = f.getElementsByTagName("script")[0]; g.parentNode.insertBefore(e, g); } })(document, window.mixpanel || []); mixpanel.init( '<?php echo esc_js( $this->token ); ?>', { api_host: "https://<?php echo esc_js( self::HOST ); ?>", id: false, property_blacklist: ['$initial_referrer', '$current_url', '$initial_referring_domain', '$referrer', '$referring_domain'] } ); </script><!-- end Mixpanel --> <?php } } wp-media/wp-mixpanel/src/WPConsumer.php 0000644 00000003602 15151523436 0014060 0 ustar 00 <?php declare(strict_types=1); namespace WPMedia\Mixpanel; use WPMedia_ConsumerStrategies_AbstractConsumer; /** * Consumes messages and sends them to a host/endpoint using WordPress's HTTP API */ class WPConsumer extends WPMedia_ConsumerStrategies_AbstractConsumer { /** * The host to connect to (e.g. api.mixpanel.com) * * @var string */ protected $host; /** * The host-relative endpoint to write to (e.g. /engage) * * @var string */ protected $endpoint; /** * The maximum number of seconds to allow the call to execute. Default is 30 seconds. * * @var int */ protected $timeout; /** * The protocol to use for the cURL connection * * @var string */ protected $protocol; /** * Creates a new WPConsumer and assigns properties from the $options array * * @param array{host:string, endpoint:string, timeout?: int, use_ssl?: bool} $options Options for the consumer. */ public function __construct( $options ) { parent::__construct( $options ); $this->host = $options['host']; $this->endpoint = $options['endpoint']; $this->timeout = isset( $options['timeout'] ) ? $options['timeout'] : 30; $this->protocol = isset( $options['use_ssl'] ) && ( true === $options['use_ssl'] ) ? 'https' : 'http'; } /** * Send post request to the given host/endpoint using WordPress's HTTP API * * @param mixed[] $batch Batch of data to send to mixpanel. * * @return bool */ public function persist( $batch ) { if ( count( $batch ) <= 0 ) { return true; } $url = $this->protocol . '://' . $this->host . $this->endpoint; $data = 'data=' . $this->_encode( $batch ); $response = wp_remote_post( $url, [ 'timeout' => $this->timeout, 'body' => $data, ] ); if ( is_wp_error( $response ) ) { $this->_handleError( $response->get_error_code(), $response->get_error_message() ); return false; } return true; } }