version;
$basename = plugin_basename(ACCESSIBLEREADING_FILE);
$path = plugin_dir_path(ACCESSIBLEREADING_FILE);
$url = plugin_dir_url(ACCESSIBLEREADING_FILE);
$slug = dirname($basename);
$slug_underscore = str_replace('-', '_', $slug);
$this->settings = array(
// Basics
'name' => __('Accessible Reading', $slug),
'version' => $version,
'capability_post' => 'edit_post',
'capability_settings' => 'manage_options',
// URLs
'file' => ACCESSIBLEREADING_FILE,
'basename' => $basename, // E.g.: "plugin-folder/file.php"
'path' => $path, // E.g.: "/path/to/wp-content/plugins/plugin-folder/"
'url' => $url, // E.g.: "https://domain.com/wp-content/plugins/plugin-folder/"
'admin_url' => admin_url(sprintf('tools.php?page=%s', $slug)), // E.g.: "https://domain.com/wp-admin/tools.php?page=plugin-folder"
'slug' => $slug, // E.g.: "plugin-folder"
'prefix' => $slug_underscore . '_', // E.g.: "plugin_folder_"
'group' => $slug . '-group', // E.g.: "plugin-folder-group"
//Plugin-specific Settings
'hook' => $slug_underscore,
'schedule' => 1,
//Plugin-specific Options
'options' => array(
'api_key' => array(
'label' => __('API Key', $slug),
'description' => sprintf(
'%s %s',
esc_url(sprintf(
'https://tessawatkins.com/click/?utm_source=%s&utm_medium=website&utm_campaign=wordpress-plugin&utm_content=%s&utm_term=',
str_replace(array('https://', 'http://'), '', home_url()), //UTM Source
$slug //UTM Content
) . 'get-bionic-reading-api-key&redirect=' . urlencode('https://tessawatkins.com/accessible-reading-api-key/')),
__('Get an API key.', $slug),
__('Free and paid versions are available.', $slug)
),
'default' => '',
'global_override' => true, //Allow to be overriden by constant variable in wp-config.php
'private' => true, //Don't display value in dashboard if set in wp-config.php
'atts' => array(
'type' => 'text',
'required' => 'required'
)
),
'api_plan' => array(
'label' => __('Plan', $slug),
'description' => __('Select the plan that your API key is subscribed to. This will determine your API request limits. If unsure, choose "Basic."', $slug),
'default' => 'basic',
'global_override' => true, //Allow to be overriden by constant variable in wp-config.php
'private' => false, //Don't display value in dashboard if set in wp-config.php
'atts' => array(
'type' => 'select',
'required' => 'required',
'options' => array(
//Pricing Structure: https://rapidapi.com/bionic-reading-bionic-reading-default/api/bionic-reading1/pricing
'basic' => array(
'label' => __('Basic', $slug), //Plan Name
'daily_request' => 500, //Daily API Request Limit
'char' => 1000 //Character length request limit
),
'pro' => array(
'label' => __('Pro', $slug), //Plan Name
'daily_request' => 20000, //Daily API Request Limit
'char' => 10000 //Character length request limit
)
)
)
),
'fixation' => array(
'label' => __('Fixation', $slug),
'description' => __('Define the expression of the letter combinations.', $slug),
'default' => 1,
'global_override' => true, //Allow to be overriden by constant variable in wp-config.php
'atts' => array(
'type' => 'number',
'min' => 1,
'max' => 5,
'step' => 1,
'required' => 'required'
)
),
'saccade' => array(
'label' => __('Saccade', $slug),
'description' => __('Define the visual jumps from fixation to fixation.', $slug),
'default' => '10',
'global_override' => true, //Allow to be overriden by constant variable in wp-config.php
'atts' => array(
'type' => 'number',
'min' => 10,
'max' => 50,
'step' => 10,
'required' => 'required'
)
),
'toggle_switch' => array(
'label' => __('Toggle Switch Default Setting', $slug),
'description' => __('Choose the default setting for the toggle switch.', $slug),
'default' => 0,
'global_override' => false, //Allow to be overriden by constant variable in wp-config.php
'private' => false, //Don't display value in dashboard if set in wp-config.php
'atts' => array(
'type' => 'switch',
'required' => 'required',
'options' => array(
'0' => array(
'label' => __('Disabled', $slug)
),
'1' => array(
'label' => __('Enabled', $slug)
)
)
)
),
'bulk_update_posts' => array(
'default' => '',
'atts' => array(
'type' => 'hidden'
)
),
'daily_limit_tracker' => array(
'default' => '',
'atts' => array(
'type' => 'hidden'
)
),
//Allowing other post types is coming soon
'post_types' => array(
'default' => 'post',
'atts' => array(
'type' => 'hidden'
)
)
),
//Post-level Options
'post_options' => array(
'enabled' => array(
'label' => __('Allow Processing', $slug),
'description' => __('Opt this post out from being processed for accessible reading. This will also prevent the toggle switch from being shown to visitors.', $slug),
'default' => 1,
'atts' => array(
'type' => 'select',
'required' => 'required',
'options' => array(
'1' => array(
'label' => __('Enabled', $slug)
),
'0' => array(
'label' => __('Disabled', $slug)
)
)
)
),
'toggle_switch' => array(
'label' => __('Toggle Switch Default Setting', $slug),
'description' => __('Choose the default setting for the toggle switch. This will have no effect if processing is disabled for this post.', $slug),
'default' => 'global',
'atts' => array(
'type' => 'select',
'required' => 'required',
'options' => array(
'global' => array(
'label' => __('Use Global Setting', $slug)
),
'0' => array(
'label' => __('Disabled', $slug)
),
'1' => array(
'label' => __('Enabled', $slug)
)
)
)
)
)
);
//Plugin Setup
add_action('admin_init', array($this, 'register_settings')); //Register plugin option settings
add_action('admin_menu', array($this, 'admin_menu')); //Add admin page link in WordPress dashboard
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts')); //Enqueue styles/scripts for admin page
add_filter('plugin_action_links_' . $basename, array($this, 'plugin_links')); //Add link to admin page from plugins page
//register_activation_hook(ACCESSIBLEREADING_FILE, array($this, 'activate')); //Add activation hook
load_plugin_textdomain($slug, false, $slug . '/languages/'); //Translations
//Plugin-specific Actions
add_action('add_meta_boxes', array($this, 'add_metabox')); //Add metabox to posts dashboard pages
add_action('save_post', array($this, 'save_post'), 5, 3); //Save accessible reading meta on post save
add_action('post_updated', array($this, 'update_post'), 5, 3); //Update accessible reading meta on post update
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'), 20); //Enqueue styles for frontend
add_action('wp_ajax_start_bulk_update', array($this, 'bulk_start')); //Add AJAX call for logged in users to bulk save from admin page
add_action('wp_ajax_estimate_post', array($this, 'estimate_post')); //Add AJAX call for logged in users to estimate a single post
add_action($slug_underscore, array($this, 'bulk_event'), 10, 3); //Add custom CRON scheduler action
//Plugin-specific Filters
add_filter('the_content', array($this, 'display_frontend'), 15); //display on frontend
}
//**** Plugin Settings ****//
/**
* Register Plugin Settings
*
* @since 1.0.0
*/
public function register_settings()
{
//Register the section
add_settings_section(
$this->settings['group'], //Slug-name to identify the section. Used in the `id` attribute of tags.
__('Settings', $this->settings['slug']), //Formatted title of the section. Shown as the heading for the section.
array($this, 'display_plugin_setting_section'), //Function that echos out any content at the top of the section (between heading and fields).
$this->settings['slug'] //The slug-name of the settings page on which to show the section.
);
//Register the individual settings in the section
foreach ($this->settings['options'] as $setting_name => $setting_data) {
$setting_id = $this->settings['prefix'] . esc_attr($setting_name);
register_setting($this->settings['group'], $setting_id); //Register the setting
//Add the field to the admin settings page (excluding the hidden ones)
$type = esc_attr($setting_data['atts']['type']);
if ($type != 'hidden') {
$atts = array(
'type' => $type,
'name' => $setting_id,
'id' => $setting_id,
'value' => esc_attr(get_option($setting_id, esc_attr($setting_data['default']))), //The currently selected value (or default if not selected)
'label' => esc_attr($setting_data['label']),
'description' => $this->array_has_key('description', $setting_data),
'required' => esc_attr($this->array_has_key('required', $setting_data['atts'])),
'global' => $this->array_has_key('global_override', $setting_data) ? strtoupper($setting_id) : '', //Name of constant variable should it exist
'private' => $this->array_has_key('private', $setting_data)
);
switch ($type) {
case 'select':
$atts['options'] = $setting_data['atts']['options'];
break;
case 'checkbox':
case 'switch':
$atts['checked'] = checked(1, $atts['value'], false);
$atts['reverse'] = $this->array_has_key('reverse', $setting_data['atts']);
$atts['yes'] = $this->array_has_key('yes', $setting_data['atts'], __('On', $this->settings['slug']));
$atts['no'] = $this->array_has_key('no', $setting_data['atts'], __('Off', $this->settings['slug']));
break;
case 'number':
$atts['min'] = $this->array_has_key('min', $setting_data['atts']);
$atts['max'] = $this->array_has_key('max', $setting_data['atts']);
$atts['step'] = $this->array_has_key('step', $setting_data['atts']);
//Purposely not breaking here
default:
$atts['placeholder'] = esc_attr($this->array_has_key('placeholder', $setting_data['atts']));
break;
}
add_settings_field(
$setting_id, //ID
esc_attr($setting_data['label']), //Title
array($this, 'display_plugin_setting'), //Callback (should echo its output)
$this->settings['slug'], //Page
$this->settings['group'], //Section
$atts //Attributes
);
}
}
}
/**
* Register Plugin Setting Section Callback
*
* @since 1.0.0
*/
public function display_plugin_setting_section()
{
//Do nothing
}
/**
* Display plugin setting input in admin dashboard
*
* Callback for `add_settings_field()`
*
* @since 1.0.0
* @param array $args
*/
public function display_plugin_setting($args = array())
{
/**
* Variables that are already escaped:
* type, name, id, value, label, required, global, private, checked, min, max, step, placeholder
*/
if ($args['global'] && defined($args['global'])) {
//Display constant values set in wp-config.php
if ($args['private']) {
//Don't reveal if private
printf(
''
);
} else {
//Not editable
printf(
'',
esc_attr(constant($args['global']))
);
}
} else {
//Render the setting
$input_value = $args['value'];
switch ($args['type']) {
case 'hidden':
//Silence is golden
break;
case 'select':
printf(
'',
$args['id'],
$args['name'],
$args['required'] ? ' required="required"' : ''
);
foreach ($args['options'] as $key => $value) {
$option_value = esc_attr($key);
if (is_array($value)) {
$value = $value['label'];
}
printf(
'',
$option_value,
esc_attr($value),
$input_value == $option_value ? ' selected' : ''
);
}
echo ('');
break;
case 'checkbox':
printf(
'',
$args['type'],
$args['name'],
$args['id'],
$args['checked']
);
break;
case 'switch':
$value = $args['value'];
$reverse = esc_attr($args['reverse']);
printf(
'
%4$s
%5$s
',
$args['name'], //1 - Input name
$value, //2 - Input value
checked($reverse ? '0' : '1', $value, false), //3 - Checked attribute, if reversed, compare against the opposite value
esc_attr($args['no']), //4 - on value
esc_attr($args['yes']), //5 - off value
$args['label'], //6 - label
$reverse ? ' reverse-checkbox' : '' //7 - whether checkbox should be visibly reversed
);
break;
case 'number':
printf(
'',
$args['type'],
$args['id'],
$args['name'],
$input_value,
$args['placeholder'],
$args['required'] ? ' required="required"' : '',
$args['min'] ? sprintf(' min="%s"', $args['min']) : '',
$args['max'] ? sprintf(' max="%s"', $args['max']) : '',
$args['step'] ? sprintf(' step="%s"', $args['step']) : ''
);
break;
default:
printf(
'',
$args['type'],
$args['id'],
$args['name'],
$input_value,
$args['placeholder'],
$args['required'] ? ' required="required"' : ''
);
break;
}
}
if ($args['description']) {
printf('
%s', $args['description']);
}
}
/**
* Get Option Key for Settings
*
* @since 1.1.0
* @return string $id With or without a prefix, get the option name and ID
* @return array an associative array with `id` and `name` properties
*/
private function get_setting_key($id)
{
$return = array(
'id' => '',
'name' => ''
);
if (strpos($id, $this->settings['prefix']) === 0) {
//Prefix is included
$return['id'] = $id; //No change, keep prefix in ID
$return['name'] = str_replace($this->settings['prefix'], '', $id); //Remove prefix from name
} else {
//Prefix is not included
$return['name'] = $id; //No change, no prefix in name
$return['id'] = $this->settings['prefix'] . $id; //Add prefix to ID
}
return $return;
}
/**
* Get Plugin Setting
*
* This checks if a constant value was defined to override it and returns that.
*
* @since 1.0.0
* @param string $id Option ID, including prefix
* @param bool $value_only If true, returns just the value of the setting. Otherwise,
* it returns an associatve array. Default is true.
* @return string|array An associative array with the keys `value` and `constant`
* unless $value_only was true, then it returns just the value.
*/
private function get_setting($id, $value_only = true)
{
$return = array(
'value' => '',
'constant' => false
);
$setting = $this->get_setting_key($id);
$const_name = $this->array_has_key('global_override', $this->settings['options'][$setting['name']]) ? strtoupper($setting['id']) : '';
if ($const_name && defined($const_name)) {
//Display the value overriden by the constant value
$return['value'] = constant($const_name);
$return['constant'] = true;
} else {
$return['value'] = esc_attr(get_option($setting['id'], esc_attr($this->settings['options'][$setting['name']]['default'])));
}
//$this->debug_log($return, 'Getting Setting [' . $setting['id'] . ']');
if ($value_only) {
return $return['value'];
}
return $return;
}
/**
* Set Plugin Setting
*
* @since 1.1.0
* @param string $id With or without the prefix
* @param mixed $value
* @return bool True on success, false on failure
*/
private function set_setting($id, $value)
{
$setting = $this->get_setting_key($id);
$this->debug_log($value, 'Updating Option: ' . $setting['id']);
$updated = update_option($setting['id'], $value);
$this->debug_log($updated ? 'Updating success' : 'Updating failed');
return $updated;
}
/**
* Set Single Meta Data
*
* @since 1.3.0
* @param int $post_id Post ID
* @param string $key The meta key to set
* @param mixed $value The meta value to set
* @param string $post_type Optional. The post type to retrieve. Default is `post`.
* @return mixed The meta key value that was set
*/
private function set_meta($post_id, $key, $value, $post_type = 'post')
{
update_metadata($post_type, $post_id, $this->settings['prefix'] . $key, $value);
}
/**
* Get Single Meta Data
*
* @since 1.3.0
* @param int $post_id Post ID
* @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
* @param mixed $default Optional. The default value to return if not set. Default is an empty string.
* @param string $post_type Optional. The post type to retrieve. Default is `post`.
* @return mixed The value of the meta field or default if it's not explicity false as a bool or integer.
*/
private function get_meta($post_id, $key = '', $default = '', $post_type = 'post')
{
if (!$post_type || !is_numeric($post_id) || $post_id <= 0) {
return $default;
}
$key = $key ? $this->settings['prefix'] . $key : '';
$value = get_metadata($post_type, $post_id, $key, true);
//If value is set or if it is set to some falsey things on purpose
if ($value || is_bool($value) || is_numeric($value)) {
return $value;
}
return $default;
}
/**
* Get Plan
*
* @since 1.2.0
* @param string $plan Optional. Options are `basic` or `pro`. If left empty, it will look it up.
* @return string `basic` or `pro`
*/
public function get_plan($plan = false)
{
$plan = $plan ? $plan : $this->get_setting('api_plan');
if ($this->array_has_key($plan, $this->settings['options']['api_plan']['atts']['options'])) {
return $plan;
}
return 'basic'; //Default to the basic plan
}
/**
* Get Daily API Request Limit
*
* @since 1.1.0
* @param string $plan Optional. Options are `basic` or `pro`. If left empty, it will look it up.
* @return int The daily request limit based on the API plan setting
*/
public function get_daily_limit($plan = false)
{
$plan = $this->get_plan($plan);
return $this->settings['options']['api_plan']['atts']['options'][$plan]['daily_request'];
}
/**
* Get API Character Processing Limit
*
* @since 1.1.0
* @param string $plan Optional. Options are `basic` or `pro`. If left empty, it will look it up.
* @return int The maximum character processing limit based on the API plan setting
*/
private function get_character_limit($plan = false)
{
$plan = $this->get_plan($plan);
$buffer = 50; // add an arbitrary buffer for when we chunk it later, we'll separate by word, not letter
return $this->settings['options']['api_plan']['atts']['options'][$plan]['char'] - $buffer;
}
/**
* Set Daily Limit Tracker
*
* @since 1.1.0
* @param array|false $obj
* @return array an associative array with `count` (int) and `date` (int strtotime() timestamp) keys
*/
private function set_daily_limit_tracker($obj)
{
if (!is_array($obj)) {
//Reset counter
$obj = array('count' => 0, 'date' => '');
}
$this->set_setting('daily_limit_tracker', json_encode($obj, JSON_HEX_QUOT)); //Save it, looks something like {"count":1,"date":1654283454}
return $obj;
}
/**
* Get Daily Limit Tracker
*
* @since 1.1.0
* @return array an associative array with `count` (int) and `date` (int strtotime() timestamp) keys
*/
public function get_daily_limit_tracker()
{
$count = $this->get_setting('daily_limit_tracker', true);
if ($count) {
$count = json_decode(html_entity_decode($count), true, 512, JSON_HEX_QUOT);
if (is_array($count)) {
return $count;
}
}
return array('count' => 0, 'date' => '');
}
/**
* Check If Within Daily API Request Limit
*
* @param string $plan Optional. Options are `basic` or `pro`. If left empty, it will look it up.
* @param int $buffer Optional. For automated processes, we add a buffer to not use up all of today's requests.
* @param int|false $check Optional. Pass a number of proposed requests to see if you'd still be within the limit.
* @return bool Returns true if we can make more API requests today. False otherwise.
*/
public function is_within_daily_limit($plan = false, $buffer = 0, $check = false)
{
$count = $this->get_daily_limit_tracker();
$this->debug_log($plan, 'Bionic Reading API Plan');
$this->debug_log($count, 'Bionic Reading API Count');
if (is_numeric($count['count']) && $count['count']) {
$now = strtotime('now');
$this->debug_log($now, 'Now');
$this->debug_log($count['date'], 'Last API Request');
$this->debug_log(DAY_IN_SECONDS, 'Day, in seconds');
if (strtotime('now') - $count['date'] >= DAY_IN_SECONDS) {
$this->debug_log('It has been 24 hours since the last API request, reset the API counter and allow requests');
$this->set_daily_limit_tracker(false);
return true;
}
$limit = $this->get_daily_limit($plan) - $buffer;
$this->debug_log($limit, 'Check if we are within the daily limit');
return (is_numeric($check) ? $count['count'] + $check : $count['count']) <= $limit;
}
//No API calls have been made
return true;
}
/**
* Get Allowed Post Types
*
* @since 1.3.0
* @return array a sequential array of post types
*/
private function get_post_types()
{
$types = $this->get_setting('post_types', true);
if (!$types) {
$types = $this->settings['options']['post_types']['default'];
}
return explode(',', $types);
}
//**** Plugin Management Page ****//
/**
* Add Admin Page.
*
* Adds the admin page to the WordPress dashboard under "Tools".
*
* @since 1.0.0
*/
public function admin_menu()
{
add_management_page(
$this->settings['name'],
$this->settings['name'],
$this->settings['capability_settings'],
$this->settings['slug'],
array(&$this, 'admin_page')
);
}
/**
* Plugin Links
*
* Links to display on the plugins page.
*
* @since 1.0.0
* @param array $links
* @return array A list of links
*/
public function plugin_links($links)
{
$settings_link = sprintf(
'%s',
$this->settings['admin_url'],
__('Settings', $this->settings['slug'])
);
array_unshift($links, $settings_link);
return $links;
}
/**
* Admin Scripts and Styles
*
* Enqueue scripts and styles to be used on the admin pages
*
* @since 1.0.0
* @param string $hook Hook suffix for the current admin page
*/
public function admin_enqueue_scripts($hook)
{
$minified = $this->debug ? '' : '.min'; //Use minified files in production, unminified if debugging
if ($hook == 'tools_page_' . $this->settings['slug']) {
// Load only on our plugin page (a subpage of "Tools")
//Plugin Stylesheets
wp_enqueue_style(
$this->settings['prefix'] . 'layout',
$this->settings['url'] . 'assets/styles/pseudo-bootstrap' . $minified . '.css',
array(),
$this->settings['version']
);
wp_enqueue_style(
$this->settings['prefix'] . 'dashboard',
$this->settings['url'] . 'assets/styles/admin-dashboard' . $minified . '.css',
array($this->settings['prefix'] . 'layout'),
$this->settings['version']
);
//Plugin Scripts
wp_enqueue_script('jquery');
wp_enqueue_script(
$this->settings['prefix'] . 'dashboard',
$this->settings['url'] . 'assets/scripts/admin-dashboard' . $minified . '.js',
array('jquery'),
$this->settings['version'],
true
);
wp_localize_script(
$this->settings['prefix'] . 'dashboard',
'tw_ajax_object',
array(
'ajax_url' => admin_url('admin-ajax.php'),
'text' => array(
'processing_cancelled' => __('Processing canceled', $this->settings['slug'])
)
)
);
} else {
// Load only on the new/edit pages for the appropriate post types
$post_types = $this->get_post_types();
foreach ($post_types as $post_type) {
$edit_hook = $post_type . '.php';
$new_hook = $post_type . '-new.php';
if ($hook == $new_hook || $hook == $edit_hook) {
//Stylesheets
wp_enqueue_style(
$this->settings['prefix'] . 'metabox',
$this->settings['url'] . 'assets/styles/admin-metabox' . $minified . '.css',
array(),
$this->settings['version']
);
//Scripts
wp_enqueue_script('jquery');
wp_enqueue_script(
$this->settings['prefix'] . 'metabox',
$this->settings['url'] . 'assets/scripts/admin-metabox' . $minified . '.js',
array('jquery'),
$this->settings['version'],
true
);
wp_localize_script(
$this->settings['prefix'] . 'metabox',
'tw_ajax_object',
array('ajax_url' => admin_url('admin-ajax.php'))
);
return;
}
}
}
}
/**
* Display Admin Page
*
* HTML markup for the WordPress dashboard admin page for managing this plugin's settings.
*
* @since 1.0.0
*/
public function admin_page()
{
//Prevent unauthorized users from viewing the page
if (!current_user_can($this->settings['capability_settings'])) {
return;
}
load_template($this->settings['path'] . 'templates/dashboard-admin.php', true, $this->settings);
}
//**** Post Management Page ****//
/**
* Add Metabox
*
* Adds a metabox to the edit pages of the posts of the appropriate post type
*
* @since 1.3.0
*/
public function add_metabox()
{
$post_types = $this->get_post_types();
foreach ($post_types as $post_type) {
add_meta_box(
$this->settings['slug'], // Unique ID
$this->settings['name'], // Box title
array($this, 'display_metabox'), // Content callback, must be of type callable
$post_type // Post type
);
}
}
/**
* Display Metabox
*
* HTML markup for the metabox used to manage this plugin at the post level
*
* @since 1.3.0
* @param WP_Post $post Post Object.
*/
public function display_metabox($post)
{
//Prevent unauthorized users from viewing the page
if (!current_user_can($this->settings['capability_post'], $post->ID)) {
return;
}
//Get the post-level meta field HTML
$fields = array();
foreach ($this->settings['post_options'] as $option => $option_settings) {
switch ($option_settings['atts']['type']) {
case 'select':
$fields[$option] = array(
'input' => $this->get_dropdown(array(
'name' => $option,
'value' => $this->get_meta(
$post->ID,
$option,
$option_settings['default'],
$post->post_type
),
'label' => $option_settings['label'],
'options' => $option_settings['atts']['options']
)),
'label' => $option_settings['label'],
'description' => $option_settings['description']
);
break;
default:
//Might make other types later, IDK
break;
}
}
//Load the template file
load_template($this->settings['path'] . 'templates/edit-metabox.php', true, array(
'post' => array('ID' => $post->ID, 'type' => $post->post_type),
'plugin_settings' => $this->settings,
'api_request_count' => $this->get_daily_limit_tracker()['count'],
'api_request_limit' => $this->get_daily_limit(),
'api_request_estimate' => sprintf(
__('This post will use approximately %s API request(s) to process accessible content due to the character limitations.', $this->settings['slug']),
$this->get_post_estimate(
$post->ID,
'',
true,
true,
$post->post_type
)
),
'fields' => $fields
));
}
/**
* Save Post
*
* When creating a new post, update the accessible reading content
*
* @since 1.0.0
* @param integer $post_id Post ID.
* @param WP_Post $post Post object
* @param integer $update If post is being updated, 1 is passed. Otherwise 0.
*/
public function save_post($post_id, $post, $update)
{
$this->debug_log(' ');
if (!in_array($post->post_type, $this->get_post_types())) {
$this->debug_log('Acessible Reading: Save Post - the post type [' . $post->post_type . '] is not allowed, do nothing');
return; //If this is an update, do nothing
} elseif (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
$this->debug_log('Acessible Reading: Save Post - autosaving, do nothing');
return; //Autosave, do nothing
} elseif (defined('DOING_AJAX') && DOING_AJAX) {
$this->debug_log('Acessible Reading: Save Post - doing AJAX, do nothing');
return; // AJAX call, do nothing
} elseif (!current_user_can($this->settings['capability_post'], $post_id)) {
$this->debug_log('Acessible Reading: Save Post - user does not have permission, do nothing');
return; // If user does not have permissions, do nothing
} elseif ($update) {
$this->debug_log('Acessible Reading: Save Post - updating, do nothing');
return; //If this is an update, do nothing
}
//Update the fields in the metabox
$this->debug_log('Acessible Reading: Save Post - updating post meta...');
$this->update_post_meta($post_id, $_POST, $post->post_type);
//Continue checking if accessible content needs to be created
if (!$this->get_meta($post_id, 'enabled', $this->settings['post_options']['enabled']['default'], $post->post_type)) {
$this->debug_log('Acessible Reading: Save Post - this post is disabled, do nothing');
return;
}
$this->debug_log('Acessible Reading: Save Post - creating accessible content');
$this->process_post($post_id, $post->post_content, $post->post_type);
}
/**
* Update Post
*
* @since 1.0.0
* @param int $post_id Post ID
* @param WP_Post $post_after Post object following the update
* @param WP_Post $post_before Post object before the update
*/
public function update_post($post_id, $post_after, $post_before)
{
$this->debug_log(' ');
if (!in_array($post_before->post_type, $this->get_post_types())) {
$this->debug_log('Acessible Reading: Update Post - the post type [' . $post_before->post_type . '] is not allowed, do nothing');
return;
}
//Update the fields in the metabox
$this->debug_log('Acessible Reading: Update Post - updating post meta...');
$this->update_post_meta($post_id, $_POST, $post_after->post_type);
//Continue checking if accessible content needs to be created
if ($post_before->post_content == $post_after->post_content && $this->get_content($post_id)) {
$this->debug_log('Acessible Reading: Update Post - body content is the same and meta content exists, do nothing');
return;
} elseif (!$this->get_meta($post_id, 'enabled', 1, $post_after->post_type)) {
$this->debug_log('Acessible Reading: Update Post - this post is disabled, do nothing');
return;
}
$this->debug_log('Acessible Reading: Update Post - creating accessible content');
$this->process_post($post_id, $post_after->post_content, $post_after->post_type);
}
/**
* Update Post Meta
*
* @since 1.3.0
* @param int $post_id Post ID
* @param array $args Post args
* @param string $post_type
*/
private function update_post_meta($post_id, $args, $post_type = 'post')
{
if (is_array($args) && count($args)) {
//Loop through post-level options
foreach ($this->settings['post_options'] as $option => $option_settings) {
$this->set_meta(
$post_id,
$option,
$this->array_has_key($this->settings['prefix'] . $option, $args, $option_settings['default']),
$post_type
);
}
}
}
//**** Frontend & Shortcode ****//
/**
* Enqueue Frontend Styles and Scripts.
*
* @since 1.0.0
*/
public function enqueue_scripts()
{
$minified = $this->debug ? '' : '.min'; //Use minified files in production, unminified if debugging
//Enqueue the frontend stylesheet
wp_enqueue_style(
$this->settings['slug'],
$this->settings['url'] . 'assets/styles/accessible-reading' . $minified . '.css',
array(),
$this->settings['version']
);
//Register and enqueue frontend scripts
wp_enqueue_script(
$this->settings['slug'],
$this->settings['url'] . 'assets/scripts/accessible-reading' . $minified . '.js',
array(),
$this->settings['version'],
true
);
}
/**
* Display Switch Toggle HTML
*
* @since 1.0.0
* @param array $args An associatve array with keys for `name` (string), `value`
* (string of `true` or `false`), `yes` (string), `no` (string), `label`, and
* `reverse` (bool)
* @return string HTML for the checkbox switch
*/
private function get_checkbox_switch($args)
{
$value = esc_attr($args['value']);
$reverse = esc_attr($args['reverse']);
return sprintf(
'
%4$s
%5$s
',
esc_attr($args['name']), //1 - Input name
$value, //2 - Input value
checked($reverse ? '0' : '1', $value, false), //3 - Checked attribute, if reversed, compare against the opposite value
esc_attr($args['no']), //4 - on value
esc_attr($args['yes']), //5 - off value
$reverse ? ' reverse-checkbox' : '' //6 - whether checkbox should be visibly reversed
);
}
/**
* Display Dropdown HTML
*
* @since 1.3.0
* @param array $args An associatve array with keys for `name` (string), `value`
* (string of `true` or `false`), `yes` (string), `no` (string), and `label` (string)
* @return string HTML for the checkbox switch
*/
private function get_dropdown($args)
{
$value = esc_attr(strval($args['value']));
$html = sprintf(
'';
return $html;
}
/**
* Frontend Display
*
* Display the swap button on the frontend of a post
*
* @since 1.0.0
* @param string $content. Post content.
* @return string Modified post content.
*/
public function display_frontend($content = '')
{
if (is_singular($this->get_post_types())) {
$post_id = get_the_ID();
$post_type = get_post_type($post_id);
//Do not continue if disabled at the post level
if ($this->get_meta($post_id, 'enabled', $this->settings['post_options']['enabled']['default'], $post_type)) {
$accessible_content = $this->get_content($post_id);
if ($accessible_content) {
return sprintf(
'%s
' . $return['output'] . '
'; } elseif ($already_processing) { $return['output'] .= ' ' . sprintf( __('Processing is already in progress.', $this->settings['slug']), $estimation['crons'] ); $return['output'] = '' . $return['output'] . '
'; } else { //Process posts $updated = $this->set_setting('bulk_update_posts', implode(',', $estimation['post_ids'])); if ($updated) { $this->debug_log('Successfully updated post IDs meta'); $return['messages'][] = 'Successfully updated post IDs meta'; } else { $this->debug_log('Post IDs option failed to update (usually because the value did not change)'); $return['messages'][] = 'Post IDs option failed to update (usually because the value did not change)'; } //Schedule first CRON event $this->schedule_event(array( 'start' => 0, 'end' => $end, 'batch_limit' => $batch_limit, 'daily_limit' => $daily_limit ), $same_day); $return['output'] .= ' ' . sprintf( __('The bulk updater has been started and will take approximately %s minutes to complete. Processing takes place in the background so you can safely leave this page.', $this->settings['slug']), $estimation['crons'] ); $return['output'] = '' . $return['output'] . '
'; } } else { $return['error']++; $return['messages'][] = 'Either the batch limit or daily limit were invalid, or the batch limit was greater than the daily limit. Please check settings.'; } } else { $return['error']++; $return['messages'][] = 'Posted fields were empty!'; } $this->processing_bulk = false; wp_die(json_encode($return)); } /** * Schedule Bulk Event * * @since 1.1.0 * @param array $event_args An associatve array with `start`, `end`, `batch_limit`, and `daily_limit` keys that all have integer values. * @param bool $same_day If true, will schedule the next batch in a few minutes. If false, 24 hours. */ private function schedule_event($event_args, $same_day = true) { $time = $same_day ? '+' . $this->settings['schedule'] . ' minutes' : '+ 1 days'; $scheduled = wp_schedule_single_event( strtotime($time), //time $this->settings['hook'], //event hook $event_args //event args ); if ($scheduled) { $this->debug_log('Cron Event Scheduled Successfully: [' . $this->settings['hook'] . '] for [' . $time . '] ' . json_encode($event_args, JSON_PRETTY_PRINT)); } else { $this->debug_log('Cron Event Failed to Schedule: [' . $this->settings['hook'] . '] for [' . $time . '] ' . json_encode($event_args, JSON_PRETTY_PRINT)); } } /** * Bulk Update * * CRON event. This updates a set amount of posts from * the saved IDs in options based on the parameters. * * @since 1.1.0 * @param int $start The index of the post IDs array to start processing * @param int $end The index of the post IDs array to stop processing * @param int $batch_limit The maximum number of posts to process for this event. * @param int $daily_limit The maximum number of posts to process for today. */ public function bulk_event($start = 0, $end = 0, $batch_limit = 100, $daily_limit = 400) { //Get the post IDs $this->processing_bulk = true; $post_ids = $this->get_setting('bulk_update_posts'); $post_ids = $post_ids ? explode(',', $post_ids) : false; if (is_array($post_ids) && count($post_ids)) { $index = $start; //200 do { $this->process_post($post_ids[$index]); //Process the post ID at this index $index++; //Increment index } while ($index < $end); /* Pretend there are 500 articles, batch limit is 100, daily limit is 1000 and we already did the first 100 post count = 500 (total count) - 200 (current index) end = 300 = 200 + 100 = (current index + batch limit) if the end (300) is less or equal to than the total remaining (300), next round will be last, set it to the count else if the end (300) is greater than the daily limit, schedule the next batch for tomorrow */ //Calculate the next batch $post_count = count($post_ids); if ($index >= $post_count) { //all batches are completed! $this->debug_log('Acessible Reading: Bulk Event - all batches are completed'); } else { //$post_count = count($post_ids) - $index; //Remaining articles 500 - 200 = 300 $start = $index; //Where we left off = 400 (of 450 articles) $end = $index + $batch_limit; // 400 + 100 = 500 $batch_total = $batch_limit; //100 if ($end >= $post_count) { //500 < 450 //There are less posts than the batch limit, end at the end and it'll be the last batch $batch_total = $end - $post_count; //500 - 450 = 50 $end = $post_count; //450 } $same_day = $this->is_within_daily_limit(false, 50, $batch_total); //If we've reached our daily limit //Schedule the next event $this->schedule_event(array( 'start' => $start, 'end' => $end, 'batch_limit' => $batch_limit, 'daily_limit' => $daily_limit ), $same_day); } } else { $this->debug_log($post_ids, 'Acessible Reading: Bulk Event - post IDs were not an array or was empty'); } $this->processing_bulk = false; } /** * Get API Request Count for Single Post * * AJAX request from admin-metabox.js. It will also set the count if it wasn't already set * * @since 1.3.0 * @param int $post_id Post ID * @param string $content Optional. The content to process into accessible content. * @param bool $count_only * @param string $post_type Optional. The post type to retrieve. Default is `post`. * @return int|false|array Optional. The number of API requests that will be needed to process * this post, or false on failure, or if `$count_only` was false, will return a * sequential array of chunked content ready for processing */ public function estimate_post() { //Get parameters from POST $return = array( 'success' => 0, 'error' => 0, 'messages' => array('Processing single post'), 'output' => '', 'fields' => array( 'post_id' => $this->array_has_key('post_id', $_POST), 'post_type' => $this->array_has_key('post_type', $_POST), 'post_content' => $this->array_has_key('post_content', $_POST) ) ); if ($return['fields']['post_type'] && $return['fields']['post_id'] && is_numeric($return['fields']['post_id']) && $return['fields']['post_id'] > 0) { $return['success']++; $return['output'] = sprintf( __('This post will use approximately %s API request(s) to process accessible content due to the character limitations.', $this->settings['slug']), $this->get_post_estimate( $return['fields']['post_id'], $return['fields']['post_content'], true, true, $return['fields']['post_type'] ) ); } else { $return['error']++; $return['output'] = __('Could not estimate API usage because either the post type or post ID is invalid.', $this->settings['slug']); } wp_die(json_encode($return)); } //**** Utility Functions ****// /** * Array Key Exists and Has Value * * @since 1.0.0 * @param string|int $key The key to search for in the array. * @param array $array The array to search. * @param mixed $default The default value to return if not found or * is empty. Default is an empty string. * @return mixed The value of the key found in the array if it exists * or the value of `$default` if not found or is empty. */ private function array_has_key($key = '', $array = array(), $default = '') { //Check if this key exists in the array if ((is_string($key) || is_numeric($key)) && is_array($array) && count($array) && array_key_exists($key, $array)) { // Only return it if it has any value (falsy boolean/integer values count) if ($array[$key] || is_bool($array[$key]) || is_numeric($array[$key])) { return $array[$key]; } } return $default; } /** * Normalize HTML * * Sanitizes post content, removes HTML comments, and removes excess whitespace * Documentation: https://developer.wordpress.org/plugins/security/securing-output/ * * @since 1.0.0 * @param string $content * @return string modified content */ private function normalize_html($content = '') { if ($content) { return $this->remove_excess_whitespace(wp_kses_post($this->remove_html_comments($content))); } return $content; } /** * Remove excess whitespace * * @since 1.0.0 * @param string $content * @return string modified content */ private function remove_excess_whitespace($content = '') { return trim(preg_replace('/\s+/', ' ', $content)); } /** * Remove HTML Comments * * @since 1.0.0 * @param string $content * @return string modified content */ private function remove_html_comments($content = '') { return preg_replace('//', '', $content); } /** * Write a message to debug.log * * Uses `error_log` * * @since 1.0.0 * @param mixed The variable to dump. */ private function debug_log($obj, $title = '') { if ($this->debug && WP_DEBUG && WP_DEBUG_LOG) { if ($title) { error_log($title); } if (is_array($obj) || is_object($obj)) { error_log(print_r($obj, true)); } else { error_log($obj); } } } } } if (!function_exists('array_key_first')) { /** * Gets the first key of an array * * Gets the first key of the given array without affecting the internal array pointer. * * @since 1.0.0 * @param array $array * @return int|string|null */ function array_key_first($array = array()) { foreach ($array as $key => $value) { return $key; } return null; } } if (!function_exists('accessible_reading')) { /** * Returns the main instance of AccessibleReading. * * @since 1.0.0 * @return AccessibleReading */ function accessible_reading() { return AccessibleReading::instance(); } } accessible_reading();//Run once to init /* Purposely excluding the closing PHP tag to avoid "headers already sent" error */