PK!\$$controller-frontend.phpnu[>}> */ protected array $shown_tables = array(); /** * List of registered DataTables datetime formats. * * @since 3.0.0 * @var string[] */ protected array $datatables_datetime_formats = array(); /** * Initiates Frontend functionality. * * @since 1.0.0 */ public function __construct() { parent::__construct(); /** * Filters the admin menu parent page, which is needed for the construction of plugin URLs. * * @since 1.0.0 * * @param string $parent_page Current admin menu parent page. */ $this->parent_page = apply_filters( 'tablepress_admin_menu_parent_page', TablePress::$model_options->get( 'admin_menu_parent_page' ) ); $this->is_top_level_page = in_array( $this->parent_page, array( 'top', 'middle', 'bottom' ), true ); /** * Filters whether TablePress should load its frontend CSS files on all pages. * For block themes, the default behavior is to only load the CSS files when a table is encountered on the page. * If Elementor is active, the CSS is also loaded on the editor page. * * @since 3.0.1 * * @param bool $use_legacy_css_loading Whether TablePress should load its frontend CSS files on all pages. */ $this->use_legacy_css_loading = apply_filters( 'tablepress_frontend_legacy_css_loading', ! wp_is_block_theme() || ( isset( $_GET['elementor-preview'] ) && is_plugin_active( 'elementor/elementor.php' ) ) ); if ( $this->use_legacy_css_loading ) { add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) ); } add_action( 'wp_print_footer_scripts', array( $this, 'add_datatables_calls' ), 9 ); // Priority 9 so that this runs before `_wp_footer_scripts()`. // Register TablePress Shortcodes. Priority 20 is kept for backwards-compatibility purposes. add_action( 'init', array( $this, 'init_shortcodes' ), 20 ); /** * Filters whether the WordPress search shall also search TablePress tables. * * @since 1.0.0 * * @param bool $search Whether the TablePress tables shall be searched. Default true. */ if ( apply_filters( 'tablepress_wp_search_integration', true ) ) { // Extend WordPress Search to also find posts/pages that have a table with the one of the search terms in title (if shown), description (if shown), or content. add_filter( 'posts_search', array( $this, 'posts_search_filter' ) ); } /** * Load TablePress Template Tag functions. */ TablePress::load_file( 'template-tag-functions.php', 'controllers' ); /** * Register the tablepress/table block and its dependencies. */ if ( function_exists( 'wp_register_block_metadata_collection' ) ) { // wp_register_block_metadata_collection() is only available since WP 6.7. wp_register_block_metadata_collection( TABLEPRESS_ABSPATH . 'blocks', TABLEPRESS_ABSPATH . 'blocks/blocks-manifest.php', ); } register_block_type_from_metadata( TABLEPRESS_ABSPATH . 'blocks/table/block.json', array( 'render_callback' => array( $this, 'table_block_render_callback' ), ), ); /** * Register the TablePress Elementor widgets. */ add_action( 'elementor/widgets/register', array( $this, 'register_elementor_widgets' ) ); add_action( 'elementor/editor/after_enqueue_styles', array( $this, 'enqueue_elementor_editor_styles' ), 10, 0 ); } /** * Registers TablePress Shortcodes. * * @since 1.0.0 */ public function init_shortcodes(): void { add_shortcode( TablePress::$shortcode, array( $this, 'shortcode_table' ) ); add_shortcode( TablePress::$shortcode_info, array( $this, 'shortcode_table_info' ) ); } /** * Checks if the CSS files for TablePress default CSS and "Custom CSS" should be loaded. * * This function is only called when a [table /] Shortcode or "TablePress Table" block is evaluated, so that CSS files are only loaded when needed. * * @since 3.0.0 */ public function maybe_enqueue_css(): void { // Bail early if the legacy CSS loading mechanism is used, as the files will then have been enqueued already. if ( $this->use_legacy_css_loading && ! doing_action( 'enqueue_block_assets' ) ) { return; } /* * Bail early if the function is called from some action hook outside of the normal rendering process. * These are often used by e.g. SEO plugins that render the content in additional contexts, e.g. to get an excerpt via an output buffer. * In these cases, we don't want to enqueue the CSS, as it would likely not be printed on the page. */ if ( doing_action( 'wp_head' ) || doing_action( 'wp_footer' ) ) { return; } // Prevent repeated execution via a static variable. static $css_enqueued = false; if ( $css_enqueued && ! doing_action( 'enqueue_block_assets' ) ) { return; } $css_enqueued = true; $this->enqueue_css(); } /** * Enqueues CSS files for TablePress default CSS and "Custom CSS" (if desired). * * If styles have not been printed to the page (in the ``), the TablePress CSS files will be enqueued. * If styles have already been printed to the page, the TablePress CSS files will be printed right away (likely in the `). * * @since 1.0.0 */ public function enqueue_css(): void { /** * Filters whether the TablePress Default CSS code shall be loaded. * * @since 1.0.0 * * @param bool $use Whether the Default CSS shall be loaded. Default true. */ $use_default_css = apply_filters( 'tablepress_use_default_css', true ); $use_custom_css = TablePress::$model_options->get( 'use_custom_css' ); if ( ! $use_default_css && ! $use_custom_css ) { // Register a placeholder dependency, so that the handle is known for other styles. wp_register_style( 'tablepress-default', false ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion return; } $custom_css = TablePress::$model_options->get( 'custom_css' ); $use_custom_css = $use_custom_css && '' !== $custom_css; $use_custom_css_file = $use_custom_css && TablePress::$model_options->get( 'use_custom_css_file' ); /** * Filters the "Custom CSS" version number that is appended to the enqueued CSS files * * @since 1.0.0 * * @param int $version The "Custom CSS" version. */ $custom_css_version = (string) apply_filters( 'tablepress_custom_css_version', TablePress::$model_options->get( 'custom_css_version' ) ); $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' ); // Determine Default CSS URL. $rtl = ( is_rtl() ) ? '-rtl' : ''; $unfiltered_default_css_url = plugins_url( "css/build/default{$rtl}.css", TABLEPRESS__FILE__ ); /** * Filters the URL from which the TablePress Default CSS file is loaded. * * @since 1.0.0 * * @param string $unfiltered_default_css_url URL of the TablePress Default CSS file. */ $default_css_url = apply_filters( 'tablepress_default_css_url', $unfiltered_default_css_url ); $use_custom_css_combined_file = ( $use_default_css && $use_custom_css_file && ! SCRIPT_DEBUG && ! is_rtl() && $unfiltered_default_css_url === $default_css_url && $tablepress_css->load_custom_css_from_file( 'combined' ) ); if ( $use_custom_css_combined_file ) { $custom_css_combined_url = $tablepress_css->get_custom_css_location( 'combined', 'url' ); // Need to use 'tablepress-default' instead of 'tablepress-combined' to not break existing TablePress Extensions. wp_enqueue_style( 'tablepress-default', $custom_css_combined_url, array(), $custom_css_version ); if ( did_action( 'wp_print_styles' ) ) { wp_print_styles( 'tablepress-default' ); } return; } if ( $use_default_css ) { wp_enqueue_style( 'tablepress-default', $default_css_url, array(), TablePress::version ); } else { // Register a placeholder dependency, so that the handle is known for other styles. wp_register_style( 'tablepress-default', false ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion } $use_custom_css_minified_file = ( $use_custom_css_file && ! SCRIPT_DEBUG && $tablepress_css->load_custom_css_from_file( 'minified' ) ); if ( $use_custom_css_minified_file ) { $custom_css_minified_url = $tablepress_css->get_custom_css_location( 'minified', 'url' ); wp_enqueue_style( 'tablepress-custom', $custom_css_minified_url, array( 'tablepress-default' ), $custom_css_version ); if ( did_action( 'wp_print_styles' ) ) { wp_print_styles( 'tablepress-custom' ); } return; } $use_custom_css_normal_file = ( $use_custom_css_file && $tablepress_css->load_custom_css_from_file( 'normal' ) ); if ( $use_custom_css_normal_file ) { $custom_css_normal_url = $tablepress_css->get_custom_css_location( 'normal', 'url' ); wp_enqueue_style( 'tablepress-custom', $custom_css_normal_url, array( 'tablepress-default' ), $custom_css_version ); if ( did_action( 'wp_print_styles' ) ) { wp_print_styles( 'tablepress-custom' ); } return; } if ( $use_custom_css ) { // Get "Custom CSS" from options, try minified Custom CSS first. $custom_css_minified = TablePress::$model_options->get( 'custom_css_minified' ); if ( ! empty( $custom_css_minified ) ) { $custom_css = $custom_css_minified; } /** * Filters the "Custom CSS" code that is to be loaded as inline CSS. * * @since 1.0.0 * * @param string $custom_css The "Custom CSS" code. */ $custom_css = apply_filters( 'tablepress_custom_css', $custom_css ); if ( ! empty( $custom_css ) ) { wp_add_inline_style( 'tablepress-default', $custom_css ); if ( did_action( 'wp_print_styles' ) ) { wp_print_styles( 'tablepress-default' ); } return; } } } /** * Enqueues the DataTables JavaScript library and its dependencies. * * @since 3.0.0 */ protected function enqueue_datatables_files(): void { $js_file = 'js/jquery.datatables.min.js'; $js_url = plugins_url( $js_file, TABLEPRESS__FILE__ ); /** * Filters the URL from which the DataTables JavaScript library file is loaded. * * @since 1.0.0 * * @param string $js_url URL of the DataTables JS library file. * @param string $js_file Path and file name of the DataTables JS library file. */ $js_url = apply_filters( 'tablepress_datatables_js_url', $js_url, $js_file ); $dependencies = array( 'jquery-core' ); if ( ! empty( $this->datatables_datetime_formats ) ) { $dependencies[] = 'moment'; } /** * Filters the dependencies for the DataTables JavaScript library. * * @since 3.0.0 * * @param string[] $dependencies The dependencies for the DataTables JS library. */ $dependencies = apply_filters( 'tablepress_datatables_js_dependencies', $dependencies ); wp_enqueue_script( 'tablepress-datatables', $js_url, $dependencies, TablePress::version, true ); } /** * Adds the JavaScript code for the invocation of the DataTables JS library. * * @since 1.0.0 */ public function add_datatables_calls(): void { // Prevent repeated execution (which would lead to DataTables error messages) via a static variable. static $datatables_calls_printed = false; if ( $datatables_calls_printed ) { return; } // Bail early if there are no TablePress tables on the page. if ( empty( $this->shown_tables ) ) { return; } /* * Don't add the DataTables function calls in the scope of the block editor iframe. * This is necessary for non-block themes, for others, the repeated execution check above is sufficient. */ if ( function_exists( 'get_current_screen' ) ) { $current_screen = get_current_screen(); if ( ( $current_screen instanceof WP_Screen ) && $current_screen->is_block_editor() ) { return; } } // Filter out all tables that use DataTables. $shown_tables_with_datatables = array(); foreach ( $this->shown_tables as $table_id => $table_store ) { if ( ! empty( $table_store['instances'] ) ) { $shown_tables_with_datatables[ (string) $table_id ] = $table_store; } } // Bail early if there are no tables with activated DataTables on the page. if ( empty( $shown_tables_with_datatables ) ) { return; } $this->enqueue_datatables_files(); // Storage for the DataTables language strings. $datatables_language = array(); // Generate the specific JS commands, depending on chosen features on the "Edit" screen and the Shortcode parameters. $commands = array(); foreach ( $shown_tables_with_datatables as $table_id => $table_store ) { $table_id = (string) $table_id; // Ensure that the table ID is a string, as it comes from an array key where numeric strings are converted to integers. foreach ( $table_store['instances'] as $html_id => $js_options ) { $parameters = array(); // Settle dependencies/conflicts between certain features. if ( false !== $js_options['datatables_scrolly'] ) { // datatables_scrolly can be a string, so that the explicit `false` check is needed. // Vertical scrolling and pagination don't work together. $js_options['datatables_paginate'] = false; } // Sanitize, as it may come from a Shortcode attribute. $js_options['datatables_paginate_entries'] = (int) $js_options['datatables_paginate_entries']; /* * DataTables language/translation handling. */ /** * Filters the locale/language for the DataTables JavaScript library. * * @since 1.0.0 * * @param string $locale The DataTables JS library locale. * @param string $table_id The current table ID. */ $datatables_locale = apply_filters( 'tablepress_datatables_locale', $js_options['datatables_locale'], $table_id ); // Only load each locale's language file once. if ( ! isset( $datatables_language[ $datatables_locale ] ) ) { $orig_language_file = TABLEPRESS_ABSPATH . "i18n/datatables/lang-{$datatables_locale}.php"; /** * Filters the language file path for the DataTables JavaScript library. * * PHP files that return an array and JSON files are supported. * The JSON file method is deprecated and should no longer be used. * * @since 1.0.0 * * @param string $orig_language_file Language file path for the DataTables JS library. * @param string $datatables_locale Current locale/language for the DataTables JS library. * @param string $tablepress_abspath Base path of the TablePress plugin. */ $language_file = apply_filters( 'tablepress_datatables_language_file', $orig_language_file, $datatables_locale, TABLEPRESS_ABSPATH ); /* * Load translation file if it's not "en_US" (included as the default in DataTables) * or if the filter was used to change the language file, and the language file exists. * Otherwise, use an empty en_US placeholder, so that the strings are filterable later. */ if ( ( 'en_US' !== $datatables_locale || $orig_language_file !== $language_file ) && file_exists( $language_file ) ) { if ( str_ends_with( $language_file, '.php' ) ) { $datatables_strings = require $language_file; if ( ! is_array( $datatables_strings ) ) { $datatables_strings = array(); } } elseif ( str_ends_with( $language_file, '.json' ) ) { $datatables_strings = file_get_contents( $language_file ); $datatables_strings = json_decode( $datatables_strings, true ); // @phpstan-ignore argument.type // Check if JSON could be decoded. if ( is_null( $datatables_strings ) ) { $datatables_strings = array(); } $datatables_strings = (array) $datatables_strings; } else { // The filtered language file exists, but is not a .php or .json file, so don't use it. $datatables_strings = array(); } } else { // If no translation file for the defined locale exists or is needed, use "en_US", as that's built-in. $datatables_locale = 'en_US'; $datatables_strings = array(); } /** * Filters the language strings for the DataTables JavaScript library's features. * * @since 2.0.0 * * @param array $datatables_strings The language strings for DataTables. * @param string $datatables_locale Current locale/language for the DataTables JS library. */ $datatables_language[ $datatables_locale ] = apply_filters( 'tablepress_datatables_language_strings', $datatables_strings, $datatables_locale ); } $parameters['language'] = "language:DT_language['{$datatables_locale}']"; // These parameters need to be added for performance gain or to overwrite unwanted default behavior. if ( $js_options['datatables_sort'] ) { // No initial sort. $parameters['order'] = 'order:[]'; // Don't add additional classes, to speed up sorting. $parameters['orderClasses'] = 'orderClasses:false'; } // The following options are activated by default, so we only need to "false" them if we don't want them, but don't need to "true" them if we do. if ( ! $js_options['datatables_sort'] ) { $parameters['ordering'] = 'ordering:false'; } if ( $js_options['datatables_paginate'] ) { $parameters['pagingType'] = "pagingType:'simple_numbers'"; if ( $js_options['datatables_lengthchange'] ) { $length_menu = array( 10, 25, 50, 100 ); if ( ! in_array( $js_options['datatables_paginate_entries'], $length_menu, true ) ) { $length_menu[] = $js_options['datatables_paginate_entries']; sort( $length_menu, SORT_NUMERIC ); $parameters['lengthMenu'] = 'lengthMenu:[' . implode( ',', $length_menu ) . ']'; } } else { $parameters['lengthChange'] = 'lengthChange:false'; } if ( 10 !== $js_options['datatables_paginate_entries'] ) { $parameters['pageLength'] = "pageLength:{$js_options['datatables_paginate_entries']}"; } } else { $parameters['paging'] = 'paging:false'; } if ( ! $js_options['datatables_filter'] ) { $parameters['searching'] = 'searching:false'; } if ( ! $js_options['datatables_info'] ) { $parameters['info'] = 'info:false'; } if ( $js_options['datatables_scrollx'] ) { $parameters['scrollX'] = 'scrollX:true'; } if ( false !== $js_options['datatables_scrolly'] ) { $parameters['scrollY'] = 'scrollY:"' . preg_replace( '#[^0-9a-z.%]#', '', $js_options['datatables_scrolly'] ) . '"'; $parameters['scrollCollapse'] = 'scrollCollapse:true'; } if ( '' !== $js_options['datatables_custom_commands'] ) { $parameters['custom_commands'] = trim( $js_options['datatables_custom_commands'] ); // Remove leading and trailing whitespace. $parameters['custom_commands'] = trim( $parameters['custom_commands'], ',' ); // Remove potentially leading and trailing commas to prevent JS script errors. } /** * Filters the parameters that are passed to the DataTables JavaScript library. * * @since 1.0.0 * * @param array $parameters The parameters for the DataTables JS library. * @param string $table_id The current table ID. * @param string $html_id The ID of the table HTML element. * @param array $js_options The options for the JS library. */ $parameters = apply_filters( 'tablepress_datatables_parameters', $parameters, $table_id, $html_id, $js_options ); // If an existing parameter is set as an object key in the "Custom Commands", remove its separate value, to allow for full overrides. if ( isset( $parameters['custom_commands'] ) && '' !== $parameters['custom_commands'] ) { $parameters_in_custom_commands = TablePress::extract_keys_from_js_object_string( '{' . $parameters['custom_commands'] . '}' ); foreach ( $parameters_in_custom_commands as $parameter_in_custom_commands ) { unset( $parameters[ $parameter_in_custom_commands ] ); } } $name = substr( $html_id, 11 ); // Remove "tablepress-" from the HTML ID. $name = "DT_TP['" . str_replace( '-', '_', $name ) . "']"; $parameters = implode( ',', $parameters ); $parameters = ( ! empty( $parameters ) ) ? '{' . $parameters . '}' : ''; $command = "{$name} = new DataTable('#{$html_id}',{$parameters});"; /** * Filters the JavaScript command that invokes the DataTables JavaScript library on one table. * * @since 1.0.0 * * @param string $command The JS command for the DataTables JS library. * @param string $html_id The ID of the table HTML element. * @param string $parameters The parameters for the DataTables JS library. * @param string $table_id The current table ID. * @param array $js_options The options for the JS library. * @param string $name The name of the DataTable instance. */ $command = apply_filters( 'tablepress_datatables_command', $command, $html_id, $parameters, $table_id, $js_options, $name ); if ( ! empty( $command ) ) { $commands[] = $command; } } // foreach table instance } // foreach table ID // DataTables language/translation handling. if ( ! empty( $datatables_language ) ) { $datatables_language_command = wp_json_encode( $datatables_language, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_FORCE_OBJECT ); $datatables_language_command = "var DT_language={$datatables_language_command};\n"; } else { $datatables_language_command = ''; } // DataTables datetime format string handling. if ( ! empty( $this->datatables_datetime_formats ) ) { // Create a command like `DataTable.datetime('MM/DD/YYYY');DataTable.datetime('DD.MM.YYYY');`. $datatables_datetime_command = implode( '', array_map( static fn( string $datetime_format ): string => "DataTable.datetime('{$datetime_format}');", $this->datatables_datetime_formats, ) ) . "\n"; } else { $datatables_datetime_command = ''; } /** * Filters the JavaScript code for the DataTables JavaScript library that initializes the automatically detected date/time formats via moment.js. * * @since 3.0.0 * * @param string $datatables_datetime_command The JS code for the DataTables JS library that initializes the date/time formats. * @param string[] $datatables_datetime_formats The date/time formats for moment.js. */ $datatables_datetime_command = apply_filters( 'tablepress_datatables_datetime_command', $datatables_datetime_command, $this->datatables_datetime_formats ); $datatables_pre_commands = $datatables_language_command . $datatables_datetime_command; $commands = implode( "\n", $commands ); /** * Filters the JavaScript commands that invoke the DataTables JavaScript library on all tables on the page. * * @since 1.0.0 * * @param string $commands The JS commands for the DataTables JS library. */ $commands = apply_filters( 'tablepress_all_datatables_commands', $commands ); if ( '' === $commands ) { return; } $script_template = <<<'JS' var DT_TP = {}; jQuery(($)=>{ %1$s%2$s }); JS; /** * Filters the script/jQuery wrapper code for the DataTables commands calls. * * @since 1.14.0 * * @param string $script_template Default script/jQuery wrapper code for the DataTables commands calls. */ $script_template = apply_filters( 'tablepress_all_datatables_commands_wrapper', $script_template ); $script = sprintf( $script_template, $datatables_pre_commands, $commands ); wp_add_inline_script( 'tablepress-datatables', $script ); // Prevent repeated execution (which would lead to DataTables error messages) via a static variable. $datatables_calls_printed = true; } /** * Handles the Shortcode [table id= /]. * * @since 1.0.0 * * @param array|string $shortcode_atts List of attributes that where included in the Shortcode. An empty string for empty Shortcodes like [table] or [table /]. * @return string Resulting HTML code for the table with the ID . */ public function shortcode_table( /* array|string */ $shortcode_atts ): string { $shortcode_atts = (array) $shortcode_atts; $this->maybe_enqueue_css(); $_render = TablePress::load_class( 'TablePress_Render', 'class-render.php', 'classes' ); $default_shortcode_atts = $_render->get_default_render_options(); /** * Filters the available/default attributes for the [table] Shortcode. * * @since 1.0.0 * * @param array $default_shortcode_atts The [table] Shortcode default attributes. */ $default_shortcode_atts = apply_filters( 'tablepress_shortcode_table_default_shortcode_atts', $default_shortcode_atts ); // Parse Shortcode attributes, only allow those that are specified. $shortcode_atts = shortcode_atts( $default_shortcode_atts, $shortcode_atts ); // Optional third argument left out on purpose. Use filter in the next line instead. /** * Filters the attributes that were passed to the [table] Shortcode. * * @since 1.0.0 * * @param array $shortcode_atts The attributes passed to the [table] Shortcode. */ $shortcode_atts = apply_filters( 'tablepress_shortcode_table_shortcode_atts', $shortcode_atts ); // Check, if a table with the given ID exists. $table_id = (string) preg_replace( '/[^a-zA-Z0-9_-]/', '', $shortcode_atts['id'] ); if ( ! TablePress::$model_table->table_exists( $table_id ) ) { $message = "[table “{$table_id}” not found /]
\n"; /** * Filters the "Table not found" message. * * @since 1.0.0 * * @param string $message The "Table not found" message. * @param string $table_id The current table ID. */ $message = apply_filters( 'tablepress_table_not_found_message', $message, $table_id ); return $message; } // Load table, with table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, true, true ); if ( is_wp_error( $table ) ) { $message = "[table “{$table_id}” could not be loaded /]
\n"; /** * Filters the "Table could not be loaded" message. * * @since 1.0.0 * * @param string $message The "Table could not be loaded" message. * @param string $table_id The current table ID. * @param WP_Error $table The error object for the table. */ $message = apply_filters( 'tablepress_table_load_error_message', $message, $table_id, $table ); return $message; } if ( isset( $table['is_corrupted'] ) && $table['is_corrupted'] ) { $message = "
Attention: The internal data of table “{$table_id}” is corrupted!
"; /** * Filters the "Table data is corrupted" message. * * @since 1.0.0 * * @param string $message The "Table data is corrupted" message. * @param string $table_id The current table ID. * @param string $json_error The JSON error with information about the corrupted table. */ $message = apply_filters( 'tablepress_table_corrupted_message', $message, $table_id, $table['json_error'] ); return $message; } if ( ! is_null( $shortcode_atts['datatables_custom_commands'] ) ) { /** * Filters whether the "datatables_custom_commands" Shortcode parameter is disabled. * * By default, the "datatables_custom_commands" Shortcode parameter is disabled for security reasons. * * @since 1.0.0 * * @param bool $disable Whether to disable the "datatables_custom_commands" Shortcode parameter. Default true. */ if ( apply_filters( 'tablepress_disable_custom_commands_shortcode_parameter', true ) ) { $shortcode_atts['datatables_custom_commands'] = null; } else { // Convert the HTML entity `&` back to `&` manually, as entities in Shortcodes in normal text paragraphs are sometimes double-encoded. $shortcode_atts['datatables_custom_commands'] = str_replace( '&', '&', $shortcode_atts['datatables_custom_commands'] ); // Convert HTML entities like `<`, `[`, `[`, and `&` back to their respective characters. $shortcode_atts['datatables_custom_commands'] = html_entity_decode( $shortcode_atts['datatables_custom_commands'], ENT_QUOTES | ENT_HTML5, get_option( 'blog_charset' ) ); } } // Determine options to use (if set in Shortcode, use those, otherwise use stored options, from the "Edit" screen). $render_options = array(); foreach ( $shortcode_atts as $key => $value ) { if ( is_null( $value ) && isset( $table['options'][ $key ] ) ) { // Use the table's stored option value, if the Shortcode parameter was not set. $render_options[ $key ] = $table['options'][ $key ]; } elseif ( is_string( $value ) ) { // Convert strings 'true' or 'false' to boolean, keep others. $value_lowercase = strtolower( $value ); if ( 'true' === $value_lowercase ) { $render_options[ $key ] = true; } elseif ( 'false' === $value_lowercase ) { $render_options[ $key ] = false; } else { $render_options[ $key ] = $value; } } else { // Keep all other values. $render_options[ $key ] = $value; } } // Backward compatibility: Convert boolean or numeric string "table_head" and "table_foot" options to integer. $render_options['table_head'] = absint( $render_options['table_head'] ); $render_options['table_foot'] = absint( $render_options['table_foot'] ); // Generate unique HTML ID, depending on how often this table has already been shown on this page. if ( ! isset( $this->shown_tables[ $table_id ] ) ) { $this->shown_tables[ $table_id ] = array( 'count' => 0, 'instances' => array(), ); } ++$this->shown_tables[ $table_id ]['count']; $count = $this->shown_tables[ $table_id ]['count']; $render_options['html_id'] = "tablepress-{$table_id}"; if ( $count > 1 ) { $render_options['html_id'] .= "-no-{$count}"; } /** * Filters the ID of the table HTML element. * * @since 1.0.0 * * @param string $html_id The ID of the table HTML element. * @param string $table_id The current table ID. * @param int $count Number of copies of the table with this table ID on the page. */ $render_options['html_id'] = apply_filters( 'tablepress_html_id', $render_options['html_id'], $table_id, $count ); // Generate the "Edit Table" link. $render_options['edit_table_url'] = ''; /** * Filters whether the "Edit" link below the table shall be shown. * * The "Edit" link is only shown to logged-in users who possess the necessary capability to edit the table. * * @since 1.0.0 * * @param bool $show Whether to show the "Edit" link below the table. Default true. * @param string $table_id The current table ID. */ if ( is_user_logged_in() && ! $render_options['block_preview'] && apply_filters( 'tablepress_edit_link_below_table', true, $table['id'] ) && current_user_can( 'tablepress_edit_table', $table['id'] ) ) { $render_options['edit_table_url'] = TablePress::url( array( 'action' => 'edit', 'table_id' => $table['id'] ) ); } /** * Filters the render options for the table. * * The render options are determined from the settings on a table's "Edit" screen and the Shortcode parameters. * * @since 1.0.0 * * @param array $render_options The render options for the table. * @param array $table The current table. */ $render_options = apply_filters( 'tablepress_table_render_options', $render_options, $table ); // Backward compatibility: Convert boolean "table_head" and "table_foot" options to integer, in case they were overwritten via the filter hook. $render_options['table_head'] = absint( $render_options['table_head'] ); $render_options['table_foot'] = absint( $render_options['table_foot'] ); // Check if table output shall and can be loaded from the transient cache, otherwise generate the output. if ( $render_options['cache_table_output'] && ! is_user_logged_in() ) { // Hash the Render Options array to get a unique cache identifier. $table_hash = md5( wp_json_encode( $render_options, TABLEPRESS_JSON_OPTIONS ) ); // @phpstan-ignore argument.type $transient_name = 'tablepress_' . $table_hash; // Attention: This string must not be longer than 45 characters! $output = get_transient( $transient_name ); if ( false === $output || '' === $output ) { // Render/generate the table HTML, as it was not found in the cache. $_render->set_input( $table, $render_options ); $output = $_render->get_output( 'html' ); // Save render output in a transient, set cache timeout to 24 hours. set_transient( $transient_name, $output, DAY_IN_SECONDS ); // Update output caches list transient (necessary for cache invalidation upon table saving). $caches_list_transient_name = 'tablepress_c_' . md5( $table_id ); $caches_list = get_transient( $caches_list_transient_name ); if ( false === $caches_list ) { $caches_list = array(); } else { $caches_list = (array) json_decode( $caches_list, true ); } if ( ! in_array( $transient_name, $caches_list, true ) ) { $caches_list[] = $transient_name; } set_transient( $caches_list_transient_name, wp_json_encode( $caches_list, TABLEPRESS_JSON_OPTIONS ), 2 * DAY_IN_SECONDS ); } else { /** * Filters the cache hit comment message. * * @since 1.0.0 * * @param string $comment The cache hit comment message. */ $output .= apply_filters( 'tablepress_cache_hit_comment', "" ); } } else { // Render/generate the table HTML, as no cache is to be used. $_render->set_input( $table, $render_options ); $output = $_render->get_output( 'html' ); } // If DataTables is to be and can be used with this instance of a table, process its parameters and register the call for inclusion in the footer. if ( $render_options['use_datatables'] && 0 < $render_options['table_head'] && ! str_contains( $output, 'tbody-has-connected-cells' ) // The Render class adds this CSS class to the `` element if the table has connected cells in the ``. ) { // Get options for the DataTables JavaScript library from the table's render options. $js_options = array(); foreach ( array( 'alternating_row_colors', 'datatables_sort', 'datatables_paginate', 'datatables_paginate', 'datatables_paginate_entries', 'datatables_lengthchange', 'datatables_filter', 'datatables_info', 'datatables_scrollx', 'datatables_scrolly', 'datatables_locale', 'datatables_custom_commands', ) as $option ) { $js_options[ $option ] = $render_options[ $option ]; } /** * Filters the JavaScript options for the table. * * The JavaScript options are determined from the settings on a table's "Edit" screen and the Shortcode parameters. * They are part of the render options and can be overwritten with Shortcode parameters. * * @since 1.0.0 * * @param array $js_options The JavaScript options for the table. * @param string $table_id The current table ID. * @param array $render_options The render options for the table. */ $js_options = apply_filters( 'tablepress_table_js_options', $js_options, $table_id, $render_options ); $this->shown_tables[ $table_id ]['instances'][ (string) $render_options['html_id'] ] = $js_options; // DataTables datetime format string handling. if ( '' !== $render_options['datatables_datetime'] ) { $render_options['datatables_datetime'] = explode( '|', $render_options['datatables_datetime'] ); foreach ( $render_options['datatables_datetime'] as $datetime_format ) { $datetime_format = trim( $datetime_format ); if ( '' !== $datetime_format && ! in_array( $datetime_format, $this->datatables_datetime_formats, true ) ) { $this->datatables_datetime_formats[] = $datetime_format; } } } } // Maybe print a list of used render options. if ( $render_options['shortcode_debug'] && is_user_logged_in() ) { $output .= '
' . var_export( $render_options, true ) . '
'; // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export } return $output; } /** * Handles the Shortcode [table-info id= field= /]. * * @since 1.0.0 * * @param array|string $shortcode_atts List of attributes that where included in the Shortcode. An empty string for empty Shortcodes like [table] or [table /]. * @return string Text that replaces the Shortcode (error message or asked-for information). */ public function shortcode_table_info( /* array|string */ $shortcode_atts ): string { $shortcode_atts = (array) $shortcode_atts; // Parse Shortcode attributes, only allow those that are specified. $default_shortcode_atts = array( 'id' => '', 'field' => '', 'format' => '', ); /** * Filters the available/default attributes for the [table-info] Shortcode. * * @since 1.0.0 * * @param array $default_shortcode_atts The [table-info] Shortcode default attributes. */ $default_shortcode_atts = apply_filters( 'tablepress_shortcode_table_info_default_shortcode_atts', $default_shortcode_atts ); $shortcode_atts = shortcode_atts( $default_shortcode_atts, $shortcode_atts ); // Optional third argument left out on purpose. Use filter in the next line instead. /** * Filters the attributes that were passed to the [table-info] Shortcode. * * @since 1.0.0 * * @param array $shortcode_atts The attributes passed to the [table-info] Shortcode. */ $shortcode_atts = apply_filters( 'tablepress_shortcode_table_info_shortcode_atts', $shortcode_atts ); /** * Filters whether the output of the [table-info] Shortcode is overwritten/short-circuited. * * @since 1.0.0 * * @param false|string $overwrite Whether the [table-info] output is overwritten. Return false for the regular content, and a string to overwrite the output. * @param array $shortcode_atts The attributes passed to the [table-info] Shortcode. */ $overwrite = apply_filters( 'tablepress_shortcode_table_info_overwrite', false, $shortcode_atts ); if ( is_string( $overwrite ) ) { return $overwrite; } // Check, if a table with the given ID exists. $table_id = preg_replace( '/[^a-zA-Z0-9_-]/', '', $shortcode_atts['id'] ); if ( ! TablePress::$model_table->table_exists( $table_id ) ) { $message = "[table “{$table_id}” not found /]
\n"; /** This filter is documented in controllers/controller-frontend.php */ $message = apply_filters( 'tablepress_table_not_found_message', $message, $table_id ); return $message; } // Load table, with table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, true, true ); if ( is_wp_error( $table ) ) { $message = "[table “{$table_id}” could not be loaded /]
\n"; /** This filter is documented in controllers/controller-frontend.php */ $message = apply_filters( 'tablepress_table_load_error_message', $message, $table_id, $table ); return $message; } $field = (string) preg_replace( '/[^a-z_]/', '', strtolower( $shortcode_atts['field'] ) ); $format = (string) preg_replace( '/[^a-z]/', '', strtolower( $shortcode_atts['format'] ) ); // Generate output, depending on what information (field) was asked for. switch ( $field ) { case 'name': case 'description': $output = $table[ $field ]; break; case 'last_modified': switch ( $format ) { case 'raw': case 'mysql': $output = $table['last_modified']; break; case 'human': $modified_timestamp = date_create( $table['last_modified'], wp_timezone() ); if ( false === $modified_timestamp ) { $modified_timestamp = $table['last_modified']; } else { $modified_timestamp = $modified_timestamp->getTimestamp(); } $current_timestamp = time(); $time_diff = $current_timestamp - $modified_timestamp; // Time difference is only shown up to one week. if ( $time_diff >= 0 && $time_diff < WEEK_IN_SECONDS ) { $output = sprintf( __( '%s ago', 'default' ), human_time_diff( $modified_timestamp, $current_timestamp ) ); } else { $output = TablePress::format_datetime( $table['last_modified'], '
' ); } break; case 'date': $output = TablePress::format_datetime( $table['last_modified'], get_option( 'date_format' ) ); break; case 'time': $output = TablePress::format_datetime( $table['last_modified'], get_option( 'time_format' ) ); break; default: $output = TablePress::format_datetime( $table['last_modified'] ); break; } break; case 'last_editor': $output = TablePress::get_user_display_name( $table['options']['last_editor'] ); break; case 'author': $output = TablePress::get_user_display_name( $table['author'] ); break; case 'number_rows': $output = count( $table['data'] ); if ( 'raw' !== $format ) { $output -= $table['options']['table_head']; $output -= $table['options']['table_foot']; } break; case 'number_columns': $output = count( $table['data'][0] ); break; default: $output = "[table-info field “{$field}” not found in table “{$table_id}” /]
\n"; /** * Filters the "table info field not found" message. * * @since 1.0.0 * * @param string $output The "table info field not found" message. * @param array $table The current table. * @param string $field The field that was not found. * @param string $format The return format for the field. */ $output = apply_filters( 'tablepress_table_info_not_found_message', $output, $table, $field, $format ); } /** * Filters the output of the [table-info] Shortcode. * * @since 1.0.0 * * @param string $output The output of the [table-info] Shortcode. * @param array $table The current table. * @param array $shortcode_atts The attributes passed to the [table-info] Shortcode. */ $output = apply_filters( 'tablepress_shortcode_table_info_output', $output, $table, $shortcode_atts ); return $output; } /** * Expands the WP Search to also find posts and pages that have a search term in a table that is shown in them. * * This is done by looping through all search terms and TablePress tables and searching there for the search term, * saving all tables's IDs that have a search term and then expanding the WP query to search for posts or pages that have the * Shortcode for one of these tables in their content. * * @since 1.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search_sql Current part of the "WHERE" clause of the SQL statement used to get posts/pages from the WP database that is related to searching. * @return string Eventually extended SQL "WHERE" clause, to also find posts/pages with Shortcodes in them. */ public function posts_search_filter( /* string */ $search_sql ): string { // Don't use a type hint in the method declaration as there can be cases where `null` is passed to the filter hook callback somehow. global $wpdb; // Protect against cases where `null` is somehow passed to the filter hook callback. if ( ! is_string( $search_sql ) ) { // @phpstan-ignore function.alreadyNarrowedType (The `is_string()` check is needed as the input is coming from a filter hook.) return ''; } if ( ! is_search() || ! is_main_query() ) { return $search_sql; } // Get variable that contains all search terms, parsed from $_GET['s'] by WP. $search_terms = get_query_var( 'search_terms' ); if ( empty( $search_terms ) || ! is_array( $search_terms ) ) { return $search_sql; } // Load all table IDs and prime post meta cache for cached access to options and visibility settings of the tables, don't run filter hook. $table_ids = TablePress::$model_table->load_all( true, false ); // Array of all search words that were found, and the table IDs where they were found. $query_result = array(); foreach ( $table_ids as $table_id ) { // Load table, with table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, true, true ); // Skip tables that could not be loaded. if ( is_wp_error( $table ) ) { continue; } // Do not search in corrupted tables. if ( isset( $table['is_corrupted'] ) && $table['is_corrupted'] ) { continue; } foreach ( $search_terms as $search_term ) { if ( ( $table['options']['print_name'] && false !== stripos( $table['name'], (string) $search_term ) ) || ( $table['options']['print_description'] && false !== stripos( $table['description'], (string) $search_term ) ) ) { // Found the search term in the name or description (and they are shown). $query_result[ $search_term ][] = $table_id; // Add table ID to result list. // No need to continue searching this search term in this table. continue; } // Search search term in visible table cells (without taking Shortcode parameters into account!). foreach ( $table['data'] as $row_idx => $table_row ) { if ( 0 === $table['visibility']['rows'][ $row_idx ] ) { // Row is hidden, so don't search in it. continue; } foreach ( $table_row as $col_idx => $table_cell ) { if ( 0 === $table['visibility']['columns'][ $col_idx ] ) { // Column is hidden, so don't search in it. continue; } // @todo Cells are not evaluated here, so math formulas are searched. if ( false !== stripos( $table_cell, (string) $search_term ) ) { // Found the search term in the cell content. $query_result[ $search_term ][] = $table_id; // Add table ID to result list // No need to continue searching this search term in this table. continue 3; } } } } } // For all found table IDs for each search term, add additional OR statement to the SQL "WHERE" clause. // If $_GET['exact'] is set, WordPress doesn't use % in SQL LIKE clauses. $exact = get_query_var( 'exact' ); $n = ( empty( $exact ) ) ? '%' : ''; $search_sql = $wpdb->remove_placeholder_escape( $search_sql ); foreach ( $query_result as $search_term => $table_ids ) { $search_term = esc_sql( $wpdb->esc_like( $search_term ) ); $old_or = "OR ({$wpdb->posts}.post_content LIKE '{$n}{$search_term}{$n}')"; // @phpstan-ignore encapsedStringPart.nonString (The esc_sql() call above returns a string, as a string is passed.) $table_ids = implode( '|', $table_ids ); $regexp = '\\\\[' . TablePress::$shortcode . ' id=(["\\\']?)(' . $table_ids . ')([\]"\\\' /])'; // ' needs to be single escaped, [ double escaped (with \\) in mySQL $new_or = $old_or . " OR ({$wpdb->posts}.post_content REGEXP '{$regexp}')"; $search_sql = str_replace( $old_or, $new_or, $search_sql ); } $search_sql = $wpdb->add_placeholder_escape( $search_sql ); return $search_sql; } /** * Callback function for rendering the tablepress/table block. * * @since 2.0.0 * * @param array $block_attributes List of attributes that where included in the block settings. * @return string Resulting HTML code for the table. */ public function table_block_render_callback( array $block_attributes ): string { // Don't return anything if no table was selected. if ( '' === $block_attributes['id'] ) { return ''; } if ( '' !== trim( $block_attributes['parameters'] ) ) { $render_attributes = shortcode_parse_atts( $block_attributes['parameters'] ); } else { $render_attributes = array(); } $render_attributes['id'] = $block_attributes['id']; return $this->shortcode_table( $render_attributes ); } /** * Registers the TablePress Elementor widgets. * * @since 3.1.0 * * @param \Elementor\Widgets_Manager $widgets_manager Elementor widgets manager. */ public function register_elementor_widgets( \Elementor\Widgets_Manager $widgets_manager ): void { TablePress::load_file( 'class-elementor-widget-table.php', 'classes' ); $widgets_manager->register( new TablePress\Elementor\TablePressTableWidget() ); // @phpstan-ignore method.notFound (Elementor methods are not in the stubs.) } /** * Enqueues the TablePress Elementor Editor CSS styles. * * @since 3.1.0 */ public function enqueue_elementor_editor_styles(): void { $svg_url = plugins_url( 'admin/img/tablepress-editor-button.svg', TABLEPRESS__FILE__ ); wp_register_style( 'tablepress-elementor', false ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion wp_add_inline_style( 'tablepress-elementor', << .tablepress-elementor-icon) { height: 43.5px; } .tablepress-elementor-icon { display: inline-block; height: 28px; width: 28px; background-image: url({$svg_url}); background-repeat: no-repeat; background-position: center; background-size: 28px auto; } CSS ); wp_enqueue_style( 'tablepress-elementor' ); } } // class TablePress_Frontend_Controller PK! index.phpnu[

update your WordPress installation to at least version %2$s!', 'tablepress' ), esc_url( self_admin_url( 'update-core.php' ) ), '6.2' ); } else { printf( __( 'Please ask your site’s administrator to update WordPress to at least version %1$s!', 'tablepress' ), '6.2' ); } ?>

Learn more about updating PHP or contact your server administrator.', 'tablepress' ), esc_url( wp_get_update_php_url() ) ); ?>

> */ protected array $view_actions = array(); /** * Instance of the TablePress Admin View that is rendered. * * @since 1.0.0 */ protected \TablePress_View $view; /** * Initialize the Admin Controller, determine location the admin menu, set up actions. * * @since 1.0.0 */ public function __construct() { parent::__construct(); // Handler for changing the number of shown tables in the list of tables (via WP List Table class). add_filter( 'set_screen_option_tablepress_list_per_page', array( $this, 'save_list_tables_screen_option' ), 10, 3 ); add_action( 'admin_menu', array( $this, 'add_admin_menu_entry' ) ); add_action( 'admin_init', array( $this, 'add_admin_actions' ) ); add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) ); add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) ); } /** * Handler for changing the number of shown tables in the list of tables (via WP List Table class). * * @since 1.0.0 * * @param mixed $screen_option Current value of the filter (probably bool false). * @param string $option Option in which the setting is stored. * @param int $value Current value of the setting. * @return int Changed value of the setting */ public function save_list_tables_screen_option( /* mixed */ $screen_option, string $option, int $value ): int { return $value; } /** * Add admin screens to the correct place in the admin menu. * * @since 1.0.0 */ public function add_admin_menu_entry(): void { // Callback for all menu entries. $callback = array( $this, 'show_admin_page' ); /** * Filters the TablePress admin menu entry name. * * @since 1.0.0 * * @param string $entry_name The admin menu entry name. Default "TablePress". */ $admin_menu_entry_name = apply_filters( 'tablepress_admin_menu_entry_name', 'TablePress' ); $this->init_view_actions(); $min_access_cap = $this->view_actions['list']['required_cap']; if ( TablePress::$controller->is_top_level_page ) { $icon_url = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMCIgaGVpZ2h0PSIyMCIgdmlld0JveD0iLTMyIC0zMiA2NCA2NCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTAtMjUuODU0aC0yNS44NTR2NTEuNzA4aDUxLjcwOFYwSDIxdjIxaC00MnYtNDJIMFoiLz48cGF0aCBkPSJNLTE4LTE4aDEwdjEwaC0xMHpNLTE4LTVoMTBWNWgtMTB6TS01LTVINVY1SC01ek0tMTggOGgxMHYxMGgtMTB6TS01IDhINXYxMEgtNXpNOCA4aDEwdjEwSDh6TTUtMzFoNi4xOHY2LjE4SDV6TTE5LTI1aDYuMTh2Ni4xOEgxOXpNMC0xNWgzLjgydjMuODJIMHpNMTAtMjBoMy44MnYzLjgySDEwek0yNS0xMmgzLjgydjMuODJIMjV6TTgtMTNoMTB2MTBIOHoiLz48L3N2Zz4='; switch ( TablePress::$controller->parent_page ) { case 'top': $position = 3; // Position of Dashboard + 1. break; case 'bottom': $position = isset( $GLOBALS['_wp_last_utility_menu'] ) ? ++$GLOBALS['_wp_last_utility_menu'] : 80; break; case 'middle': default: $position = isset( $GLOBALS['_wp_last_object_menu'] ) ? ++$GLOBALS['_wp_last_object_menu'] : 25; break; } // Prevent overwriting existing menu entries. while ( isset( $GLOBALS['menu'][ $position ] ) ) { ++$position; } add_menu_page( 'TablePress', $admin_menu_entry_name, $min_access_cap, 'tablepress', $callback, $icon_url, $position ); // @phpstan-ignore argument.type foreach ( $this->view_actions as $action => $entry ) { if ( ! $entry['show_entry'] ) { continue; } $slug = 'tablepress'; if ( 'list' !== $action ) { $slug .= '_' . $action; } // @phpstan-ignore argument.type, argument.type $page_hook = add_submenu_page( 'tablepress', sprintf( __( '%1$s ‹ %2$s', 'tablepress' ), $entry['page_title'], 'TablePress' ), $entry['admin_menu_title'], $entry['required_cap'], $slug, $callback ); if ( false !== $page_hook ) { $this->page_hooks[] = $page_hook; } } } else { // @phpstan-ignore argument.type $page_hook = add_submenu_page( TablePress::$controller->parent_page, 'TablePress', $admin_menu_entry_name, $min_access_cap, 'tablepress', $callback ); if ( false !== $page_hook ) { $this->page_hooks[] = $page_hook; } } } /** * Set up handlers for user actions in the backend that exceed plain viewing. * * @since 1.0.0 */ public function add_admin_actions(): void { // Register the callbacks for processing action requests. $post_actions = array( 'list', 'add', 'options', 'export', 'import' ); $get_actions = array( 'hide_message', 'delete_table', 'copy_table', 'preview_table', 'editor_button_thickbox', 'uninstall_tablepress' ); foreach ( $post_actions as $action ) { add_action( "admin_post_tablepress_{$action}", array( $this, "handle_post_action_{$action}" ) ); } foreach ( $get_actions as $action ) { add_action( "admin_post_tablepress_{$action}", array( $this, "handle_get_action_{$action}" ) ); } // Register callbacks to trigger load behavior for admin pages. foreach ( $this->page_hooks as $page_hook ) { add_action( "load-{$page_hook}", array( $this, 'load_admin_page' ) ); } /** * Filters whether the legacy editor button should be loaded on the post editing screen. * * @since 2.1.0 * * @param bool $load_button Whether to load the legacy editor button. Default true. */ if ( apply_filters( 'tablepress_add_legacy_editor_button', true ) ) { $pages_with_editor_button = array( 'post.php', 'post-new.php' ); foreach ( $pages_with_editor_button as $editor_page ) { add_action( "load-{$editor_page}", array( $this, 'add_editor_buttons' ) ); } } if ( ! is_network_admin() && ! is_user_admin() ) { add_action( 'admin_bar_menu', array( $this, 'add_wp_admin_bar_new_content_menu_entry' ), 71 ); } add_action( 'load-plugins.php', array( $this, 'plugins_page' ) ); } /** * Loads additional JavaScript code for the TablePress table block (in the block editor context). * * @since 2.2.0 */ public function enqueue_block_editor_assets(): void { /* * Register the `react-jsx-runtime` polyfill, if it is not already registered. * This is needed as a polyfill for WP < 6.6, and can be removed once WP 6.6 is the minimum requirement for TablePress. */ if ( ! wp_script_is( 'react-jsx-runtime', 'registered' ) ) { wp_register_script( 'react-jsx-runtime', plugins_url( 'admin/js/react-jsx-runtime.min.js', TABLEPRESS__FILE__ ), array( 'react' ), TablePress::version, true ); } // Add table information for the block editor to the page. $handle = generate_block_asset_handle( 'tablepress/table', 'editorScript' ); $data = $this->get_block_editor_data(); wp_add_inline_script( $handle, $data, 'before' ); } /** * Loads additional CSS code for the TablePress table block (inside the block editor iframe). * * @since 2.2.0 */ public function enqueue_block_assets(): void { // Load the TablePress default CSS and the user's "Custom CSS" in the block editor iframe. if ( is_admin() ) { TablePress::$controller->maybe_enqueue_css(); } } /** * Gets the inline data that is referenced by the Block Editor JavaScript code for the TablePress blocks. * * @since 2.0.0 * * @return string JavaScript code for the Block Editor. */ protected function get_block_editor_data(): string { $tables = array(); // Load all table IDs without priming the post meta cache, as table options/visibility are not needed. $table_ids = TablePress::$model_table->load_all( false ); foreach ( $table_ids as $table_id ) { // Load table, without table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, false, false ); // Skip tables that could not be loaded. if ( is_wp_error( $table ) ) { continue; } if ( '' === trim( $table['name'] ) ) { $table['name'] = __( '(no name)', 'tablepress' ); } $tables[ $table_id ] = esc_html( $table['name'] ); } /** * Filters the list of table IDs and names that is passed to the block editor, and is then used in the dropdown of the TablePress table block. * * @since 2.0.0 * * @param array $tables List of table names, the table ID is the array key. */ $tables = apply_filters( 'tablepress_block_editor_tables_list', $tables ); $tables = wp_json_encode( $tables, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); if ( false === $tables ) { // JSON encoding failed, return an error object. Use a prefixed "_error" key to avoid conflicts with intentionally added "error" keys. $tables = '{ "_error": "The data could not be encoded to JSON!" }'; } // Print the JSON data inside a `JSON.parse()` call in JS for speed gains, with necessary escaping of `\` and `'`. $tables = str_replace( array( '\\', "'" ), array( '\\\\', "\'" ), $tables ); $shortcode = esc_js( TablePress::$shortcode ); $template = TablePress::$model_table->get_table_template(); $template = wp_json_encode( $template['options'], JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); if ( false === $template ) { // JSON encoding failed, return an error object. Use a prefixed "_error" key to avoid conflicts with intentionally added "error" keys. $template = '{ "_error": "The data could not be encoded to JSON!" }'; } // Print the JSON data inside a `JSON.parse()` call in JS for speed gains, with necessary escaping of `\` and `'`. $template = str_replace( array( '\\', "'" ), array( '\\\\', "\'" ), $template ); /** * Filters whether the table block preview should be loaded via a in the block editor. * * @since 2.0.0 * * @param bool $load_block_preview Whether the table block preview should be loaded. */ $load_block_preview = apply_filters( 'tablepress_show_block_editor_preview', true ); $load_block_preview = (bool) $load_block_preview ? 'true' : 'false'; $url = ''; if ( current_user_can( 'tablepress_list_tables' ) ) { $url = TablePress::url( array( 'action' => 'list' ) ); } return <<enqueue_script( 'quicktags-button', array( 'quicktags', 'media-upload' ), array( 'editor_button' => array( 'caption' => __( 'Table', 'tablepress' ), 'title' => __( 'Insert a TablePress table', 'tablepress' ), 'thickbox_title' => __( 'Insert a TablePress table', 'tablepress' ), 'thickbox_url' => TablePress::url( array( 'action' => 'editor_button_thickbox' ), true, 'admin-post.php' ), ), ), ); // TinyMCE integration. if ( user_can_richedit() ) { add_filter( 'mce_external_plugins', array( $this, 'add_tinymce_plugin' ) ); add_filter( 'mce_buttons', array( $this, 'add_tinymce_button' ) ); } } /** * Adds the "Table" button to the TinyMCE toolbar. * * @since 1.0.0 * * @param string[] $buttons Current set of buttons in the TinyMCE toolbar. * @return string[] Extended set of buttons in the TinyMCE toolbar, including the "Table" button. */ public function add_tinymce_button( array $buttons ): array { $buttons[] = 'tablepress_insert_table'; return $buttons; } /** * Registers the "Table" button plugin for the TinyMCE editor. * * @since 1.0.0 * * @param array $plugins Current set of registered TinyMCE plugins. * @return array Extended set of registered TinyMCE plugins, including the "Table" button plugin. */ public function add_tinymce_plugin( array $plugins ): array { $plugins['tablepress_tinymce'] = plugins_url( 'admin/js/build/tinymce-button.js', TABLEPRESS__FILE__ ); return $plugins; } /** * Add "TablePress Table" entry to "New" dropdown menu in the WP Admin Bar. * * @since 1.0.0 * * @param WP_Admin_Bar $wp_admin_bar The current WP Admin Bar object. */ public function add_wp_admin_bar_new_content_menu_entry( WP_Admin_Bar $wp_admin_bar ): void { if ( ! current_user_can( 'tablepress_add_tables' ) ) { return; } // Don't load TablePress assets on the Freemius opt-in/activation screen. if ( tb_tp_fs()->is_activation_mode() && tb_tp_fs()->is_activation_page() ) { return; } $wp_admin_bar->add_menu( array( 'parent' => 'new-content', 'id' => 'new-tablepress-table', 'title' => __( 'TablePress table', 'tablepress' ), 'href' => TablePress::url( array( 'action' => 'add' ) ), ) ); } /** * Handle actions for loading of Plugins page. * * @since 1.0.0 */ public function plugins_page(): void { // Add additional links on Plugins page. add_filter( 'plugin_action_links_' . TABLEPRESS_BASENAME, array( $this, 'add_plugin_action_links' ) ); add_filter( 'plugin_row_meta', array( $this, 'add_plugin_row_meta' ), 10, 2 ); $incompatible_superseded_extensions = array( 'tablepress-datatables-alphabetsearch/tablepress-datatables-alphabetsearch.php', 'tablepress-datatables-column-filter-widgets/tablepress-datatables-column-filter-widgets.php', 'tablepress-datatables-columnfilter/tablepress-datatables-columnfilter.php', 'tablepress-datatables-fixedcolumns/tablepress-datatables-fixedcolumns.php', 'tablepress-datatables-inverted-filter/tablepress-datatables-inverted-filter.php', 'tablepress-datatables-row-details/tablepress-datatables-row-details.php', 'tablepress-datatables-rowgroup/tablepress-datatables-rowgroup.php', 'tablepress-responsive-tables/tablepress-responsive-tables.php', ); foreach ( $incompatible_superseded_extensions as $plugin_file ) { add_action( "after_plugin_row_{$plugin_file}", array( $this, 'add_superseded_extension_meta_row' ), 10, 3 ); } } /** * Add links to the TablePress entry in the "Plugin" column on the Plugins page. * * @since 1.0.0 * * @param string[] $links List of links to print in the "Plugin" column on the Plugins page. * @return string[] Extended list of links to print in the "Plugin" column on the Plugins page. */ public function add_plugin_action_links( array $links ): array { if ( current_user_can( 'tablepress_list_tables' ) ) { $links[] = '' . __( 'Plugin page', 'tablepress' ) . ''; } return $links; } /** * Add links to the TablePress entry in the "Description" column on the Plugins page. * * @since 1.0.0 * * @param string[] $links List of links to print in the "Description" column on the Plugins page. * @param string $file Name of the plugin. * @return string[] Extended list of links to print in the "Description" column on the Plugins page. */ public function add_plugin_row_meta( array $links, string $file ): array { if ( TABLEPRESS_BASENAME === $file ) { $links[] = '' . __( 'FAQ', 'tablepress' ) . ''; $links[] = '' . __( 'Documentation', 'tablepress' ) . ''; $links[] = '' . __( 'Support', 'tablepress' ) . ''; if ( ! TABLEPRESS_IS_PLAYGROUND_PREVIEW && tb_tp_fs()->is_free_plan() ) { $links[] = '' . __( 'Go Premium', 'tablepress' ) . ''; } } return $links; } /** * Prints a superseded extension notice below certain TablePress Extension plugins' meta rows on the "Plugins" screen. * * @since 2.4.1 * * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. * @param string $status Status filter currently applied to the plugin list. */ public function add_superseded_extension_meta_row( string $plugin_file, array $plugin_data, string $status ): void { if ( ! is_plugin_active( $plugin_file ) ) { return; } ?>
is_top_level_page ) { // Or, for sub-menu entry of an admin menu "TablePress" entry, get it from the "page" GET parameter. if ( 'tablepress' !== $_GET['page'] ) { // Actions that are top-level entries, but don't have an action GET parameter (action is after last _ in string). $action = substr( $_GET['page'], 11 ); // $_GET['page'] has the format 'tablepress_{$action}' } } // Check if action is a supported action, and whether the user is allowed to access this screen. if ( ! isset( $this->view_actions[ $action ] ) || ! current_user_can( $this->view_actions[ $action ]['required_cap'] ) ) { // @phpstan-ignore argument.type (The array value for the capability is always a string.) wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } // Don't load TablePress assets on the Freemius opt-in/activation screen. if ( tb_tp_fs()->is_activation_mode() && tb_tp_fs()->is_activation_page() ) { return; } // Changes current screen ID and pagenow variable in JS, to enable automatic meta box JS handling. set_current_screen( "tablepress_{$action}" ); /* * Set the `$typenow` global to the current CPT ourselves, as `WP_Screen::get()` does not determine the CPT correctly. * This is necessary as the WP Admin Menu can otherwise highlight wrong entries, see https://github.com/TablePress/TablePress/issues/24. */ if ( isset( $_GET['post_type'] ) && post_type_exists( $_GET['post_type'] ) ) { $GLOBALS['typenow'] = $_GET['post_type']; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited } // Pre-define some view data. $data = array( 'view_actions' => $this->view_actions, 'message' => ( ! empty( $_GET['message'] ) ) ? $_GET['message'] : false, 'error_details' => ( ! empty( $_GET['error_details'] ) ) ? $_GET['error_details'] : '', 'site_used_editor' => TablePress::site_used_editor(), ); // Depending on the action, load more necessary data for the corresponding view. switch ( $action ) { case 'list': $data['table_id'] = ( ! empty( $_GET['table_id'] ) ) ? $_GET['table_id'] : false; // Prime the post meta cache for cached loading of last_editor. $data['table_ids'] = TablePress::$model_table->load_all( true ); $data['messages']['donation_nag'] = $this->maybe_show_donation_message(); $data['messages']['first_visit'] = ! $data['messages']['donation_nag'] && TablePress::$model_options->get( 'message_first_visit' ); $data['messages']['plugin_update'] = TablePress::$model_options->get( 'message_plugin_update' ); $data['messages']['superseded_extensions'] = current_user_can( 'manage_options' ) && TablePress::$model_options->get( 'message_superseded_extensions' ); $data['table_count'] = count( $data['table_ids'] ); break; case 'about': $data['first_activation'] = TablePress::$model_options->get( 'first_activation' ); break; case 'options': /* * Maybe try saving "Custom CSS" to a file: * (called here, as the credentials form posts to this handler again, due to how `request_filesystem_credentials()` works) */ if ( isset( $_GET['item'] ) && 'save_custom_css' === $_GET['item'] ) { TablePress::check_nonce( 'options', $_GET['item'] ); // Nonce check here, as we don't have an explicit handler, and even viewing the screen needs to be checked. $action = 'options_custom_css'; // To load a different view. // Try saving "Custom CSS" to a file, otherwise this gets the HTML for the credentials form. $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' ); $result = $tablepress_css->save_custom_css_to_file_plugin_options( TablePress::$model_options->get( 'custom_css' ), TablePress::$model_options->get( 'custom_css_minified' ) ); if ( is_string( $result ) ) { $data['credentials_form'] = $result; // This will only be called if the save function doesn't do a redirect. } elseif ( true === $result ) { /* * At this point, saving was successful, so enable usage of CSS in files again, * and also increase the "Custom CSS" version number (for cache busting). */ TablePress::$model_options->update( array( 'use_custom_css_file' => true, 'custom_css_version' => TablePress::$model_options->get( 'custom_css_version' ) + 1, ) ); TablePress::redirect( array( 'action' => 'options', 'message' => 'success_save' ) ); } else { // Leaves only $result === false. TablePress::redirect( array( 'action' => 'options', 'message' => 'success_save_error_custom_css' ) ); } break; } $data['frontend_options']['use_custom_css'] = TablePress::$model_options->get( 'use_custom_css' ); $data['frontend_options']['custom_css'] = TablePress::$model_options->get( 'custom_css' ); $data['user_options']['parent_page'] = TablePress::$controller->parent_page; break; case 'edit': if ( empty( $_GET['table_id'] ) ) { TablePress::redirect( array( 'action' => 'list', 'message' => 'error_no_table' ) ); } // Load table, with table data, options, and visibility settings. $data['table'] = TablePress::$model_table->load( $_GET['table_id'], true, true ); if ( is_wp_error( $data['table'] ) ) { TablePress::redirect( array( 'action' => 'list', 'message' => 'error_load_table', 'error_details' => TablePress::get_wp_error_string( $data['table'] ) ) ); } if ( ! current_user_can( 'tablepress_edit_table', $_GET['table_id'] ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } break; case 'export': // Load all table IDs without priming the post meta cache, as table options/visibility are not needed. $table_ids = TablePress::$model_table->load_all( false ); $data['tables'] = array(); foreach ( $table_ids as $table_id ) { if ( ! current_user_can( 'tablepress_export_table', $table_id ) ) { continue; } // Load table, without table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, false, false ); // Skip tables that could not be loaded. if ( is_wp_error( $table ) ) { continue; } $data['tables'][ $table['id'] ] = $table['name']; } $data['tables_count'] = TablePress::$model_table->count_tables(); $data['export_ids'] = ( ! empty( $_GET['table_id'] ) ) ? explode( ',', $_GET['table_id'] ) : array(); $exporter = TablePress::load_class( 'TablePress_Export', 'class-export.php', 'classes' ); $data['zip_support_available'] = $exporter->zip_support_available; $data['export_formats'] = $exporter->export_formats; $data['csv_delimiters'] = $exporter->csv_delimiters; $data['export_format'] = ( ! empty( $_GET['export_format'] ) ) ? $_GET['export_format'] : 'csv'; $data['csv_delimiter'] = ( ! empty( $_GET['csv_delimiter'] ) ) ? $_GET['csv_delimiter'] : _x( ',', 'Default CSV delimiter in the translated language (";", ",", or "tab")', 'tablepress' ); break; case 'import': // Load all table IDs without priming the post meta cache, as table options/visibility are not needed. $table_ids = TablePress::$model_table->load_all( false ); $data['tables'] = array(); foreach ( $table_ids as $table_id ) { if ( ! current_user_can( 'tablepress_edit_table', $table_id ) ) { continue; } // Load table, without table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, false, false ); // Skip tables that could not be loaded. if ( is_wp_error( $table ) ) { continue; } $data['tables'][ $table['id'] ] = $table['name']; } $data['table_ids'] = $table_ids; // Backward compatibility for the retired "Table Auto Update" Extension, which still relies on this variable name. $data['tables_count'] = TablePress::$model_table->count_tables(); $importer = TablePress::load_class( 'TablePress_Import', 'class-import.php', 'classes' ); $data['import_type'] = ( ! empty( $_GET['import_type'] ) ) ? $_GET['import_type'] : 'add'; $data['import_existing_table'] = ( ! empty( $_GET['import_existing_table'] ) ) ? $_GET['import_existing_table'] : ''; $data['import_source'] = ( ! empty( $_GET['import_source'] ) ) ? $_GET['import_source'] : 'file-upload'; $data['import_url'] = ( ! empty( $_GET['import_url'] ) ) ? wp_unslash( $_GET['import_url'] ) : 'https://'; $data['import_server'] = ( ! empty( $_GET['import_server'] ) ) ? wp_unslash( $_GET['import_server'] ) : ABSPATH; $data['import_form-field'] = ( ! empty( $_GET['import_form-field'] ) ) ? wp_unslash( $_GET['import_form-field'] ) : ''; $data['legacy_import'] = ( ! empty( $_GET['legacy_import'] ) ) ? $_GET['legacy_import'] : 'false'; break; } /** * Filters the data that is passed to the current TablePress View. * * @since 1.0.0 * * @param array $data Data for the view. * @param string $action The current action for the view. */ $data = apply_filters( 'tablepress_view_data', $data, $action ); // Prepare and initialize the view. $this->view = TablePress::load_view( $action, $data ); } /** * Render the view that has been initialized in load_admin_page() (called by WordPress when the actual page content is needed). * * @since 1.0.0 */ public function show_admin_page(): void { $this->view->render(); } /** * Decides whether a message about Premium versions (previously, about donations) shall be shown on the "All Tables" screen, depending on passed days since installation and whether it was shown before. * * @since 1.0.0 * * @return bool Whether the message shall be shown on the "All Tables" screen. */ protected function maybe_show_donation_message(): bool { // Only show the message to plugin admins. if ( ! current_user_can( 'tablepress_edit_options' ) ) { return false; } if ( ! TablePress::$model_options->get( 'message_donation_nag' ) ) { return false; } // Determine, how long has the plugin been installed. $seconds_installed = time() - TablePress::$model_options->get( 'first_activation' ); return ( $seconds_installed > MONTH_IN_SECONDS / 2 ); } /** * Init list of actions that have a view with their titles/names/caps. * * @since 1.0.0 */ protected function init_view_actions(): void { $this->view_actions = array( 'list' => array( 'show_entry' => true, 'page_title' => __( 'All Tables', 'tablepress' ), 'admin_menu_title' => __( 'All Tables', 'tablepress' ), 'nav_tab_title' => __( 'All Tables', 'tablepress' ), 'required_cap' => 'tablepress_list_tables', ), 'add' => array( 'show_entry' => true, 'page_title' => __( 'Add New Table', 'tablepress' ), 'admin_menu_title' => __( 'Add New Table', 'tablepress' ), 'nav_tab_title' => __( 'Add New', 'tablepress' ), 'required_cap' => 'tablepress_add_tables', ), 'edit' => array( 'show_entry' => false, 'page_title' => __( 'Edit Table', 'tablepress' ), 'admin_menu_title' => '', 'nav_tab_title' => '', 'required_cap' => 'tablepress_edit_tables', ), 'import' => array( 'show_entry' => true, 'page_title' => __( 'Import a Table', 'tablepress' ), 'admin_menu_title' => __( 'Import a Table', 'tablepress' ), 'nav_tab_title' => _x( 'Import', 'navigation bar', 'tablepress' ), 'required_cap' => 'tablepress_import_tables', ), 'export' => array( 'show_entry' => true, 'page_title' => __( 'Export a Table', 'tablepress' ), 'admin_menu_title' => __( 'Export a Table', 'tablepress' ), 'nav_tab_title' => _x( 'Export', 'navigation bar', 'tablepress' ), 'required_cap' => 'tablepress_export_tables', ), 'options' => array( 'show_entry' => true, 'page_title' => __( 'Plugin Options', 'tablepress' ), 'admin_menu_title' => __( 'Plugin Options', 'tablepress' ), 'nav_tab_title' => __( 'Plugin Options', 'tablepress' ), 'required_cap' => 'tablepress_access_options_screen', ), 'about' => array( 'show_entry' => true, 'page_title' => __( 'About', 'tablepress' ), 'admin_menu_title' => __( 'About TablePress', 'tablepress' ), 'nav_tab_title' => __( 'About', 'tablepress' ), 'required_cap' => 'tablepress_access_about_screen', ), ); /** * Filters the available TablePres Views/Actions and their parameters. * * @since 1.0.0 * * @param array> $view_actions The available Views/Actions and their parameters. */ $this->view_actions = apply_filters( 'tablepress_admin_view_actions', $this->view_actions ); } /* * HTTP POST actions. */ /** * Handle Bulk Actions (Copy, Export, Delete) on "All Tables" list screen. * * @since 1.0.0 */ public function handle_post_action_list(): void { TablePress::check_nonce( 'list' ); if ( isset( $_POST['bulk-action-selector-top'] ) && '-1' !== $_POST['bulk-action-selector-top'] ) { $bulk_action = $_POST['bulk-action-selector-top']; } elseif ( isset( $_POST['bulk-action-selector-bottom'] ) && '-1' !== $_POST['bulk-action-selector-bottom'] ) { $bulk_action = $_POST['bulk-action-selector-bottom']; } else { $bulk_action = false; } if ( ! in_array( $bulk_action, array( 'copy', 'export', 'delete' ), true ) ) { TablePress::redirect( array( 'action' => 'list', 'message' => 'error_bulk_action_invalid' ) ); } if ( empty( $_POST['table'] ) || ! is_array( $_POST['table'] ) ) { TablePress::redirect( array( 'action' => 'list', 'message' => 'error_no_selection' ) ); } $tables = wp_unslash( $_POST['table'] ); $no_success = array(); // To store table IDs that failed. switch ( $bulk_action ) { case 'copy': foreach ( $tables as $table_id ) { if ( current_user_can( 'tablepress_copy_table', $table_id ) ) { $copy_table_id = TablePress::$model_table->copy( $table_id ); if ( is_wp_error( $copy_table_id ) ) { $no_success[] = $table_id; } } else { $no_success[] = $table_id; } } break; case 'export': /* * Cap check is done on redirect target page. * To export, redirect to "Export" screen, with selected table IDs. */ $table_ids = implode( ',', $tables ); TablePress::redirect( array( 'action' => 'export', 'table_id' => $table_ids ) ); // break; // unreachable. case 'delete': foreach ( $tables as $table_id ) { if ( current_user_can( 'tablepress_delete_table', $table_id ) ) { $deleted = TablePress::$model_table->delete( $table_id ); if ( is_wp_error( $deleted ) ) { $no_success[] = $table_id; } } else { $no_success[] = $table_id; } } break; } if ( 0 !== count( $no_success ) ) { // @todo maybe pass this information to the view? $message = "error_{$bulk_action}_not_all_tables"; } else { $plural = ( count( $tables ) > 1 ) ? '_plural' : ''; $message = "success_{$bulk_action}{$plural}"; } /* * Slightly more complex redirect method, to account for sort, search, and pagination in the WP_List_Table on the List View, * but only if this action succeeds, to have everything fresh in the event of an error. */ $sendback = wp_get_referer(); if ( ! $sendback ) { $sendback = TablePress::url( array( 'action' => 'list', 'message' => $message ) ); } else { $sendback = remove_query_arg( array( 'action', 'message', 'table_id' ), $sendback ); $sendback = add_query_arg( array( 'action' => 'list', 'message' => $message ), $sendback ); } wp_redirect( $sendback ); exit; } /** * Add a table, according to the parameters on the "Add new Table" screen. * * @since 1.0.0 */ public function handle_post_action_add(): void { TablePress::check_nonce( 'add' ); if ( ! current_user_can( 'tablepress_add_tables' ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } if ( empty( $_POST['table'] ) || ! is_array( $_POST['table'] ) ) { TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => 'The HTTP POST data is empty.' ) ); } $add_table = wp_unslash( $_POST['table'] ); // Perform confidence checks of posted data. $name = $add_table['name'] ?? ''; $description = $add_table['description'] ?? ''; if ( ! isset( $add_table['rows'], $add_table['columns'] ) ) { TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => 'The HTTP POST data does not contain the table size.' ) ); } $num_rows = absint( $add_table['rows'] ); $num_columns = absint( $add_table['columns'] ); if ( 0 === $num_rows || 0 === $num_columns ) { TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => 'The table size is invalid.' ) ); } // Create a new table array with information from the posted data. $new_table = array( 'name' => $name, 'description' => $description, 'data' => array_fill( 0, $num_rows, array_fill( 0, $num_columns, '' ) ), 'visibility' => array( 'rows' => array_fill( 0, $num_rows, 1 ), 'columns' => array_fill( 0, $num_columns, 1 ), ), ); // Merge this data into an empty table template. $table = TablePress::$model_table->prepare_table( TablePress::$model_table->get_table_template(), $new_table, false ); if ( is_wp_error( $table ) ) { TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => TablePress::get_wp_error_string( $table ) ) ); } // Add the new table (and get its first ID). $table_id = TablePress::$model_table->add( $table ); if ( is_wp_error( $table_id ) ) { TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => TablePress::get_wp_error_string( $table_id ) ) ); } TablePress::redirect( array( 'action' => 'edit', 'table_id' => $table_id, 'message' => 'success_add' ) ); } /** * Save changed "Plugin Options". * * @since 1.0.0 */ public function handle_post_action_options(): void { TablePress::check_nonce( 'options' ); if ( ! current_user_can( 'tablepress_access_options_screen' ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } if ( empty( $_POST['options'] ) || ! is_array( $_POST['options'] ) ) { TablePress::redirect( array( 'action' => 'options', 'message' => 'error_save' ) ); } $posted_options = wp_unslash( $_POST['options'] ); // Valid new options that will be merged into existing ones. $new_options = array(); // Check each posted option value, and (maybe) add it to the new options. if ( ! empty( $posted_options['admin_menu_parent_page'] ) && '-' !== $posted_options['admin_menu_parent_page'] ) { $new_options['admin_menu_parent_page'] = $posted_options['admin_menu_parent_page']; // Re-init parent information, as `TablePress::redirect()` URL might be wrong otherwise. /** This filter is documented in classes/class-controller.php */ TablePress::$controller->parent_page = apply_filters( 'tablepress_admin_menu_parent_page', $posted_options['admin_menu_parent_page'] ); TablePress::$controller->is_top_level_page = in_array( TablePress::$controller->parent_page, array( 'top', 'middle', 'bottom' ), true ); } // Custom CSS can only be saved if the user is allowed to do so. $update_custom_css_files = false; if ( current_user_can( 'tablepress_edit_options' ) ) { // Checkbox. $new_options['use_custom_css'] = ( isset( $posted_options['use_custom_css'] ) && 'true' === $posted_options['use_custom_css'] ); if ( isset( $posted_options['custom_css'] ) ) { $new_options['custom_css'] = $posted_options['custom_css']; $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' ); if ( '' !== $new_options['custom_css'] ) { // Update "Custom CSS" to use DataTables 2 variants instead of old DataTables 1.x CSS classes. $new_options['custom_css'] = TablePress::convert_datatables_api_data( $new_options['custom_css'] ); // Sanitize and tidy up Custom CSS. $new_options['custom_css'] = $tablepress_css->sanitize_css( $new_options['custom_css'] ); // Minify Custom CSS. $new_options['custom_css_minified'] = $tablepress_css->minify_css( $new_options['custom_css'] ); } else { $new_options['custom_css_minified'] = ''; } // Maybe update CSS files as well. $custom_css_file_contents = $tablepress_css->load_custom_css_from_file( 'normal' ); if ( false === $custom_css_file_contents ) { $custom_css_file_contents = ''; } // Don't write to file if it already has the desired content. if ( $new_options['custom_css'] !== $custom_css_file_contents ) { $update_custom_css_files = true; // Set to false again. As it was set here, it will be set true again, if file saving succeeds. $new_options['use_custom_css_file'] = false; } } } // Save gathered new options (will be merged into existing ones), and flush caches of caching plugins, to make sure that the new Custom CSS is used. if ( ! empty( $new_options ) ) { TablePress::$model_options->update( $new_options ); TablePress::$model_table->_flush_caching_plugins_caches(); } if ( $update_custom_css_files ) { // Capability check is performed above. TablePress::redirect( array( 'action' => 'options', 'item' => 'save_custom_css' ), true ); } TablePress::redirect( array( 'action' => 'options', 'message' => 'success_save' ) ); } /** * Export selected tables. * * @since 1.0.0 */ public function handle_post_action_export(): void { TablePress::check_nonce( 'export' ); if ( ! current_user_can( 'tablepress_export_tables' ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } if ( empty( $_POST['export'] ) || ! is_array( $_POST['export'] ) ) { TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The HTTP POST data is empty.' ) ); } $export = wp_unslash( $_POST['export'] ); if ( empty( $export['tables_list'] ) ) { TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The HTTP POST data does not contain tables.' ) ); } /** @var TablePress_Export $exporter */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort $exporter = TablePress::load_class( 'TablePress_Export', 'class-export.php', 'classes' ); if ( empty( $export['format'] ) || ! isset( $exporter->export_formats[ $export['format'] ] ) ) { TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The export format is invalid.' ) ); } if ( empty( $export['csv_delimiter'] ) ) { // Set a value, so that the variable exists. $export['csv_delimiter'] = ''; } if ( 'csv' === $export['format'] && ! isset( $exporter->csv_delimiters[ $export['csv_delimiter'] ] ) ) { TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The CSV delimiter is invalid.' ) ); } $tables = explode( ',', $export['tables_list'] ); // Determine if ZIP file support is available. if ( $exporter->zip_support_available && ( ( isset( $export['zip_file'] ) && 'true' === $export['zip_file'] ) || count( $tables ) > 1 ) ) { // Export to ZIP only if ZIP is desired or if more than one table were selected (mandatory then). $export_to_zip = true; } else { $export_to_zip = false; } if ( ! $export_to_zip ) { // Exporting without a ZIP file is only possible for one table, so take the first one. if ( ! current_user_can( 'tablepress_export_table', $tables[0] ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } // Load table, with table data, options, and visibility settings. $table = TablePress::$model_table->load( $tables[0], true, true ); if ( is_wp_error( $table ) ) { TablePress::redirect( array( 'action' => 'export', 'message' => 'error_load_table', 'export_format' => $export['format'], 'csv_delimiter' => $export['csv_delimiter'], 'error_details' => TablePress::get_wp_error_string( $table ) ) ); } if ( isset( $table['is_corrupted'] ) && $table['is_corrupted'] ) { TablePress::redirect( array( 'action' => 'export', 'message' => 'error_table_corrupted', 'export_format' => $export['format'], 'csv_delimiter' => $export['csv_delimiter'] ) ); } $download_filename = sprintf( '%1$s-%2$s-%3$s.%4$s', $table['id'], $table['name'], wp_date( 'Y-m-d' ), $export['format'] ); /** * Filters the download filename of the exported table. * * @since 2.0.0 * * @param string $download_filename The download filename of exported table. * @param string $table_id Table ID of the exported table. * @param string $table_name Table name of the exported table. * @param string $export_format Format for the export ('csv', 'html', 'json', 'zip'). * @param bool $export_to_zip Whether the export is to a ZIP file (of multiple export files). */ $download_filename = apply_filters( 'tablepress_export_filename', $download_filename, $table['id'], $table['name'], $export['format'], $export_to_zip ); $download_filename = sanitize_file_name( $download_filename ); // Export the table. $export_data = $exporter->export_table( $table, $export['format'], $export['csv_delimiter'] ); /** * Filters the exported table data. * * @since 1.6.0 * * @param string $export_data The exported table data. * @param array $table Table to be exported. * @param string $export_format Format for the export ('csv', 'html', 'json'). * @param string $csv_delimiter Delimiter for CSV export. */ $export_data = apply_filters( 'tablepress_export_data', $export_data, $table, $export['format'], $export['csv_delimiter'] ); $download_data = $export_data; } else { // Zipping can use a lot of memory and execution time, but not this much hopefully. wp_raise_memory_limit( 'admin' ); if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( 300 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } $zip_file = new ZipArchive(); $download_filename = sprintf( 'tablepress-export-%1$s-%2$s.zip', wp_date( 'Y-m-d-H-i-s' ), $export['format'] ); /** This filter is documented in controllers/controller-admin.php */ $download_filename = apply_filters( 'tablepress_export_filename', $download_filename, '', '', $export['format'], $export_to_zip ); $download_filename = sanitize_file_name( $download_filename ); $full_filename = wp_tempnam( $download_filename ); if ( true !== $zip_file->open( $full_filename, ZipArchive::OVERWRITE ) ) { @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged TablePress::redirect( array( 'action' => 'export', 'message' => 'error_create_zip_file', 'export_format' => $export['format'], 'csv_delimiter' => $export['csv_delimiter'], 'error_details' => 'The ZIP file could not be opened for writing.' ) ); } foreach ( $tables as $table_id ) { // Don't export tables for which the user doesn't have the necessary export rights. if ( ! current_user_can( 'tablepress_export_table', $table_id ) ) { continue; } // Load table, with table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, true, true ); // Don't export if the table could not be loaded. if ( is_wp_error( $table ) ) { continue; } // Don't export if the table is corrupted. if ( isset( $table['is_corrupted'] ) && $table['is_corrupted'] ) { continue; } $export_data = $exporter->export_table( $table, $export['format'], $export['csv_delimiter'] ); /** This filter is documented in controllers/controller-admin.php */ $export_data = apply_filters( 'tablepress_export_data', $export_data, $table, $export['format'], $export['csv_delimiter'] ); $export_filename = sprintf( '%1$s-%2$s-%3$s.%4$s', $table['id'], $table['name'], wp_date( 'Y-m-d' ), $export['format'] ); /** This filter is documented in controllers/controller-admin.php */ $export_filename = apply_filters( 'tablepress_export_filename', $export_filename, $table['id'], $table['name'], $export['format'], $export_to_zip ); $export_filename = sanitize_file_name( $export_filename ); $zip_file->addFromString( $export_filename, $export_data ); } // If something went wrong, or no files were added to the ZIP file, bail out. // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase if ( ZipArchive::ER_OK !== $zip_file->status || 0 === $zip_file->numFiles ) { $zip_file->close(); @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged TablePress::redirect( array( 'action' => 'export', 'message' => 'error_create_zip_file', 'export_format' => $export['format'], 'csv_delimiter' => $export['csv_delimiter'], 'error_details' => 'The ZIP file could not be written or is empty.' ) ); } $zip_file->close(); // Load contents of the ZIP file, to send it as a download. $download_data = file_get_contents( $full_filename ); if ( false === $download_data ) { @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged TablePress::redirect( array( 'action' => 'export', 'message' => 'error_create_zip_file', 'export_format' => $export['format'], 'csv_delimiter' => $export['csv_delimiter'], 'error_details' => 'The ZIP file content could not be read.' ) ); } @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged } // Send download headers for export file. header( 'Content-Description: File Transfer' ); header( 'Content-Type: application/octet-stream' ); header( "Content-Disposition: attachment; filename=\"{$download_filename}\"" ); header( 'Content-Transfer-Encoding: binary' ); header( 'Expires: 0' ); header( 'Cache-Control: must-revalidate' ); header( 'Pragma: public' ); header( 'Content-Length: ' . strlen( $download_data ) ); // $filetype = text/csv, text/html, application/json // header( 'Content-Type: ' . $filetype. '; charset=' . get_option( 'blog_charset' ) ); @ob_end_clean(); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged flush(); echo $download_data; exit; } /** * Import data from existing source (Upload, URL, Server, Direct input). * * @since 1.0.0 */ public function handle_post_action_import(): void { TablePress::check_nonce( 'import' ); if ( ! current_user_can( 'tablepress_import_tables' ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } if ( empty( $_POST['import'] ) || ! is_array( $_POST['import'] ) ) { TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The HTTP POST data is empty.' ) ); } $import_config = wp_unslash( $_POST['import'] ); if ( empty( $import_config['source'] ) ) { TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The HTTP POST does not contain an import configuration.' ) ); } // For security reasons, the "server" source is only available for super admins on multisite and admins on single sites. if ( 'server' === $import_config['source'] ) { if ( ! is_super_admin() && ! ( ! is_multisite() && current_user_can( 'manage_options' ) ) ) { TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'You do not have the required access rights.' ) ); } } // For security reasons, the "url" source is only available admins and editors via a custom capability. if ( 'url' === $import_config['source'] ) { if ( ! current_user_can( 'tablepress_import_tables_url' ) ) { TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'You do not have the required access rights.' ) ); } } // Move file upload data to the main import configuration. $import_config['file-upload'] = $_FILES['import_file_upload'] ?? null; // Check if the source data for the chosen import source is defined. if ( empty( $import_config[ $import_config['source'] ] ) ) { TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The HTTP POST data does not contain an import source.' ) ); } // Set default values for non-essential configuration variables. if ( ! isset( $import_config['type'] ) ) { $import_config['type'] = 'add'; } if ( ! isset( $import_config['existing_table'] ) ) { $import_config['existing_table'] = ''; } $import_config['legacy_import'] = ( isset( $import_config['legacy_import'] ) && 'true' === $import_config['legacy_import'] ); $importer = TablePress::load_class( 'TablePress_Import', 'class-import.php', 'classes' ); $import = $importer->run( $import_config ); if ( is_wp_error( $import ) || 0 < count( $import['errors'] ) ) { $redirect_parameters = array( 'action' => 'import', 'message' => 'error_import', 'import_type' => $import_config['type'], 'import_existing_table' => $import_config['existing_table'], 'import_source' => $import_config['source'], 'legacy_import' => $import_config['legacy_import'], ); if ( in_array( $import_config['source'], array( 'url', 'server' ), true ) ) { $redirect_parameters[ "import_{$import_config['source']}" ] = $import_config[ $import_config['source'] ]; } if ( is_wp_error( $import ) ) { $redirect_parameters['error_details'] = TablePress::get_wp_error_string( $import ); } elseif ( 0 < count( $import['errors'] ) ) { $wp_error_strings = array(); foreach ( $import['errors'] as $file ) { $wp_error_strings[] = TablePress::get_wp_error_string( $file->error ); } $redirect_parameters['error_details'] = implode( ', ', $wp_error_strings ); } TablePress::redirect( $redirect_parameters ); } // At this point, there were no import errors. if ( count( $import['tables'] ) > 1 ) { TablePress::redirect( array( 'action' => 'list', 'message' => 'success_import' ) ); } elseif ( 1 === count( $import['tables'] ) ) { TablePress::redirect( array( 'action' => 'edit', 'table_id' => $import['tables'][0]['id'], 'message' => 'success_import' ) ); } else { TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The number of imported tables is invalid.' ) ); } } /* * HTTP GET actions. */ /** * Hide a header message on an admin screen. * * @since 1.0.0 */ public function handle_get_action_hide_message(): void { $message_item = ! empty( $_GET['item'] ) ? $_GET['item'] : ''; TablePress::check_nonce( 'hide_message', $message_item ); if ( ! current_user_can( 'tablepress_list_tables' ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } TablePress::$model_options->update( "message_{$message_item}", false ); $return = ! empty( $_GET['return'] ) ? $_GET['return'] : 'list'; TablePress::redirect( array( 'action' => $return ) ); } /** * Delete a table. * * @since 1.0.0 */ public function handle_get_action_delete_table(): void { $table_id = ( ! empty( $_GET['item'] ) ) ? $_GET['item'] : false; TablePress::check_nonce( 'delete_table', $table_id ); $return = ! empty( $_GET['return'] ) ? $_GET['return'] : 'list'; $return_item = ! empty( $_GET['return_item'] ) ? $_GET['return_item'] : false; // The nonce check should actually catch this already. if ( false === $table_id ) { TablePress::redirect( array( 'action' => $return, 'message' => 'error_delete', 'table_id' => $return_item ) ); } if ( ! current_user_can( 'tablepress_delete_table', $table_id ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } $deleted = TablePress::$model_table->delete( $table_id ); if ( is_wp_error( $deleted ) ) { TablePress::redirect( array( 'action' => $return, 'message' => 'error_delete', 'table_id' => $return_item, 'error_details' => TablePress::get_wp_error_string( $deleted ) ) ); } /* * Slightly more complex redirect method, to account for sort, search, and pagination in the WP_List_Table on the List View, * but only if this action succeeds, to have everything fresh in the event of an error. */ $sendback = wp_get_referer(); if ( ! $sendback ) { $sendback = TablePress::url( array( 'action' => 'list', 'message' => 'success_delete', 'table_id' => $return_item ) ); } else { $sendback = remove_query_arg( array( 'action', 'message', 'table_id' ), $sendback ); $sendback = add_query_arg( array( 'action' => 'list', 'message' => 'success_delete', 'table_id' => $return_item ), $sendback ); } wp_redirect( $sendback ); exit; } /** * Copy a table. * * @since 1.0.0 */ public function handle_get_action_copy_table(): void { $table_id = ( ! empty( $_GET['item'] ) ) ? $_GET['item'] : false; TablePress::check_nonce( 'copy_table', $table_id ); $return = ! empty( $_GET['return'] ) ? $_GET['return'] : 'list'; $return_item = ! empty( $_GET['return_item'] ) ? $_GET['return_item'] : false; // The nonce check should actually catch this already. if ( false === $table_id ) { TablePress::redirect( array( 'action' => $return, 'message' => 'error_copy', 'table_id' => $return_item ) ); } if ( ! current_user_can( 'tablepress_copy_table', $table_id ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } $copy_table_id = TablePress::$model_table->copy( $table_id ); if ( is_wp_error( $copy_table_id ) ) { TablePress::redirect( array( 'action' => $return, 'message' => 'error_copy', 'table_id' => $return_item, 'error_details' => TablePress::get_wp_error_string( $copy_table_id ) ) ); } $return_item = $copy_table_id; /* * Slightly more complex redirect method, to account for sort, search, and pagination in the WP_List_Table on the List View, * but only if this action succeeds, to have everything fresh in the event of an error. */ $sendback = wp_get_referer(); if ( ! $sendback ) { $sendback = TablePress::url( array( 'action' => $return, 'message' => 'success_copy', 'table_id' => $return_item ) ); } else { $sendback = remove_query_arg( array( 'action', 'message', 'table_id' ), $sendback ); $sendback = add_query_arg( array( 'action' => $return, 'message' => 'success_copy', 'table_id' => $return_item ), $sendback ); } wp_redirect( $sendback ); exit; } /** * Preview a table. * * @since 1.0.0 */ public function handle_get_action_preview_table(): void { $table_id = ( ! empty( $_GET['item'] ) ) ? $_GET['item'] : false; TablePress::check_nonce( 'preview_table', $table_id ); // Nonce check should actually catch this already. if ( false === $table_id ) { wp_die( __( 'The preview could not be loaded.', 'tablepress' ), __( 'Preview', 'tablepress' ) ); } if ( ! current_user_can( 'tablepress_preview_table', $table_id ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } // Load table, with table data, options, and visibility settings. $table = TablePress::$model_table->load( $table_id, true, true ); if ( is_wp_error( $table ) ) { wp_die( __( 'The table could not be loaded.', 'tablepress' ), __( 'Preview', 'tablepress' ) ); } // Sanitize all table data to remove unsafe HTML from the preview output, if the user is not allowed to work with unfiltered HTML. if ( ! current_user_can( 'unfiltered_html' ) ) { $table = TablePress::$model_table->sanitize( $table ); } // Create a render class instance. $_render = TablePress::load_class( 'TablePress_Render', 'class-render.php', 'classes' ); // Merge desired options with default render options (see TablePress_Controller_Frontend::shortcode_table()). $default_render_options = $_render->get_default_render_options(); /** This filter is documented in controllers/controller-frontend.php */ $default_render_options = apply_filters( 'tablepress_shortcode_table_default_shortcode_atts', $default_render_options ); $render_options = shortcode_atts( $default_render_options, $table['options'] ); /** This filter is documented in controllers/controller-frontend.php */ $render_options = apply_filters( 'tablepress_shortcode_table_shortcode_atts', $render_options ); $render_options['html_id'] = "tablepress-{$table['id']}"; $render_options['block_preview'] = true; $_render->set_input( $table, $render_options ); $view_data = array( 'table_id' => $table_id, 'head_html' => $_render->get_preview_css(), 'body_html' => $_render->get_output( 'html' ), 'site_used_editor' => TablePress::site_used_editor(), ); $custom_css = TablePress::$model_options->get( 'custom_css' ); $use_custom_css = ( TablePress::$model_options->get( 'use_custom_css' ) && '' !== $custom_css ); if ( $use_custom_css ) { $view_data['head_html'] .= "\n"; } // Prepare, initialize, and render the view. $this->view = TablePress::load_view( 'preview_table', $view_data ); $this->view->render(); } /** * Shows a list of tables in the Editor toolbar Thickbox (opened by TinyMCE or Quicktags button). * * @since 1.0.0 */ public function handle_get_action_editor_button_thickbox(): void { TablePress::check_nonce( 'editor_button_thickbox' ); if ( ! current_user_can( 'tablepress_list_tables' ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } $view_data = array( // Load all table IDs without priming the post meta cache, as table options/visibility are not needed. 'table_ids' => TablePress::$model_table->load_all( false ), ); set_current_screen( 'tablepress_editor_button_thickbox' ); // Prepare, initialize, and render the view. $this->view = TablePress::load_view( 'editor_button_thickbox', $view_data ); $this->view->render(); } /** * Uninstall TablePress, and delete all tables and options. * * @since 1.0.0 */ public function handle_get_action_uninstall_tablepress(): void { TablePress::check_nonce( 'uninstall_tablepress' ); $plugin = TABLEPRESS_BASENAME; if ( ! current_user_can( 'deactivate_plugin', $plugin ) || ! current_user_can( 'tablepress_edit_options' ) || ! current_user_can( 'tablepress_delete_tables' ) || is_plugin_active_for_network( $plugin ) ) { wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 ); } // Deactivate TablePress for the site (but not for the network). deactivate_plugins( $plugin, false, false ); update_option( 'recently_activated', array( $plugin => time() ) + (array) get_option( 'recently_activated', array() ) ); // Delete all tables, "Custom CSS" files, and options. TablePress::$model_table->delete_all(); $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' ); $css_files_deleted = $tablepress_css->delete_custom_css_files(); TablePress::$model_options->remove_access_capabilities(); TablePress::$model_table->destroy(); TablePress::$model_options->destroy(); $output = '' . __( 'TablePress was uninstalled successfully.', 'tablepress' ) . '

'; $output .= __( 'All tables, data, and options were deleted.', 'tablepress' ); if ( is_multisite() ) { $output .= ' ' . __( 'You may now ask the network admin to delete the plugin’s folder tablepress from the server, if no other site in the network uses it.', 'tablepress' ); } else { $output .= ' ' . __( 'You may now manually delete the plugin’s folder tablepress from the plugins directory on your server or use the “Delete” link for TablePress on the WordPress “Plugins” page.', 'tablepress' ); } if ( $css_files_deleted ) { $output .= ' ' . __( 'Your TablePress “Custom CSS” files have been deleted automatically.', 'tablepress' ); } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found if ( is_multisite() ) { $output .= ' ' . __( 'Please also ask him to delete your TablePress “Custom CSS” files from the server.', 'tablepress' ); } else { $output .= ' ' . __( 'You may now also delete your TablePress “Custom CSS” files in the wp-content folder.', 'tablepress' ); } } $output .= "

\n

"; if ( ! is_multisite() || is_super_admin() ) { $output .= '' . __( 'Go to “Plugins” page', 'tablepress' ) . ' '; } $output .= '' . __( 'Go to Dashboard', 'tablepress' ) . ''; wp_die( $output, __( 'Uninstall TablePress', 'tablepress' ), array( 'response' => 200, 'back_link' => false ) ); } } // class TablePress_Admin_Controller PK!+Cf4c c freemius-filters.phpnu[add_filter( 'plugin_icon', static function ( $icon ) /* No return type declaration or type hints, due to required PHP compatibility of this file! */ { $icon = dirname( __DIR__ ) . '/admin/img/tablepress-icon.svg'; return $icon; } // No trailing comma in function call, due to required PHP compatibility of this file! ); // Load the TablePress style customizations for the Freemius Pricing screen. tb_tp_fs()->add_filter( 'pricing/css_path', static function ( $path ) /* No return type declaration or type hints, due to required PHP compatibility of this file! */ { $path = dirname( __DIR__ ) . '/admin/css/build/freemius-pricing.css'; return $path; } // No trailing comma in function call, due to required PHP compatibility of this file! ); // Hide the "Pricing" menu entry for users with a valid and active premium license. tb_tp_fs()->add_filter( 'is_submenu_visible', static function ( $is_visible, $menu_id ) /* No return type declaration or type hints, due to required PHP compatibility of this file! */ { if ( 'pricing' === $menu_id ) { $is_visible = ! TABLEPRESS_IS_PLAYGROUND_PREVIEW && ! tb_tp_fs()->is_paying_or_trial() && current_user_can( 'tablepress_list_tables' ); } return $is_visible; }, 10, 2 // No trailing comma in function call, due to required PHP compatibility of this file! ); // Show only annual but not calculated monthly prices on the "Pricing" page. tb_tp_fs()->add_filter( 'pricing/show_annual_in_monthly', '__return_false' ); // Determine the default currency based on the top-level domain (TLD) of the site URL. tb_tp_fs()->add_filter( 'default_currency', static function ( $currency ) /* No return type declaration or type hints, due to required PHP compatibility of this file! */ { $host = wp_parse_url( site_url(), PHP_URL_HOST ); if ( is_string( $host ) ) { $tld = strtolower( pathinfo( $host, PATHINFO_EXTENSION ) ); if ( in_array( $tld, array( 'at', 'be', 'bg', 'cy', 'cz', 'de', 'dk', 'ee', 'es', 'fi', 'fr', 'gr', 'hu', 'ie', 'it', 'lt', 'lu', 'lv', 'mt', 'nl', 'pl', 'pt', 'ro', 'se', 'si', 'sk', 'uk' ), true ) ) { $currency = 'eur'; } } return $currency; } // No trailing comma in function call, due to required PHP compatibility of this file! ); // Hide the tabs navigation on Freemius screens. tb_tp_fs()->add_filter( 'hide_account_tabs', '__return_true' ); // Use different arrow icons in the admin menu. tb_tp_fs()->override_i18n( array( 'symbol_arrow-left' => '←', 'symbol_arrow-right' => '→', ) ); PK!j)P<<controller-admin_ajax.phpnu[update( "message_{$message_item}", false ); wp_die( '1' ); } /** * Saves the table after the "Save Changes" button on the "Edit" screen has been clicked. * * @since 1.0.0 */ public function ajax_action_save_table(): void { if ( empty( $_POST['tablepress']['id'] ) ) { wp_die( '-1' ); } $edit_table = wp_unslash( $_POST['tablepress'] ); // Check if the submitted nonce matches the generated nonce we created earlier, dies -1 on failure. TablePress::check_nonce( 'edit', $edit_table['id'], '_ajax_nonce', true ); // Ignore the request if the current user doesn't have sufficient permissions. if ( ! current_user_can( 'tablepress_edit_table', $edit_table['id'] ) ) { wp_die( '-1' ); } // Default response data. $success = false; $message = 'error_save'; $error_details = ''; do { // To be able to "break;" (allows for better readable code). // Load table, without table data, but with options and visibility settings. $existing_table = TablePress::$model_table->load( $edit_table['id'], false, true ); if ( is_wp_error( $existing_table ) ) { $error = new WP_Error( 'ajax_save_table_load', '', $edit_table['id'] ); $error->merge_from( $existing_table ); $error_details = TablePress::get_wp_error_string( $error ); break; } // Check and convert all data that was transmitted as valid JSON. $keys = array( 'data', 'options', 'visibility' ); foreach ( $keys as $key ) { if ( empty( $edit_table[ $key ] ) ) { $error = new WP_Error( "ajax_save_table_{$key}_empty", '', $edit_table['id'] ); $error_details = TablePress::get_wp_error_string( $error ); break 2; } $edit_table[ $key ] = json_decode( $edit_table[ $key ], true ); if ( is_null( $edit_table[ $key ] ) ) { $error = new WP_Error( "ajax_save_table_{$key}_invalid_json", '', $edit_table['id'] ); $error_details = TablePress::get_wp_error_string( $error ); break 2; } $edit_table[ $key ] = (array) $edit_table[ $key ]; // Cast to array again, to catch strings, etc. } // Check consistency of new table, and then merge with existing table. $table = TablePress::$model_table->prepare_table( $existing_table, $edit_table, true ); if ( is_wp_error( $table ) ) { $error = new WP_Error( 'ajax_save_table_prepare', '', $edit_table['id'] ); $error->merge_from( $table ); $error_details = TablePress::get_wp_error_string( $error ); break; } // DataTables Custom Commands can only be edited by trusted users. if ( ! current_user_can( 'unfiltered_html' ) ) { $table['options']['datatables_custom_commands'] = $existing_table['options']['datatables_custom_commands']; } // Save updated table. $saved = TablePress::$model_table->save( $table ); if ( is_wp_error( $saved ) ) { $error = new WP_Error( 'ajax_save_table_save', '', $table['id'] ); $error->merge_from( $saved ); $error_details = TablePress::get_wp_error_string( $error ); break; } // At this point, the table was saved successfully, possible ID change remains. $success = true; $message = 'success_save'; // Check if ID change is desired. if ( $table['id'] === $table['new_id'] ) { // If not, we are done. break; } // Change table ID. if ( current_user_can( 'tablepress_edit_table_id', $table['id'] ) ) { $id_changed = TablePress::$model_table->change_table_id( $table['id'], $table['new_id'] ); if ( ! is_wp_error( $id_changed ) ) { $message = 'success_save_success_id_change'; $table['id'] = $table['new_id']; } else { $message = 'success_save_error_id_change'; $error = new WP_Error( 'ajax_save_table_id_change', '', $table['new_id'] ); $error->merge_from( $id_changed ); $error_details = TablePress::get_wp_error_string( $error ); } } else { $message = 'success_save_error_id_change'; $error_details = 'table_id_could_not_be_changed: capability_check_failed'; } // @phpstan-ignore doWhile.alwaysFalse } while ( false ); // Do-while-loop through this exactly once, to be able to "break;" early. // Generate the response. // Common data for all responses. $response = array( 'success' => $success, 'message' => $message, ); if ( $success ) { // For the phpstan ignores in the next lines: If this is reached, $table is guaranteed to exist and is a valid array. $response['table_id'] = $table['id']; // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $response['new_edit_nonce'] = wp_create_nonce( TablePress::nonce( 'edit', $table['id'] ) ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $response['new_preview_nonce'] = wp_create_nonce( TablePress::nonce( 'preview_table', $table['id'] ) ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $response['new_copy_nonce'] = wp_create_nonce( TablePress::nonce( 'copy_table', $table['id'] ) ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $response['new_delete_nonce'] = wp_create_nonce( TablePress::nonce( 'delete_table', $table['id'] ) ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $response['last_modified'] = TablePress::format_datetime( $table['last_modified'] ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $response['last_editor'] = TablePress::get_user_display_name( $table['options']['last_editor'] ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined } if ( ! empty( $error_details ) ) { $response['error_details'] = esc_html( $error_details ); } // Buffer all outputs, to prevent errors/warnings being printed that make the JSON invalid. $output_buffer = ob_get_clean(); if ( ! empty( $output_buffer ) ) { $response['output_buffer'] = $output_buffer; } // Send the response. wp_send_json( $response ); } /** * Returns the live preview data of table that has non-saved changes. * * @since 1.0.0 */ public function ajax_action_preview_table(): void { if ( empty( $_POST['tablepress']['id'] ) ) { wp_die( '-1' ); } $preview_table = wp_unslash( $_POST['tablepress'] ); // Check if the submitted nonce matches the generated nonce we created earlier, dies -1 on failure. TablePress::check_nonce( 'preview_table', $preview_table['id'], '_ajax_nonce', true ); // Ignore the request if the current user doesn't have sufficient permissions. if ( ! current_user_can( 'tablepress_preview_table', $preview_table['id'] ) ) { wp_die( '-1' ); } // Default response data. $success = false; do { // To be able to "break;" (allows for better readable code). // Load table, without table data, but with options and visibility settings. $existing_table = TablePress::$model_table->load( $preview_table['id'], false, true ); if ( is_wp_error( $existing_table ) ) { break; } // Check and convert all data that was transmitted as valid JSON. $keys = array( 'data', 'options', 'visibility' ); foreach ( $keys as $key ) { if ( empty( $preview_table[ $key ] ) ) { break 2; } $preview_table[ $key ] = json_decode( $preview_table[ $key ], true ); if ( is_null( $preview_table[ $key ] ) ) { break 2; } $preview_table[ $key ] = (array) $preview_table[ $key ]; // Cast to array again, to catch strings, etc. } // Check consistency of new table, and then merge with existing table. $table = TablePress::$model_table->prepare_table( $existing_table, $preview_table, true ); if ( is_wp_error( $table ) ) { break; } // DataTables Custom Commands can only be edited by trusted users. if ( ! current_user_can( 'unfiltered_html' ) ) { $table['options']['datatables_custom_commands'] = $existing_table['options']['datatables_custom_commands']; } // If the ID has changed, and the new ID is valid, render with the new ID (important e.g. for CSS classes/HTML ID). if ( $table['id'] !== $table['new_id'] && 0 === preg_match( '/[^a-zA-Z0-9_-]/', $table['new_id'] ) ) { $table['id'] = $table['new_id']; } // Sanitize all table data to remove unsafe HTML from the preview output, if the user is not allowed to work with unfiltered HTML. if ( ! current_user_can( 'unfiltered_html' ) ) { $table = TablePress::$model_table->sanitize( $table ); } // At this point, the table data is valid and sanitized and can be rendered. $success = true; // @phpstan-ignore doWhile.alwaysFalse } while ( false ); // Do-while-loop through this exactly once, to be able to "break;" early. if ( $success ) { // Create a render class instance. $_render = TablePress::load_class( 'TablePress_Render', 'class-render.php', 'classes' ); // Merge desired options with default render options (see TablePress_Controller_Frontend::shortcode_table()). $default_render_options = $_render->get_default_render_options(); /** This filter is documented in controllers/controller-frontend.php */ $default_render_options = apply_filters( 'tablepress_shortcode_table_default_shortcode_atts', $default_render_options ); // For the phpstan ignores in the next lines: If this is reached, $table is guaranteed to exist and is a valid array. $render_options = shortcode_atts( $default_render_options, $table['options'] ); // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined /** This filter is documented in controllers/controller-frontend.php */ $render_options = apply_filters( 'tablepress_shortcode_table_shortcode_atts', $render_options ); $render_options['html_id'] = "tablepress-{$table['id']}"; // @phpstan-ignore offsetAccess.nonOffsetAccessible, variable.undefined $render_options['block_preview'] = true; $_render->set_input( $table, $render_options ); // @phpstan-ignore variable.undefined $head_html = $_render->get_preview_css(); $custom_css = TablePress::$model_options->get( 'custom_css' ); $use_custom_css = ( TablePress::$model_options->get( 'use_custom_css' ) && '' !== $custom_css ); if ( $use_custom_css ) { $head_html .= "\n"; } $body_html = '

' . __( 'This is a preview of your table.', 'tablepress' ) . ' ' . __( 'Because of CSS styling in your theme, the table might look different on your page!', 'tablepress' ) . ' ' . __( 'The Table Features for Site Visitors, like sorting, filtering, and pagination, are also not available in this preview!', 'tablepress' ) . '
'; // Show the instructions string depending on whether the Block Editor is used on the site or not. if ( 'block' === TablePress::site_used_editor() ) { $body_html .= sprintf( __( 'To insert a table into a post or page, add a “%1$s” block in the block editor and select the desired table.', 'tablepress' ), __( 'TablePress table', 'tablepress' ) ); } elseif ( 'elementor' === TablePress::site_used_editor() ) { $body_html .= sprintf( __( 'To insert a table into a post or page, add a “%1$s” widget in the Elementor editor and select the desired table.', 'tablepress' ), __( 'TablePress table', 'tablepress' ) ); } else { $body_html .= __( 'To insert a table into a post or page, paste its Shortcode at the desired place in the editor.', 'tablepress' ) . ' ' . __( 'Each table has a unique ID that needs to be adjusted in that Shortcode.', 'tablepress' ); } $body_html .= '

' . $_render->get_output( 'html' ) . '
'; } else { $head_html = ''; $body_html = __( 'The preview could not be loaded.', 'tablepress' ); } // Generate the response. $response = array( 'success' => $success, 'head_html' => $head_html, 'body_html' => $body_html, ); // Buffer all outputs, to prevent errors/warnings being printed that make the JSON invalid. $output_buffer = ob_get_clean(); if ( ! empty( $output_buffer ) ) { $response['output_buffer'] = $output_buffer; } // Send the response. wp_send_json( $response ); } /** * Saves the screen options on the "Edit" screen when they are changed. * * @since 2.1.0 */ public function ajax_action_save_screen_options(): void { // Check if the submitted nonce matches the generated nonce we created earlier, dies -1 on failure. TablePress::check_nonce( 'screen_options', false, '_ajax_nonce', true ); if ( empty( $_POST['tablepress'] ) ) { wp_die( '-1' ); } $screen_options = wp_unslash( $_POST['tablepress'] ); // Sanitize and limit values to a minimum and a maximum. $new_screen_options = array(); if ( isset( $screen_options['table_editor_column_width'] ) ) { $new_screen_options['table_editor_column_width'] = absint( $screen_options['table_editor_column_width'] ); $new_screen_options['table_editor_column_width'] = max( $new_screen_options['table_editor_column_width'], 30 ); // Minimum width: 30 pixels. $new_screen_options['table_editor_column_width'] = min( $new_screen_options['table_editor_column_width'], 9999 ); // Maximum width: 9999 pixels. } if ( isset( $screen_options['table_editor_line_clamp'] ) ) { $new_screen_options['table_editor_line_clamp'] = absint( $screen_options['table_editor_line_clamp'] ); $new_screen_options['table_editor_line_clamp'] = min( $new_screen_options['table_editor_line_clamp'], 999 ); // Maximum lines: 999. Minimum of 0 (for all lines) is ensured by absint(). } if ( empty( $new_screen_options ) ) { wp_die( '-1' ); } TablePress::$model_options->update( $new_screen_options ); // Generate the response. $response = array( 'success' => true, ); // Buffer all outputs, to prevent errors/warnings being printed that make the JSON invalid. $output_buffer = ob_get_clean(); if ( ! empty( $output_buffer ) ) { $response['output_buffer'] = $output_buffer; } // Send the response. wp_send_json( $response ); } } // class TablePress_Admin_AJAX_Controller PK! H H template-tag-functions.phpnu[ $table_query Query-string-like list or array of parameters for Shortcode "table" rendering. * @return string HTML of the rendered table. */ function tablepress_get_table( /* string|array */ $table_query ): string { if ( is_array( $table_query ) ) { $atts = $table_query; } else { parse_str( (string) $table_query, $atts ); } return TablePress::$controller->shortcode_table( $atts ); // @phpstan-ignore argument.type } /** * Provides template tag functionality for the "table" Shortcode, to be used anywhere in the template, echoes the table HTML. * * @since 1.0.0 * * @see tablepress_get_table() * * @param string|array $table_query Query-string-like list or array of parameters for Shortcode "table" rendering. */ function tablepress_print_table( /* string|array */ $table_query ): void { echo tablepress_get_table( $table_query ); } /** * Provides template tag functionality for the "table-info" Shortcode, to be used anywhere in the template, returns the info. * * @since 1.0.0 * * @param string|array $table_query Query-string-like list or array of parameters for Shortcode "table-info" rendering. * @return string Desired table information. */ function tablepress_get_table_info( /* string|array */ $table_query ): string { if ( is_array( $table_query ) ) { $atts = $table_query; } else { parse_str( (string) $table_query, $atts ); } return TablePress::$controller->shortcode_table_info( $atts ); // @phpstan-ignore argument.type } /** * Provides template tag functionality for the "table-info" Shortcode, to be used anywhere in the template, echoes the info. * * @since 1.0.0 * * @see tablepress_get_table_info() * * @param string|array $table_query Query-string-like list or array of parameters for Shortcode "table-info" rendering. */ function tablepress_print_table_info( /* string|array */ $table_query ): void { echo tablepress_get_table_info( $table_query ); } PK!\$$controller-frontend.phpnu[PK! kindex.phpnu[PK!tбenvironment-checks.phpnu[PK!:controller-admin.phpnu[PK!+Cf4c c freemius-filters.phpnu[PK!j)P<<fcontroller-admin_ajax.phpnu[PK! H H template-tag-functions.phpnu[PKQP)
is_free_plan() ) { echo '

'; _e( 'This TablePress Extension was retired.', 'tablepress' ); echo ' '; _e( 'The plugin does no longer work with TablePress 3 and will no longer receive updates or support!', 'tablepress' ); echo '
'; _e( 'Keeping it activated can lead to errors on your website!', 'tablepress' ); echo ' ' . sprintf( __( 'Find out what you can do to continue using its features!', 'tablepress' ), 'https://tablepress.org/upgrade-extensions/?utm_source=plugin&utm_medium=textlink&utm_content=plugins-list-table' ) . ''; echo '

'; } ?>