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( ''); 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
%s
%s
', $this->debug ? '' : '', $this->get_meta( $post_id, 'toggle_switch', $this->get_setting('toggle_switch', true), //Fallback to the global setting $post_type ), $this->get_checkbox_switch(array( 'name' => $this->settings['slug'], 'value' => 'swap-accessible-reading', 'reverse' => false, 'no' => __('Enable Accessible Reading', $this->settings['slug']), 'yes' => __('Disable Accessible Reading', $this->settings['slug']) )), $content, $accessible_content ); } } } return $content; } /** * Get Meta Key for Accessible Content * * @since 1.0.0 * @return string meta key */ private function get_key() { return $this->settings['prefix'] . 'content'; } //**** Accessible Content Processing ****// /** * Create Accessible Reading Content for Post * * @since 1.1.0 * @param int $post_id Post ID * @param string $content Optional. The content to process into accessible content. * @param string $post_type Optional. The post type to retrieve. Default is `post`. * @return string accessible content or empty string on failure */ private function process_post($post_id, $content = '', $post_type = 'post') { if (is_numeric($post_id) && $post_id) { $request_count = 0; //This will be important later if (!$content) { //Get this post's content $content = get_the_content(null, false, $post_id); } if (is_string($content) && $content) { $content = $this->normalize_html($content); $content_chunks = $this->get_post_estimate( $post_id, $content, true, //Force new chunks to be created false, //Return the chunks $post_type ); $request_count = count($content_chunks); //How many API requests this is going to need if ($request_count) { $accessible_content = array(); foreach ($content_chunks as $excerpt) { $accessible_content[] = $this->create_accessible_content($excerpt); //Sent it through the API } $accessible_content = implode('', $accessible_content); //Return array to string if ($accessible_content) { //Save content to post $this->save_content($post_id, $accessible_content, $post_type); $this->debug_log('Acessible Reading: Process Post - accessible content created and saved in meta data'); return $accessible_content; } else { $this->debug_log('Acessible Reading: Process Post - accessible content was blank'); } } } else { $this->debug_log('Acessible Reading: Process Post - original content was blank'); } //Save how many requests it took to generate $this->set_meta($post_id, 'api_request_count', $request_count, $post_type); } else { $this->debug_log('Acessible Reading: Process Post - invalid post ID'); } return ''; } /** * Set API Request Count for Post * * @since 1.2.0 * @param int $post_id Post ID * @param string $content Optional. The content to process into accessible content. * @param bool $count_only If true, only return the number of API requests. If false, * return the array of chunked content. * @param string $post_type Optional. The post type to retrieve. Default is `post`. * @return int|false|array 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 */ private function set_post_estimate($post_id, $content = '', $count_only = true, $post_type = 'post') { $request_count = false; if (is_numeric($post_id) && $post_id) { $request_count = 0; if (!$content) { //Get this post's content, this may have to change depending on post type? $content = get_the_content(null, false, $post_id); } $content_chunks = ''; if (is_string($content) && $content) { $content_chunks = $this->get_content_chunks($this->normalize_html($content)); $request_count = count($content_chunks); //How many API requests this is going to need } //Save the chunked content $this->set_meta($post_id, 'content_chunked', $content_chunks, $post_type); //Save how many requests it will take to generate $this->set_meta($post_id, 'api_request_count', $request_count, $post_type); } if ($count_only) { return $request_count; } return $content_chunks; } /** * Get API Request Count for Single Post * * It will also set the count if it wasn't already set * * @since 1.2.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 */ private function get_post_estimate($post_id, $content = '', $force_new = false, $count_only = true, $post_type = 'post') { $request_count = false; if (!$force_new && is_numeric($post_id) && $post_id) { if ($count_only) { $request_count = $this->get_meta($post_id, 'api_request_count', 0, $post_type); if (is_numeric($request_count)) { return $request_count; } } else { $content_chunks = $this->get_meta($post_id, 'content_chunked', '', $post_type); if (is_array($content_chunks)) { return $content_chunks; } } } return $this->set_post_estimate($post_id, $content, $count_only); } /** * Get Post Estimates * * @since 1.2.0 * @param int $batch_limit * @param bool $all * @param bool $force_new * @return array an associatve array that include keys for `total` (int|bool, total * number of requests that would be used), `last_run` (TBD), `count` (int, the total * number of posts included in this query), and `post_ids` (array, a sequential array * of Post IDs) */ private function get_post_estimates($batch_limit, $all = false, $force_new = false) { $return = array( 'total' => false, //The total number of requests that would be used if the bulk updater was run on these settings 'last_run' => '', //Estimating when the last CRON event would be run 'count' => 0, 'post_ids' => array() ); //Query the blog for posts $query_args = array( 'fields' => 'ids', //Return an array of post IDs 'post_type' => $this->get_post_types(), //Only our allowed post types 'posts_per_page' => -1, //Get all 'orderby' => 'date', //Order by publish date 'order' => 'DESC', //Get the newest first ); if (!$all) { //$return['messages'][] = 'Only processing posts that do not have accessible content.'; $meta_key = $this->get_key(); $query_args['meta_query'] = array( 'relation' => 'OR', //return results where field does not exist array( 'key' => $meta_key, 'value' => 'bug #23268', //Included for compatibility for WordPress version below 3.9 'compare' => 'NOT EXISTS' ), //return results where field exists but is empty array( 'key' => $meta_key, 'value' => array(''), 'compare' => 'IN' ) ); } else { //$return['messages'][] = 'All posts excluding those that are disabled'; $meta_key = $this->settings['prefix'] . 'enabled'; $query_args['meta_query'] = array( 'relation' => 'OR', //return results where field does not exist array( 'key' => $meta_key, 'value' => 'bug #23268', //Included for compatibility for WordPress version below 3.9 'compare' => 'NOT EXISTS' ), //return results where field exists but is empty or is equal to 1 array( 'key' => $meta_key, 'value' => array('', '1'), 'compare' => 'IN' ) ); } $query = new WP_Query($query_args); $post_ids = $query->posts; $this->debug_log($post_ids, 'Post IDs'); $return['count'] = is_array($post_ids) ? count($post_ids) : 0; if ($return['count']) { //$return['post_ids'] = $post_ids; if (!$all) { //Resetting count because we need to filter disabled posts, can't mix and/or meta queries $return['count'] = 0; } $return['total'] = 0; foreach ($post_ids as $post_id) { //Only get post ID if enabled $post_type = get_post_type($post_id); if ($this->get_meta($post_id, 'enabled', $this->settings['post_options']['enabled']['default'], $post_type)) { $return['post_ids'][] = $post_id; //Add post ID to final array $requests = $this->get_post_estimate($post_id, '', $force_new, true, $post_type); //Also sets the meta field for this post's requests if (is_numeric($requests)) { $return['total'] += $requests; } } } //How many CRON events would get scheduled $return['crons'] = ceil($return['total'] / $batch_limit); } else { $this->debug_log('Post IDs were not an array or were empty, could not create an estimate.'); } $return['count'] = count($return['post_ids']); return $return; } /** * Get Content Chunks * * @since 1.2.0 * @param string $content * @return array a sequential array of HTML content divided * up to fit within the API request parameters */ private function get_content_chunks($content = '') { $chunks = array(); if (is_string($content) && !empty($content)) { $length = strlen($content); $char_limit = $this->get_character_limit(); $s = 0; //Starting index do { //Get the excerpt using the character limit $excerpt = substr( $content, //Original content $s, //Starting index point $char_limit //Length ); if (is_string($excerpt)) { $this->debug_log(' Starting Point: ' . $s); //Trim the content to a block level element $possible_ends = array( 'line' => strripos($excerpt, PHP_EOL), //Identify the last occurrence of a new line 'div' => strripos($excerpt, ''), //Identify the last occurrence of a closing div tag 'p' => strripos($excerpt, '

'), //Identify the last occurrence of a closing paragraph tag 'ul' => strripos($excerpt, ''), //Identify the last occurrence of a closing unordered list 'ol' => strripos($excerpt, ''), //Identify the last occurrence of a closing ordered list 'h1' => strripos($excerpt, ''), //Identify the last occurrence of a closing header 1 tag 'h2' => strripos($excerpt, ''), //Identify the last occurrence of a closing header 2 tag 'h3' => strripos($excerpt, ''), //Identify the last occurrence of a closing header 3 tag 'h4' => strripos($excerpt, ''), //Identify the last occurrence of a closing header 4 tag 'h5' => strripos($excerpt, ''), //Identify the last occurrence of a closing header 5 tag 'h6' => strripos($excerpt, '') //Identify the last occurrence of a closing header 6 tag ); $excerpt_end = $char_limit; foreach ($possible_ends as $tag => $possible_end) { if (is_numeric($possible_end) && $possible_end < $excerpt_end) { $excerpt_end = $possible_end; if ($tag !== 'line') { $excerpt_end += strlen($tag) + 3; //Include the closing tag in the trim } } } $excerpt = substr($excerpt, 0, $excerpt_end); //Chop the excerpt $this->debug_log(' Excerpt length: ' . $excerpt_end); $this->debug_log(' Excerpt Character Count: ' . strlen($excerpt)); $this->debug_log($excerpt, true, true, ' Excerpt'); $s += $excerpt_end; //New starting index is at the excerpt's end $chunks[] = $excerpt; //Add the excerpt to the list of chunks } } while ($s < $length); } return $chunks; //Return the array of chunked content } /** * Create Accessible Reading Content * * Utilize the Bionic Reading API to generate accessible * content of the original content. * * @since 1.0.0 * @param string $content The content to process into accessible content. * @return string accessible content */ private function create_accessible_content($content = '') { $accessible_content = ''; if ($content) { //Use the API to generate bionic content $api_key = $this->get_setting($this->settings['prefix'] . 'api_key', true); if ($api_key) { $api = wp_remote_post('https://bionic-reading1.p.rapidapi.com/convert', array( 'method' => 'POST', 'timeout' => 30, 'redirection' => 10, 'httpversion' => CURL_HTTP_VERSION_1_1, 'blocking' => true, 'headers' => array( 'content-type' => 'application/x-www-form-urlencoded', 'X-RapidAPI-Host' => 'bionic-reading1.p.rapidapi.com', 'X-RapidAPI-Key' => $api_key ), 'body' => array( 'content' => $content, 'response_type' => 'html', 'request_type' => 'html', 'fixation' => $this->get_setting($this->settings['prefix'] . 'fixation', true), 'saccade' => $this->get_setting($this->settings['prefix'] . 'saccade', true) ) )); if (is_wp_error($api)) { $this->debug_log($api, 'Acessible Reading: API Connection Error'); } else { $accessible_content = wp_remote_retrieve_body($api); if (strpos($accessible_content, '{') === 0) { //This is a JS error $this->debug_log(json_decode($accessible_content, true, 512, JSON_PRETTY_PRINT), 'Acessible Reading: API Error'); $accessible_content = ''; } } //Update Daily Limit Counter $count = $this->get_daily_limit_tracker(); $count['count']++; //Increment the counter $count['date'] = strtotime('now'); //Date/time of last API request $this->debug_log($count, 'Acessible Reading: Tracking API Counter'); $this->set_daily_limit_tracker($count); } else { $this->debug_log('Acessible Reading: create accessible content - API key is missing!'); } } else { $this->debug_log('Acessible Reading: create accessible content - content parameter was falsy'); } return $this->normalize_html($accessible_content); } /** * Save Accessible Content for Post ID * * @since 1.0.0 * @param int $post_id Post ID * @param string $content * @param string $post_type Optional. The post type to retrieve. Default is `post`. * @return string $content */ private function save_content($post_id, $content, $post_type = 'post') { //Save the accessible content in post meta and return it return $this->set_meta($post_id, 'content', $content, $post_type); } /** * Get Accessible Content for Post * * @since 1.0.0 * @param int $post_id Post ID * @param string $post_type Optional. The post type to retrieve. Default is `post`. * @return string The accessible content */ private function get_content($post_id, $post_type = 'post') { return $this->get_meta($post_id, 'content', '', $post_type); } //**** Bulk Update Functions ****// /** * Check if Processing Bulk Operation * * @since 1.3.0 * @return bool If true, either it is actively processing or an event is scheduled to be processed. */ public function is_processing_bulk() { return $this->processing_bulk || wp_next_scheduled($this->settings['hook']); } /** * Start Bulk Post Update * * AJAX request from admin-dashboard.js * * @since 1.1.0 */ public function bulk_start() { $already_processing = $this->is_processing_bulk(); $this->processing_bulk = true; $this->debug_log('Start Bulk Updater', ' '); //Get parameters from POST $fields = $this->array_has_key('fields', $_POST); $return = array( 'success' => 0, 'error' => 0, 'messages' => array('Starting bulk updater'), 'output' => '', 'fields' => $fields ); if ($fields) { $return['success']++; $fields = explode('&', $fields); $args = array(); foreach ($fields as $property_string) { $split = explode('=', $property_string); if (count($split) > 1) { $args[$split[0]] = $split[1]; } } $daily_limit = $this->get_daily_limit(); $batch_limit = $this->array_has_key('batch_limit', $args); if ($batch_limit && $daily_limit && $batch_limit <= $daily_limit) { $return['success']++; $estimate = $this->array_has_key('estimate', $args); $estimation = $this->get_post_estimates( $batch_limit, $this->array_has_key('force_generate', $args), $estimate ); $plan = $this->get_plan(); $end = $estimation['count'] < $batch_limit ? $estimation['count'] : $batch_limit; $same_day = $this->is_within_daily_limit($plan, 50, $end); //If we've reached our daily limit if ($estimate) { //Return estimation details if ($estimation['count'] && $estimation['total']) { $return['output'] = sprintf( __('There are %s post(s) that will be processed with these settings.', $this->settings['slug']), $estimation['count'] ); $same_day = $this->is_within_daily_limit($plan, 50, $estimation['count']); //If we've reached our daily limit $return['output'] .= ' ' . sprintf( __('Based on your API plan and character counts of your post content, it will take %s API request(s) to complete this process.', $this->settings['slug']), $estimation['total'] ); $return['output'] .= ' ' . sprintf( __('Based on your batch limit, it will take approximately %s minutes to complete. Processing takes place in the background so you can safely leave this page once it is started.', $this->settings['slug']), $estimation['crons'] ); if (!$same_day) { $return['output'] .= ' ' . sprintf( __("Processing will not be completed today due to your plan's daily API request limit. It will automatically resume 24 hours after it's last request.", $this->settings['slug']), $estimation['crons'] ); } } else { $return['output'] = sprintf( __('There are no posts that will be processed with these settings.', $this->settings['slug']), $estimation['count'] ); } $return['output'] = '

' . $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 */