PluginProbe
TablePress – Tables in WordPress made easy / 2.3
TablePress – Tables in WordPress made easy v2.3
3.3.4 3.3.3 3.3.2 3.3.1 trunk 1.12 1.14 1.9.2 2.0.4 2.1.7 2.1.8 2.2 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.3 2.3.1 2.3.2 2.4 2.4.1 2.4.2 2.4.3 2.4.4 All 44 releases
tablepress / controllers / controller-admin.php

controller-admin.php in TablePress – Tables in WordPress made easy 2.3, at controllers/controller-admin.php

1,391 lines 58.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Admin Controller for TablePress with the functionality for the non-AJAX backend
4 *
5 * @package TablePress
6 * @subpackage Controllers
7 * @author Tobias Bäthge
8 * @since 1.0.0
9 */
10
11 // Prohibit direct script loading.
12 defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );
13
14 /**
15 * Admin Controller class, extends Base Controller Class
16 *
17 * @package TablePress
18 * @subpackage Controllers
19 * @author Tobias Bäthge
20 * @since 1.0.0
21 */
22 class TablePress_Admin_Controller extends TablePress_Controller {
23
24 /**
25 * Page hooks (i.e. names) WordPress uses for the TablePress admin screens,
26 * populated in add_admin_menu_entry().
27 *
28 * @since 1.0.0
29 * @var string[]
30 */
31 protected $page_hooks = array();
32
33 /**
34 * Actions that have a view and admin menu or nav tab menu entry.
35 *
36 * @since 1.0.0
37 * @var array<string, array<string, bool|string>>
38 */
39 protected $view_actions = array();
40
41 /**
42 * Instance of the TablePress Admin View that is rendered.
43 *
44 * @since 1.0.0
45 * @var TablePress_View
46 */
47 protected $view;
48
49 /**
50 * Initialize the Admin Controller, determine location the admin menu, set up actions.
51 *
52 * @since 1.0.0
53 */
54 public function __construct() {
55 parent::__construct();
56
57 // Handler for changing the number of shown tables in the list of tables (via WP List Table class).
58 add_filter( 'set_screen_option_tablepress_list_per_page', array( $this, 'save_list_tables_screen_option' ), 10, 3 );
59
60 add_action( 'admin_menu', array( $this, 'add_admin_menu_entry' ) );
61 add_action( 'admin_init', array( $this, 'add_admin_actions' ) );
62
63 add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
64 add_action( 'enqueue_block_assets', array( $this, 'enqueue_block_assets' ) );
65 }
66
67 /**
68 * Handler for changing the number of shown tables in the list of tables (via WP List Table class).
69 *
70 * @since 1.0.0
71 *
72 * @param mixed $screen_option Current value of the filter (probably bool false).
73 * @param string $option Option in which the setting is stored.
74 * @param int $value Current value of the setting.
75 * @return int Changed value of the setting
76 */
77 public function save_list_tables_screen_option( /* mixed */ $screen_option, string $option, int $value ): int {
78 return $value;
79 }
80
81 /**
82 * Add admin screens to the correct place in the admin menu.
83 *
84 * @since 1.0.0
85 */
86 public function add_admin_menu_entry(): void {
87 // Callback for all menu entries.
88 $callback = array( $this, 'show_admin_page' );
89 /**
90 * Filters the TablePress admin menu entry name.
91 *
92 * @since 1.0.0
93 *
94 * @param string $entry_name The admin menu entry name. Default "TablePress".
95 */
96 $admin_menu_entry_name = apply_filters( 'tablepress_admin_menu_entry_name', 'TablePress' );
97
98 $this->init_view_actions();
99 $min_access_cap = $this->view_actions['list']['required_cap'];
100
101 if ( $this->is_top_level_page ) {
102 $icon_url = 'dashicons-list-view';
103 switch ( $this->parent_page ) {
104 case 'top':
105 $position = 3; // Position of Dashboard + 1.
106 break;
107 case 'bottom':
108 $position = ( ++$GLOBALS['_wp_last_utility_menu'] );
109 break;
110 case 'middle':
111 default:
112 $position = ( ++$GLOBALS['_wp_last_object_menu'] );
113 break;
114 }
115 add_menu_page( 'TablePress', $admin_menu_entry_name, $min_access_cap, 'tablepress', $callback, $icon_url, $position ); // @phpstan-ignore-line
116 foreach ( $this->view_actions as $action => $entry ) {
117 if ( ! $entry['show_entry'] ) {
118 continue;
119 }
120 $slug = 'tablepress';
121 if ( 'list' !== $action ) {
122 $slug .= '_' . $action;
123 }
124 // @phpstan-ignore-next-line
125 $page_hook = add_submenu_page( 'tablepress', sprintf( __( '%1$s &lsaquo; %2$s', 'tablepress' ), $entry['page_title'], 'TablePress' ), $entry['admin_menu_title'], $entry['required_cap'], $slug, $callback );
126 if ( false !== $page_hook ) {
127 $this->page_hooks[] = $page_hook;
128 }
129 }
130 } else {
131 // @phpstan-ignore-next-line
132 $page_hook = add_submenu_page( $this->parent_page, 'TablePress', $admin_menu_entry_name, $min_access_cap, 'tablepress', $callback );
133 if ( false !== $page_hook ) {
134 $this->page_hooks[] = $page_hook;
135 }
136 }
137 }
138
139 /**
140 * Set up handlers for user actions in the backend that exceed plain viewing.
141 *
142 * @since 1.0.0
143 */
144 public function add_admin_actions(): void {
145 // Register the callbacks for processing action requests.
146 $post_actions = array( 'list', 'add', 'options', 'export', 'import' );
147 $get_actions = array( 'hide_message', 'delete_table', 'copy_table', 'preview_table', 'editor_button_thickbox', 'uninstall_tablepress' );
148 foreach ( $post_actions as $action ) {
149 add_action( "admin_post_tablepress_{$action}", array( $this, "handle_post_action_{$action}" ) );
150 }
151 foreach ( $get_actions as $action ) {
152 add_action( "admin_post_tablepress_{$action}", array( $this, "handle_get_action_{$action}" ) );
153 }
154
155 // Register callbacks to trigger load behavior for admin pages.
156 foreach ( $this->page_hooks as $page_hook ) {
157 add_action( "load-{$page_hook}", array( $this, 'load_admin_page' ) );
158 }
159
160 /**
161 * Filters whether the legacy editor button should be loaded on the post editing screen.
162 *
163 * @since 2.1.0
164 *
165 * @param bool $load_button Whether to load the legacy editor button. Default true.
166 */
167 if ( apply_filters( 'tablepress_add_legacy_editor_button', true ) ) {
168 $pages_with_editor_button = array( 'post.php', 'post-new.php' );
169 foreach ( $pages_with_editor_button as $editor_page ) {
170 add_action( "load-{$editor_page}", array( $this, 'add_editor_buttons' ) );
171 }
172 }
173
174 if ( ! is_network_admin() && ! is_user_admin() ) {
175 add_action( 'admin_bar_menu', array( $this, 'add_wp_admin_bar_new_content_menu_entry' ), 71 );
176 }
177
178 add_action( 'load-plugins.php', array( $this, 'plugins_page' ) );
179
180 // Add filters and actions for the integration into the WP WXR exporter and importer.
181 add_action( 'wp_import_insert_post', array( TablePress::$model_table, 'add_table_id_on_wp_import' ), 10, 4 );
182 add_filter( 'wp_import_post_meta', array( TablePress::$model_table, 'prevent_table_id_post_meta_import_on_wp_import' ), 10, 3 );
183 add_filter( 'wxr_export_skip_postmeta', array( TablePress::$model_table, 'add_table_id_to_wp_export' ), 10, 3 );
184 }
185
186 /**
187 * Loads additional JavaScript code for the TablePress table block (in the block editor context).
188 *
189 * @since 2.2.0
190 */
191 public function enqueue_block_editor_assets(): void {
192 // Add table information for the block editor to the page.
193 $handle = generate_block_asset_handle( 'tablepress/table', 'editorScript' );
194 $data = $this->get_block_editor_data();
195 wp_add_inline_script( $handle, $data, 'before' );
196 }
197
198 /**
199 * Loads additional CSS code for the TablePress table block (inside the block editor iframe).
200 *
201 * @since 2.2.0
202 */
203 public function enqueue_block_assets(): void {
204 // Load the TablePress default CSS and the user's "Custom CSS" in the block editor iframe.
205 if ( is_admin() ) {
206 TablePress::$controller->enqueue_css();
207 }
208 }
209
210 /**
211 * Gets the inline data that is referenced by the Block Editor JavaScript code for the TablePress blocks.
212 *
213 * @since 2.0.0
214 *
215 * @return string JavaScript code for the Block Editor.
216 */
217 protected function get_block_editor_data(): string {
218 $tables = array();
219 // Load all table IDs without priming the post meta cache, as table options/visibility are not needed.
220 $table_ids = TablePress::$model_table->load_all( false );
221 foreach ( $table_ids as $table_id ) {
222 // Load table, without table data, options, and visibility settings.
223 $table = TablePress::$model_table->load( $table_id, false, false );
224 if ( '' === trim( $table['name'] ) ) { // @phpstan-ignore-line
225 $table['name'] = __( '(no name)', 'tablepress' ); // @phpstan-ignore-line
226 }
227 $tables[ $table_id ] = esc_html( $table['name'] ); // @phpstan-ignore-line
228 }
229
230 /**
231 * 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.
232 *
233 * @since 2.0.0
234 *
235 * @param array<string, string> $tables List of table names, the table ID is the array key.
236 */
237 $tables = apply_filters( 'tablepress_block_editor_tables_list', $tables );
238
239 $tables = wp_json_encode( $tables, TABLEPRESS_JSON_OPTIONS );
240 if ( false === $tables ) {
241 // JSON encoding failed, return an error object. Use a prefixed "_error" key to avoid conflicts with intentionally added "error" keys.
242 $tables = '{ "_error": "The data could not be encoded to JSON!" }';
243 }
244 // Print them inside a `JSON.parse()` call in JS for speed gains, with necessary escaping of `</script>`, `'`, and `\`.
245 $tables = str_replace( array( '</script>', '\\', "'" ), array( '<\/script>', '\\\\', "\'" ), $tables );
246
247 $shortcode = esc_js( TablePress::$shortcode );
248
249 $template = TablePress::$model_table->get_table_template();
250 $template = wp_json_encode( $template['options'], TABLEPRESS_JSON_OPTIONS );
251 if ( false === $template ) {
252 // JSON encoding failed, return an error object. Use a prefixed "_error" key to avoid conflicts with intentionally added "error" keys.
253 $template = '{ "_error": "The data could not be encoded to JSON!" }';
254 }
255 // Print them inside a `JSON.parse()` call in JS for speed gains, with necessary escaping of `</script>`, `'`, and `\`.
256 $template = str_replace( array( '</script>', '\\', "'" ), array( '<\/script>', '\\\\', "\'" ), $template );
257
258 /**
259 * Filters whether the table block preview should be loaded via a <ServerSideRender> in the block editor.
260 *
261 * @since 2.0.0
262 *
263 * @param bool $load_block_preview Whether the table block preview should be loaded.
264 */
265 $load_block_preview = apply_filters( 'tablepress_show_block_editor_preview', true );
266 $load_block_preview = (bool) $load_block_preview ? 'true' : 'false';
267
268 $url = '';
269 if ( current_user_can( 'tablepress_list_tables' ) ) {
270 $url = TablePress::url( array( 'action' => 'list' ) );
271 }
272
273 return <<<JS
274 // Ensure the global `tp` object exists.
275 window.tp = window.tp || {};
276 tp.url = '{$url}';
277 tp.load_block_preview = {$load_block_preview};
278 tp.table = {};
279 tp.table.shortcode = '{$shortcode}';
280 tp.table.template = JSON.parse( '{$template}' );
281 tp.tables = JSON.parse( '{$tables}' );
282 JS;
283 }
284
285 /**
286 * Register actions to add "Table" button to "HTML editor" and "Visual editor" toolbars.
287 *
288 * @since 1.0.0
289 */
290 public function add_editor_buttons(): void {
291 if ( ! current_user_can( 'tablepress_list_tables' ) ) {
292 return;
293 }
294
295 // Only load the toolbar integration if the Block Editor is not used.
296 if ( TablePress::site_uses_block_editor() ) {
297 return;
298 }
299
300 add_thickbox(); // The files are usually already loaded by media upload functions.
301 $admin_page = TablePress::load_class( 'TablePress_Admin_Page', 'class-admin-page-helper.php', 'classes' );
302 $admin_page->enqueue_script(
303 'quicktags-button',
304 array( 'quicktags', 'media-upload' ),
305 array(
306 'editor_button' => array(
307 'caption' => __( 'Table', 'tablepress' ),
308 'title' => __( 'Insert a TablePress table', 'tablepress' ),
309 'thickbox_title' => __( 'Insert a TablePress table', 'tablepress' ),
310 'thickbox_url' => TablePress::url( array( 'action' => 'editor_button_thickbox' ), true, 'admin-post.php' ),
311 ),
312 )
313 );
314
315 // TinyMCE integration.
316 if ( user_can_richedit() ) {
317 add_filter( 'mce_external_plugins', array( $this, 'add_tinymce_plugin' ) );
318 add_filter( 'mce_buttons', array( $this, 'add_tinymce_button' ) );
319 }
320 }
321
322 /**
323 * Adds the "Table" button to the TinyMCE toolbar.
324 *
325 * @since 1.0.0
326 *
327 * @param string[] $buttons Current set of buttons in the TinyMCE toolbar.
328 * @return string[] Extended set of buttons in the TinyMCE toolbar, including the "Table" button.
329 */
330 public function add_tinymce_button( array $buttons ): array {
331 $buttons[] = 'tablepress_insert_table';
332 return $buttons;
333 }
334
335 /**
336 * Registers the "Table" button plugin for the TinyMCE editor.
337 *
338 * @since 1.0.0
339 *
340 * @param array<string, string> $plugins Current set of registered TinyMCE plugins.
341 * @return array<string, string> Extended set of registered TinyMCE plugins, including the "Table" button plugin.
342 */
343 public function add_tinymce_plugin( array $plugins ): array {
344 $plugins['tablepress_tinymce'] = plugins_url( 'admin/js/build/tinymce-button.js', TABLEPRESS__FILE__ );
345 return $plugins;
346 }
347
348 /**
349 * Add "TablePress Table" entry to "New" dropdown menu in the WP Admin Bar.
350 *
351 * @since 1.0.0
352 *
353 * @param WP_Admin_Bar $wp_admin_bar The current WP Admin Bar object.
354 */
355 public function add_wp_admin_bar_new_content_menu_entry( WP_Admin_Bar $wp_admin_bar ): void {
356 if ( ! current_user_can( 'tablepress_add_tables' ) ) {
357 return;
358 }
359
360 // Don't load TablePress assets on the Freemius opt-in/activation screen.
361 if ( tb_tp_fs()->is_activation_mode() && tb_tp_fs()->is_activation_page() ) {
362 return;
363 }
364
365 $wp_admin_bar->add_menu( array(
366 'parent' => 'new-content',
367 'id' => 'new-tablepress-table',
368 'title' => __( 'TablePress Table', 'tablepress' ),
369 'href' => TablePress::url( array( 'action' => 'add' ) ),
370 ) );
371 }
372
373 /**
374 * Handle actions for loading of Plugins page.
375 *
376 * @since 1.0.0
377 */
378 public function plugins_page(): void {
379 // Add additional links on Plugins page.
380 add_filter( 'plugin_action_links_' . TABLEPRESS_BASENAME, array( $this, 'add_plugin_action_links' ) );
381 add_filter( 'plugin_row_meta', array( $this, 'add_plugin_row_meta' ), 10, 2 );
382 }
383
384 /**
385 * Add links to the TablePress entry in the "Plugin" column on the Plugins page.
386 *
387 * @since 1.0.0
388 *
389 * @param string[] $links List of links to print in the "Plugin" column on the Plugins page.
390 * @return string[] Extended list of links to print in the "Plugin" column on the Plugins page.
391 */
392 public function add_plugin_action_links( array $links ): array {
393 if ( current_user_can( 'tablepress_list_tables' ) ) {
394 $links[] = '<a href="' . TablePress::url() . '">' . __( 'Plugin page', 'tablepress' ) . '</a>';
395 }
396 return $links;
397 }
398
399 /**
400 * Add links to the TablePress entry in the "Description" column on the Plugins page.
401 *
402 * @since 1.0.0
403 *
404 * @param string[] $links List of links to print in the "Description" column on the Plugins page.
405 * @param string $file Name of the plugin.
406 * @return string[] Extended list of links to print in the "Description" column on the Plugins page.
407 */
408 public function add_plugin_row_meta( array $links, string $file ): array {
409 if ( TABLEPRESS_BASENAME === $file ) {
410 $links[] = '<a href="https://tablepress.org/faq/" title="' . esc_attr__( 'Frequently Asked Questions', 'tablepress' ) . '">' . __( 'FAQ', 'tablepress' ) . '</a>';
411 $links[] = '<a href="https://tablepress.org/documentation/">' . __( 'Documentation', 'tablepress' ) . '</a>';
412 $links[] = '<a href="https://tablepress.org/support/">' . __( 'Support', 'tablepress' ) . '</a>';
413 if ( ! TABLEPRESS_IS_PLAYGROUND_PREVIEW && tb_tp_fs()->is_free_plan() ) {
414 $links[] = '<a href="https://tablepress.org/premium/?utm_source=plugin&utm_medium=textlink&utm_content=plugins-screen" title="' . esc_attr__( 'Check out the Premium version of TablePress!', 'tablepress' ) . '"><strong>' . __( 'Go Premium', 'tablepress' ) . '</strong></a>';
415 }
416 }
417 return $links;
418 }
419
420 /**
421 * Prepare the rendering of an admin screen, by determining the current action, loading necessary data and initializing the view.
422 *
423 * @since 1.0.0
424 */
425 public function load_admin_page(): void {
426 // Determine the action from either the GET parameter (for sub-menu entries, and the main admin menu entry).
427 $action = ( ! empty( $_GET['action'] ) ) ? $_GET['action'] : 'list'; // Default action is list.
428 if ( $this->is_top_level_page ) {
429 // Or, for sub-menu entry of an admin menu "TablePress" entry, get it from the "page" GET parameter.
430 if ( 'tablepress' !== $_GET['page'] ) {
431 // Actions that are top-level entries, but don't have an action GET parameter (action is after last _ in string).
432 $action = substr( $_GET['page'], 11 ); // $_GET['page'] has the format 'tablepress_{$action}'
433 }
434 }
435
436 // Check if action is a supported action, and whether the user is allowed to access this screen.
437 if ( ! isset( $this->view_actions[ $action ] ) || ! current_user_can( $this->view_actions[ $action ]['required_cap'] ) ) { // @phpstan-ignore-line
438 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
439 }
440
441 // Don't load TablePress assets on the Freemius opt-in/activation screen.
442 if ( tb_tp_fs()->is_activation_mode() && tb_tp_fs()->is_activation_page() ) {
443 return;
444 }
445
446 // Changes current screen ID and pagenow variable in JS, to enable automatic meta box JS handling.
447 set_current_screen( "tablepress_{$action}" );
448
449 /*
450 * Set the `$typenow` global to the current CPT ourselves, as `WP_Screen::get()` does not determine the CPT correctly.
451 * This is necessary as the WP Admin Menu can otherwise highlight wrong entries, see https://github.com/TablePress/TablePress/issues/24.
452 */
453 if ( isset( $_GET['post_type'] ) && post_type_exists( $_GET['post_type'] ) ) {
454 $GLOBALS['typenow'] = $_GET['post_type']; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
455 }
456
457 // Pre-define some view data.
458 $data = array(
459 'view_actions' => $this->view_actions,
460 'message' => ( ! empty( $_GET['message'] ) ) ? $_GET['message'] : false,
461 'error_details' => ( ! empty( $_GET['error_details'] ) ) ? $_GET['error_details'] : '',
462 'site_uses_block_editor' => TablePress::site_uses_block_editor(),
463 );
464
465 // Depending on the action, load more necessary data for the corresponding view.
466 switch ( $action ) {
467 case 'list':
468 $data['table_id'] = ( ! empty( $_GET['table_id'] ) ) ? $_GET['table_id'] : false;
469 // Prime the post meta cache for cached loading of last_editor.
470 $data['table_ids'] = TablePress::$model_table->load_all( true );
471 $data['messages']['donation_message'] = $this->maybe_show_donation_message();
472 $data['messages']['first_visit'] = ! $data['messages']['donation_message'] && TablePress::$model_options->get( 'message_first_visit' );
473 $data['messages']['plugin_update_message'] = TablePress::$model_options->get( 'message_plugin_update' );
474 $data['table_count'] = count( $data['table_ids'] );
475 break;
476 case 'about':
477 $data['first_activation'] = TablePress::$model_options->get( 'first_activation' );
478 break;
479 case 'options':
480 /*
481 * Maybe try saving "Custom CSS" to a file:
482 * (called here, as the credentials form posts to this handler again, due to how `request_filesystem_credentials()` works)
483 */
484 if ( isset( $_GET['item'] ) && 'save_custom_css' === $_GET['item'] ) {
485 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.
486 $action = 'options_custom_css'; // to load a different view
487 // Try saving "Custom CSS" to a file, otherwise this gets the HTML for the credentials form.
488 $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' );
489 $result = $tablepress_css->save_custom_css_to_file_plugin_options( TablePress::$model_options->get( 'custom_css' ), TablePress::$model_options->get( 'custom_css_minified' ) );
490 if ( is_string( $result ) ) {
491 $data['credentials_form'] = $result; // This will only be called if the save function doesn't do a redirect.
492 } elseif ( true === $result ) {
493 /*
494 * At this point, saving was successful, so enable usage of CSS in files again,
495 * and also increase the "Custom CSS" version number (for cache busting).
496 */
497 TablePress::$model_options->update( array(
498 'use_custom_css_file' => true,
499 'custom_css_version' => TablePress::$model_options->get( 'custom_css_version' ) + 1,
500 ) );
501 TablePress::redirect( array( 'action' => 'options', 'message' => 'success_save' ) );
502 } else { // Leaves only $result === false.
503 TablePress::redirect( array( 'action' => 'options', 'message' => 'success_save_error_custom_css' ) );
504 }
505 break;
506 }
507 $data['frontend_options']['use_custom_css'] = TablePress::$model_options->get( 'use_custom_css' );
508 $data['frontend_options']['custom_css'] = TablePress::$model_options->get( 'custom_css' );
509 $data['user_options']['parent_page'] = $this->parent_page;
510 break;
511 case 'edit':
512 if ( empty( $_GET['table_id'] ) ) {
513 TablePress::redirect( array( 'action' => 'list', 'message' => 'error_no_table' ) );
514 }
515 // Load table, with table data, options, and visibility settings.
516 $data['table'] = TablePress::$model_table->load( $_GET['table_id'], true, true );
517 if ( is_wp_error( $data['table'] ) ) {
518 TablePress::redirect( array( 'action' => 'list', 'message' => 'error_load_table', 'error_details' => TablePress::get_wp_error_string( $data['table'] ) ) );
519 }
520 if ( ! current_user_can( 'tablepress_edit_table', $_GET['table_id'] ) ) {
521 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
522 }
523 break;
524 case 'export':
525 // Load all table IDs without priming the post meta cache, as table options/visibility are not needed.
526 $table_ids = TablePress::$model_table->load_all( false );
527 $data['tables'] = array();
528 foreach ( $table_ids as $table_id ) {
529 if ( ! current_user_can( 'tablepress_export_table', $table_id ) ) {
530 continue;
531 }
532 // Load table, without table data, options, and visibility settings.
533 $table = TablePress::$model_table->load( $table_id, false, false );
534 $data['tables'][ $table['id'] ] = $table['name']; // @phpstan-ignore-line
535 }
536 $data['tables_count'] = TablePress::$model_table->count_tables();
537 $data['export_ids'] = ( ! empty( $_GET['table_id'] ) ) ? explode( ',', $_GET['table_id'] ) : array();
538 $exporter = TablePress::load_class( 'TablePress_Export', 'class-export.php', 'classes' );
539 $data['zip_support_available'] = $exporter->zip_support_available;
540 $data['export_formats'] = $exporter->export_formats;
541 $data['csv_delimiters'] = $exporter->csv_delimiters;
542 $data['export_format'] = ( ! empty( $_GET['export_format'] ) ) ? $_GET['export_format'] : 'csv';
543 $data['csv_delimiter'] = ( ! empty( $_GET['csv_delimiter'] ) ) ? $_GET['csv_delimiter'] : _x( ',', 'Default CSV delimiter in the translated language (";", ",", or "tab")', 'tablepress' );
544 break;
545 case 'import':
546 // Load all table IDs without priming the post meta cache, as table options/visibility are not needed.
547 $table_ids = TablePress::$model_table->load_all( false );
548 $data['tables'] = array();
549 foreach ( $table_ids as $table_id ) {
550 if ( ! current_user_can( 'tablepress_edit_table', $table_id ) ) {
551 continue;
552 }
553 // Load table, without table data, options, and visibility settings.
554 $table = TablePress::$model_table->load( $table_id, false, false );
555 $data['tables'][ $table['id'] ] = $table['name']; // @phpstan-ignore-line
556 }
557 $data['table_ids'] = $table_ids; // Backward compatibility for the retired "Table Auto Update" Extension, which still relies on this variable name.
558 $data['tables_count'] = TablePress::$model_table->count_tables();
559 $importer = TablePress::load_class( 'TablePress_Import', 'class-import.php', 'classes' );
560 $data['import_type'] = ( ! empty( $_GET['import_type'] ) ) ? $_GET['import_type'] : 'add';
561 $data['import_existing_table'] = ( ! empty( $_GET['import_existing_table'] ) ) ? $_GET['import_existing_table'] : '';
562 $data['import_source'] = ( ! empty( $_GET['import_source'] ) ) ? $_GET['import_source'] : 'file-upload';
563 $data['import_url'] = ( ! empty( $_GET['import_url'] ) ) ? wp_unslash( $_GET['import_url'] ) : 'https://';
564 $data['import_server'] = ( ! empty( $_GET['import_server'] ) ) ? wp_unslash( $_GET['import_server'] ) : ABSPATH;
565 $data['import_form-field'] = ( ! empty( $_GET['import_form-field'] ) ) ? wp_unslash( $_GET['import_form-field'] ) : '';
566 $data['legacy_import'] = ( ! empty( $_GET['legacy_import'] ) ) ? $_GET['legacy_import'] : 'false';
567 break;
568 }
569
570 /**
571 * Filters the data that is passed to the current TablePress View.
572 *
573 * @since 1.0.0
574 *
575 * @param array<string, mixed> $data Data for the view.
576 * @param string $action The current action for the view.
577 */
578 $data = apply_filters( 'tablepress_view_data', $data, $action );
579
580 // Prepare and initialize the view.
581 $this->view = TablePress::load_view( $action, $data );
582 }
583
584 /**
585 * Render the view that has been initialized in load_admin_page() (called by WordPress when the actual page content is needed).
586 *
587 * @since 1.0.0
588 */
589 public function show_admin_page(): void {
590 $this->view->render();
591 }
592
593 /**
594 * 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.
595 *
596 * @since 1.0.0
597 *
598 * @return bool Whether the message shall be shown on the "All Tables" screen.
599 */
600 protected function maybe_show_donation_message(): bool {
601 // Only show the message to plugin admins.
602 if ( ! current_user_can( 'tablepress_edit_options' ) ) {
603 return false;
604 }
605
606 if ( ! TablePress::$model_options->get( 'message_donation_nag' ) ) {
607 return false;
608 }
609
610 // Determine, how long has the plugin been installed.
611 $seconds_installed = time() - TablePress::$model_options->get( 'first_activation' );
612 return ( $seconds_installed > MONTH_IN_SECONDS / 2 );
613 }
614
615 /**
616 * Init list of actions that have a view with their titles/names/caps.
617 *
618 * @since 1.0.0
619 */
620 protected function init_view_actions(): void {
621 $this->view_actions = array(
622 'list' => array(
623 'show_entry' => true,
624 'page_title' => __( 'All Tables', 'tablepress' ),
625 'admin_menu_title' => __( 'All Tables', 'tablepress' ),
626 'nav_tab_title' => __( 'All Tables', 'tablepress' ),
627 'required_cap' => 'tablepress_list_tables',
628 ),
629 'add' => array(
630 'show_entry' => true,
631 'page_title' => __( 'Add New Table', 'tablepress' ),
632 'admin_menu_title' => __( 'Add New Table', 'tablepress' ),
633 'nav_tab_title' => __( 'Add New', 'tablepress' ),
634 'required_cap' => 'tablepress_add_tables',
635 ),
636 'edit' => array(
637 'show_entry' => false,
638 'page_title' => __( 'Edit Table', 'tablepress' ),
639 'admin_menu_title' => '',
640 'nav_tab_title' => '',
641 'required_cap' => 'tablepress_edit_tables',
642 ),
643 'import' => array(
644 'show_entry' => true,
645 'page_title' => __( 'Import a Table', 'tablepress' ),
646 'admin_menu_title' => __( 'Import a Table', 'tablepress' ),
647 'nav_tab_title' => _x( 'Import', 'navigation bar', 'tablepress' ),
648 'required_cap' => 'tablepress_import_tables',
649 ),
650 'export' => array(
651 'show_entry' => true,
652 'page_title' => __( 'Export a Table', 'tablepress' ),
653 'admin_menu_title' => __( 'Export a Table', 'tablepress' ),
654 'nav_tab_title' => _x( 'Export', 'navigation bar', 'tablepress' ),
655 'required_cap' => 'tablepress_export_tables',
656 ),
657 'options' => array(
658 'show_entry' => true,
659 'page_title' => __( 'Plugin Options', 'tablepress' ),
660 'admin_menu_title' => __( 'Plugin Options', 'tablepress' ),
661 'nav_tab_title' => __( 'Plugin Options', 'tablepress' ),
662 'required_cap' => 'tablepress_access_options_screen',
663 ),
664 'about' => array(
665 'show_entry' => true,
666 'page_title' => __( 'About', 'tablepress' ),
667 'admin_menu_title' => __( 'About TablePress', 'tablepress' ),
668 'nav_tab_title' => __( 'About', 'tablepress' ),
669 'required_cap' => 'tablepress_access_about_screen',
670 ),
671 );
672
673 /**
674 * Filters the available TablePres Views/Actions and their parameters.
675 *
676 * @since 1.0.0
677 *
678 * @param array<string, array<string, bool|string>> $view_actions The available Views/Actions and their parameters.
679 */
680 $this->view_actions = apply_filters( 'tablepress_admin_view_actions', $this->view_actions );
681 }
682
683 /*
684 * HTTP POST actions.
685 */
686
687 /**
688 * Handle Bulk Actions (Copy, Export, Delete) on "All Tables" list screen.
689 *
690 * @since 1.0.0
691 */
692 public function handle_post_action_list(): void {
693 TablePress::check_nonce( 'list' );
694
695 if ( isset( $_POST['bulk-action-selector-top'] ) && '-1' !== $_POST['bulk-action-selector-top'] ) {
696 $bulk_action = $_POST['bulk-action-selector-top'];
697 } elseif ( isset( $_POST['bulk-action-selector-bottom'] ) && '-1' !== $_POST['bulk-action-selector-bottom'] ) {
698 $bulk_action = $_POST['bulk-action-selector-bottom'];
699 } else {
700 $bulk_action = false;
701 }
702
703 if ( ! in_array( $bulk_action, array( 'copy', 'export', 'delete' ), true ) ) {
704 TablePress::redirect( array( 'action' => 'list', 'message' => 'error_bulk_action_invalid' ) );
705 }
706
707 if ( empty( $_POST['table'] ) || ! is_array( $_POST['table'] ) ) {
708 TablePress::redirect( array( 'action' => 'list', 'message' => 'error_no_selection' ) );
709 }
710
711 $tables = wp_unslash( $_POST['table'] );
712
713 $no_success = array(); // To store table IDs that failed.
714
715 switch ( $bulk_action ) {
716 case 'copy':
717 foreach ( $tables as $table_id ) {
718 if ( current_user_can( 'tablepress_copy_table', $table_id ) ) {
719 $copy_table_id = TablePress::$model_table->copy( $table_id );
720 if ( is_wp_error( $copy_table_id ) ) {
721 $no_success[] = $table_id;
722 }
723 } else {
724 $no_success[] = $table_id;
725 }
726 }
727 break;
728 case 'export':
729 /*
730 * Cap check is done on redirect target page.
731 * To export, redirect to "Export" screen, with selected table IDs.
732 */
733 $table_ids = implode( ',', $tables );
734 TablePress::redirect( array( 'action' => 'export', 'table_id' => $table_ids ) );
735 // break; // unreachable.
736 case 'delete':
737 foreach ( $tables as $table_id ) {
738 if ( current_user_can( 'tablepress_delete_table', $table_id ) ) {
739 $deleted = TablePress::$model_table->delete( $table_id );
740 if ( is_wp_error( $deleted ) ) {
741 $no_success[] = $table_id;
742 }
743 } else {
744 $no_success[] = $table_id;
745 }
746 }
747 break;
748 }
749
750 if ( 0 !== count( $no_success ) ) { // @todo maybe pass this information to the view?
751 $message = "error_{$bulk_action}_not_all_tables";
752 } else {
753 $plural = ( count( $tables ) > 1 ) ? '_plural' : '';
754 $message = "success_{$bulk_action}{$plural}";
755 }
756
757 /*
758 * Slightly more complex redirect method, to account for sort, search, and pagination in the WP_List_Table on the List View,
759 * but only if this action succeeds, to have everything fresh in the event of an error.
760 */
761 $sendback = wp_get_referer();
762 if ( ! $sendback ) {
763 $sendback = TablePress::url( array( 'action' => 'list', 'message' => $message ) );
764 } else {
765 $sendback = remove_query_arg( array( 'action', 'message', 'table_id' ), $sendback );
766 $sendback = add_query_arg( array( 'action' => 'list', 'message' => $message ), $sendback );
767 }
768 wp_redirect( $sendback );
769 exit;
770 }
771
772 /**
773 * Add a table, according to the parameters on the "Add new Table" screen.
774 *
775 * @since 1.0.0
776 */
777 public function handle_post_action_add(): void {
778 TablePress::check_nonce( 'add' );
779
780 if ( ! current_user_can( 'tablepress_add_tables' ) ) {
781 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
782 }
783
784 if ( empty( $_POST['table'] ) || ! is_array( $_POST['table'] ) ) {
785 TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => 'The HTTP POST data is empty.' ) );
786 }
787
788 $add_table = wp_unslash( $_POST['table'] );
789
790 // Perform confidence checks of posted data.
791 $name = ( isset( $add_table['name'] ) ) ? $add_table['name'] : '';
792 $description = ( isset( $add_table['description'] ) ) ? $add_table['description'] : '';
793 if ( ! isset( $add_table['rows'], $add_table['columns'] ) ) {
794 TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => 'The HTTP POST data does not contain the table size.' ) );
795 }
796
797 $num_rows = absint( $add_table['rows'] );
798 $num_columns = absint( $add_table['columns'] );
799 if ( 0 === $num_rows || 0 === $num_columns ) {
800 TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => 'The table size is invalid.' ) );
801 }
802
803 // Create a new table array with information from the posted data.
804 $new_table = array(
805 'name' => $name,
806 'description' => $description,
807 'data' => array_fill( 0, $num_rows, array_fill( 0, $num_columns, '' ) ),
808 'visibility' => array(
809 'rows' => array_fill( 0, $num_rows, 1 ),
810 'columns' => array_fill( 0, $num_columns, 1 ),
811 ),
812 );
813 // Merge this data into an empty table template.
814 $table = TablePress::$model_table->prepare_table( TablePress::$model_table->get_table_template(), $new_table, false );
815 if ( is_wp_error( $table ) ) {
816 TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => TablePress::get_wp_error_string( $table ) ) );
817 }
818
819 // Add the new table (and get its first ID).
820 $table_id = TablePress::$model_table->add( $table );
821 if ( is_wp_error( $table_id ) ) {
822 TablePress::redirect( array( 'action' => 'add', 'message' => 'error_add', 'error_details' => TablePress::get_wp_error_string( $table_id ) ) );
823 }
824
825 TablePress::redirect( array( 'action' => 'edit', 'table_id' => $table_id, 'message' => 'success_add' ) );
826 }
827
828 /**
829 * Save changed "Plugin Options".
830 *
831 * @since 1.0.0
832 */
833 public function handle_post_action_options(): void {
834 TablePress::check_nonce( 'options' );
835
836 if ( ! current_user_can( 'tablepress_access_options_screen' ) ) {
837 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
838 }
839
840 if ( empty( $_POST['options'] ) || ! is_array( $_POST['options'] ) ) {
841 TablePress::redirect( array( 'action' => 'options', 'message' => 'error_save' ) );
842 }
843
844 $posted_options = wp_unslash( $_POST['options'] );
845
846 // Valid new options that will be merged into existing ones.
847 $new_options = array();
848
849 // Check each posted option value, and (maybe) add it to the new options.
850 if ( ! empty( $posted_options['admin_menu_parent_page'] ) && '-' !== $posted_options['admin_menu_parent_page'] ) {
851 $new_options['admin_menu_parent_page'] = $posted_options['admin_menu_parent_page'];
852 // Re-init parent information, as `TablePress::redirect()` URL might be wrong otherwise.
853 /** This filter is documented in classes/class-controller.php */
854 $this->parent_page = apply_filters( 'tablepress_admin_menu_parent_page', $posted_options['admin_menu_parent_page'] );
855 $this->is_top_level_page = in_array( $this->parent_page, array( 'top', 'middle', 'bottom' ), true );
856 }
857
858 // Custom CSS can only be saved if the user is allowed to do so.
859 $update_custom_css_files = false;
860 if ( current_user_can( 'tablepress_edit_options' ) ) {
861 // Checkbox.
862 $new_options['use_custom_css'] = ( isset( $posted_options['use_custom_css'] ) && 'true' === $posted_options['use_custom_css'] );
863
864 if ( isset( $posted_options['custom_css'] ) ) {
865 $new_options['custom_css'] = $posted_options['custom_css'];
866
867 $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' );
868 // Sanitize and tidy up Custom CSS.
869 $new_options['custom_css'] = $tablepress_css->sanitize_css( $new_options['custom_css'] );
870 // Minify Custom CSS.
871 $new_options['custom_css_minified'] = $tablepress_css->minify_css( $new_options['custom_css'] );
872
873 // Maybe update CSS files as well.
874 $custom_css_file_contents = $tablepress_css->load_custom_css_from_file( 'normal' );
875 if ( false === $custom_css_file_contents ) {
876 $custom_css_file_contents = '';
877 }
878 // Don't write to file if it already has the desired content.
879 if ( $new_options['custom_css'] !== $custom_css_file_contents ) {
880 $update_custom_css_files = true;
881 // Set to false again. As it was set here, it will be set true again, if file saving succeeds.
882 $new_options['use_custom_css_file'] = false;
883 }
884 }
885 }
886
887 // 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.
888 if ( ! empty( $new_options ) ) {
889 TablePress::$model_options->update( $new_options );
890 TablePress::$model_table->_flush_caching_plugins_caches();
891 }
892
893 if ( $update_custom_css_files ) { // Capability check is performed above.
894 TablePress::redirect( array( 'action' => 'options', 'item' => 'save_custom_css' ), true );
895 }
896
897 TablePress::redirect( array( 'action' => 'options', 'message' => 'success_save' ) );
898 }
899
900 /**
901 * Export selected tables.
902 *
903 * @since 1.0.0
904 */
905 public function handle_post_action_export(): void {
906 TablePress::check_nonce( 'export' );
907
908 if ( ! current_user_can( 'tablepress_export_tables' ) ) {
909 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
910 }
911
912 if ( empty( $_POST['export'] ) || ! is_array( $_POST['export'] ) ) {
913 TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The HTTP POST data is empty.' ) );
914 }
915
916 $export = wp_unslash( $_POST['export'] );
917
918 if ( empty( $export['tables_list'] ) ) {
919 TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The HTTP POST data does not contain tables.' ) );
920 }
921
922 /** @var TablePress_Export $exporter */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
923 $exporter = TablePress::load_class( 'TablePress_Export', 'class-export.php', 'classes' );
924
925 if ( empty( $export['format'] ) || ! isset( $exporter->export_formats[ $export['format'] ] ) ) {
926 TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The export format is invalid.' ) );
927 }
928 if ( empty( $export['csv_delimiter'] ) ) {
929 // Set a value, so that the variable exists.
930 $export['csv_delimiter'] = '';
931 }
932 if ( 'csv' === $export['format'] && ! isset( $exporter->csv_delimiters[ $export['csv_delimiter'] ] ) ) {
933 TablePress::redirect( array( 'action' => 'export', 'message' => 'error_export', 'error_details' => 'The CSV delimiter is invalid.' ) );
934 }
935
936 $tables = explode( ',', $export['tables_list'] );
937
938 // Determine if ZIP file support is available.
939 if ( $exporter->zip_support_available
940 && ( ( isset( $export['zip_file'] ) && 'true' === $export['zip_file'] ) || count( $tables ) > 1 ) ) {
941 // Export to ZIP only if ZIP is desired or if more than one table were selected (mandatory then).
942 $export_to_zip = true;
943 } else {
944 $export_to_zip = false;
945 }
946
947 if ( ! $export_to_zip ) {
948 // Exporting without a ZIP file is only possible for one table, so take the first one.
949 if ( ! current_user_can( 'tablepress_export_table', $tables[0] ) ) {
950 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
951 }
952 // Load table, with table data, options, and visibility settings.
953 $table = TablePress::$model_table->load( $tables[0], true, true );
954 if ( is_wp_error( $table ) ) {
955 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 ) ) );
956 }
957 if ( isset( $table['is_corrupted'] ) && $table['is_corrupted'] ) {
958 TablePress::redirect( array( 'action' => 'export', 'message' => 'error_table_corrupted', 'export_format' => $export['format'], 'csv_delimiter' => $export['csv_delimiter'] ) );
959 }
960 $download_filename = sprintf( '%1$s-%2$s-%3$s.%4$s', $table['id'], $table['name'], wp_date( 'Y-m-d' ), $export['format'] );
961 /**
962 * Filters the download filename of the exported table.
963 *
964 * @since 2.0.0
965 *
966 * @param string $download_filename The download filename of exported table.
967 * @param string $table_id Table ID of the exported table.
968 * @param string $table_name Table name of the exported table.
969 * @param string $export_format Format for the export ('csv', 'html', 'json', 'zip').
970 * @param bool $export_to_zip Whether the export is to a ZIP file (of multiple export files).
971 */
972 $download_filename = apply_filters( 'tablepress_export_filename', $download_filename, $table['id'], $table['name'], $export['format'], $export_to_zip );
973 $download_filename = sanitize_file_name( $download_filename );
974 // Export the table.
975 $export_data = $exporter->export_table( $table, $export['format'], $export['csv_delimiter'] );
976 /**
977 * Filters the exported table data.
978 *
979 * @since 1.6.0
980 *
981 * @param string $export_data The exported table data.
982 * @param array<string, mixed> $table Table to be exported.
983 * @param string $export_format Format for the export ('csv', 'html', 'json').
984 * @param string $csv_delimiter Delimiter for CSV export.
985 */
986 $export_data = apply_filters( 'tablepress_export_data', $export_data, $table, $export['format'], $export['csv_delimiter'] );
987 $download_data = $export_data;
988 } else {
989 // Zipping can use a lot of memory and execution time, but not this much hopefully.
990 wp_raise_memory_limit( 'admin' );
991 if ( function_exists( 'set_time_limit' ) ) {
992 @set_time_limit( 300 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
993 }
994
995 $zip_file = new ZipArchive();
996 $download_filename = sprintf( 'tablepress-export-%1$s-%2$s.zip', wp_date( 'Y-m-d-H-i-s' ), $export['format'] );
997 /** This filter is documented in controllers/controller-admin.php */
998 $download_filename = apply_filters( 'tablepress_export_filename', $download_filename, '', '', $export['format'], $export_to_zip );
999 $download_filename = sanitize_file_name( $download_filename );
1000 $full_filename = wp_tempnam( $download_filename );
1001 if ( true !== $zip_file->open( $full_filename, ZIPARCHIVE::OVERWRITE ) ) {
1002 @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1003 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.' ) );
1004 }
1005
1006 foreach ( $tables as $table_id ) {
1007 // Don't export tables for which the user doesn't have the necessary export rights.
1008 if ( ! current_user_can( 'tablepress_export_table', $table_id ) ) {
1009 continue;
1010 }
1011 // Load table, with table data, options, and visibility settings.
1012 $table = TablePress::$model_table->load( $table_id, true, true );
1013 // Don't export if the table could not be loaded.
1014 if ( is_wp_error( $table ) ) {
1015 continue;
1016 }
1017 // Don't export if the table is corrupted.
1018 if ( isset( $table['is_corrupted'] ) && $table['is_corrupted'] ) {
1019 continue;
1020 }
1021 $export_data = $exporter->export_table( $table, $export['format'], $export['csv_delimiter'] );
1022 /** This filter is documented in controllers/controller-admin.php */
1023 $export_data = apply_filters( 'tablepress_export_data', $export_data, $table, $export['format'], $export['csv_delimiter'] );
1024 $export_filename = sprintf( '%1$s-%2$s-%3$s.%4$s', $table['id'], $table['name'], wp_date( 'Y-m-d' ), $export['format'] );
1025 /** This filter is documented in controllers/controller-admin.php */
1026 $export_filename = apply_filters( 'tablepress_export_filename', $export_filename, $table['id'], $table['name'], $export['format'], $export_to_zip );
1027 $export_filename = sanitize_file_name( $export_filename );
1028 $zip_file->addFromString( $export_filename, $export_data );
1029 }
1030
1031 // If something went wrong, or no files were added to the ZIP file, bail out.
1032 // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
1033 if ( ZIPARCHIVE::ER_OK !== $zip_file->status || 0 === $zip_file->numFiles ) {
1034 $zip_file->close();
1035 @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1036 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.' ) );
1037 }
1038 $zip_file->close();
1039
1040 // Load contents of the ZIP file, to send it as a download.
1041 $download_data = file_get_contents( $full_filename );
1042 if ( false === $download_data ) {
1043 @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1044 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.' ) );
1045 }
1046 @unlink( $full_filename ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1047 }
1048
1049 // Send download headers for export file.
1050 header( 'Content-Description: File Transfer' );
1051 header( 'Content-Type: application/octet-stream' );
1052 header( "Content-Disposition: attachment; filename=\"{$download_filename}\"" );
1053 header( 'Content-Transfer-Encoding: binary' );
1054 header( 'Expires: 0' );
1055 header( 'Cache-Control: must-revalidate' );
1056 header( 'Pragma: public' );
1057 header( 'Content-Length: ' . strlen( $download_data ) );
1058 // $filetype = text/csv, text/html, application/json
1059 // header( 'Content-Type: ' . $filetype. '; charset=' . get_option( 'blog_charset' ) );
1060 @ob_end_clean(); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1061 flush();
1062 echo $download_data;
1063 exit;
1064 }
1065
1066 /**
1067 * Import data from existing source (Upload, URL, Server, Direct input).
1068 *
1069 * @since 1.0.0
1070 */
1071 public function handle_post_action_import(): void {
1072 TablePress::check_nonce( 'import' );
1073
1074 if ( ! current_user_can( 'tablepress_import_tables' ) ) {
1075 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1076 }
1077
1078 if ( empty( $_POST['import'] ) || ! is_array( $_POST['import'] ) ) {
1079 TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The HTTP POST data is empty.' ) );
1080 }
1081
1082 $import_config = wp_unslash( $_POST['import'] );
1083
1084 if ( empty( $import_config['source'] ) ) {
1085 TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The HTTP POST does not contain an import configuration.' ) );
1086 }
1087
1088 // For security reasons, the "server" source is only available for super admins on multisite and admins on single sites.
1089 if ( 'server' === $import_config['source'] ) {
1090 if ( ! is_super_admin() && ! ( ! is_multisite() && current_user_can( 'manage_options' ) ) ) {
1091 TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'You do not have the required access rights.' ) );
1092 }
1093 }
1094
1095 // Move file upload data to the main import configuration.
1096 $import_config['file-upload'] = $_FILES['import_file_upload'] ?? null;
1097
1098 // Check if the source data for the chosen import source is defined.
1099 if ( empty( $import_config[ $import_config['source'] ] ) ) {
1100 TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The HTTP POST data does not contain an import source.' ) );
1101 }
1102
1103 // Set default values for non-essential configuration variables.
1104 if ( ! isset( $import_config['type'] ) ) {
1105 $import_config['type'] = 'add';
1106 }
1107 if ( ! isset( $import_config['existing_table'] ) ) {
1108 $import_config['existing_table'] = '';
1109 }
1110
1111 $import_config['legacy_import'] = ( isset( $import_config['legacy_import'] ) && 'true' === $import_config['legacy_import'] );
1112
1113 $importer = TablePress::load_class( 'TablePress_Import', 'class-import.php', 'classes' );
1114 $import = $importer->run( $import_config );
1115
1116 if ( is_wp_error( $import ) || 0 < count( $import['errors'] ) ) {
1117 $redirect_parameters = array(
1118 'action' => 'import',
1119 'message' => 'error_import',
1120 'import_type' => $import_config['type'],
1121 'import_existing_table' => $import_config['existing_table'],
1122 'import_source' => $import_config['source'],
1123 'legacy_import' => $import_config['legacy_import'],
1124 );
1125 if ( in_array( $import_config['source'], array( 'url', 'server' ), true ) ) {
1126 $redirect_parameters[ "import_{$import_config['source']}" ] = $import_config[ $import_config['source'] ];
1127 }
1128 if ( is_wp_error( $import ) ) {
1129 $redirect_parameters['error_details'] = TablePress::get_wp_error_string( $import );
1130 } elseif ( 0 < count( $import['errors'] ) ) {
1131 $wp_error_strings = array();
1132 foreach ( $import['errors'] as $file ) {
1133 $wp_error_strings[] = TablePress::get_wp_error_string( $file->error );
1134 }
1135 $redirect_parameters['error_details'] = implode( ', ', $wp_error_strings );
1136 }
1137 TablePress::redirect( $redirect_parameters );
1138 }
1139
1140 // At this point, there were no import errors.
1141 if ( count( $import['tables'] ) > 1 ) {
1142 TablePress::redirect( array( 'action' => 'list', 'message' => 'success_import' ) );
1143 } elseif ( 1 === count( $import['tables'] ) ) {
1144 TablePress::redirect( array( 'action' => 'edit', 'table_id' => $import['tables'][0]['id'], 'message' => 'success_import' ) );
1145 } else {
1146 TablePress::redirect( array( 'action' => 'import', 'message' => 'error_import', 'error_details' => 'The number of imported tables is invalid.' ) );
1147 }
1148 }
1149
1150 /*
1151 * HTTP GET actions.
1152 */
1153
1154 /**
1155 * Hide a header message on an admin screen.
1156 *
1157 * @since 1.0.0
1158 */
1159 public function handle_get_action_hide_message(): void {
1160 $message_item = ! empty( $_GET['item'] ) ? $_GET['item'] : '';
1161 TablePress::check_nonce( 'hide_message', $message_item );
1162
1163 if ( ! current_user_can( 'tablepress_list_tables' ) ) {
1164 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1165 }
1166
1167 TablePress::$model_options->update( "message_{$message_item}", false );
1168
1169 $return = ! empty( $_GET['return'] ) ? $_GET['return'] : 'list';
1170 TablePress::redirect( array( 'action' => $return ) );
1171 }
1172
1173 /**
1174 * Delete a table.
1175 *
1176 * @since 1.0.0
1177 */
1178 public function handle_get_action_delete_table(): void {
1179 $table_id = ( ! empty( $_GET['item'] ) ) ? $_GET['item'] : false;
1180 TablePress::check_nonce( 'delete_table', $table_id );
1181
1182 $return = ! empty( $_GET['return'] ) ? $_GET['return'] : 'list';
1183 $return_item = ! empty( $_GET['return_item'] ) ? $_GET['return_item'] : false;
1184
1185 // The nonce check should actually catch this already.
1186 if ( false === $table_id ) {
1187 TablePress::redirect( array( 'action' => $return, 'message' => 'error_delete', 'table_id' => $return_item ) );
1188 }
1189
1190 if ( ! current_user_can( 'tablepress_delete_table', $table_id ) ) {
1191 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1192 }
1193
1194 $deleted = TablePress::$model_table->delete( $table_id );
1195 if ( is_wp_error( $deleted ) ) {
1196 TablePress::redirect( array( 'action' => $return, 'message' => 'error_delete', 'table_id' => $return_item, 'error_details' => TablePress::get_wp_error_string( $deleted ) ) );
1197 }
1198
1199 /*
1200 * Slightly more complex redirect method, to account for sort, search, and pagination in the WP_List_Table on the List View,
1201 * but only if this action succeeds, to have everything fresh in the event of an error.
1202 */
1203 $sendback = wp_get_referer();
1204 if ( ! $sendback ) {
1205 $sendback = TablePress::url( array( 'action' => 'list', 'message' => 'success_delete', 'table_id' => $return_item ) );
1206 } else {
1207 $sendback = remove_query_arg( array( 'action', 'message', 'table_id' ), $sendback );
1208 $sendback = add_query_arg( array( 'action' => 'list', 'message' => 'success_delete', 'table_id' => $return_item ), $sendback );
1209 }
1210 wp_redirect( $sendback );
1211 exit;
1212 }
1213
1214 /**
1215 * Copy a table.
1216 *
1217 * @since 1.0.0
1218 */
1219 public function handle_get_action_copy_table(): void {
1220 $table_id = ( ! empty( $_GET['item'] ) ) ? $_GET['item'] : false;
1221 TablePress::check_nonce( 'copy_table', $table_id );
1222
1223 $return = ! empty( $_GET['return'] ) ? $_GET['return'] : 'list';
1224 $return_item = ! empty( $_GET['return_item'] ) ? $_GET['return_item'] : false;
1225
1226 // The nonce check should actually catch this already.
1227 if ( false === $table_id ) {
1228 TablePress::redirect( array( 'action' => $return, 'message' => 'error_copy', 'table_id' => $return_item ) );
1229 }
1230
1231 if ( ! current_user_can( 'tablepress_copy_table', $table_id ) ) {
1232 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1233 }
1234
1235 $copy_table_id = TablePress::$model_table->copy( $table_id );
1236 if ( is_wp_error( $copy_table_id ) ) {
1237 TablePress::redirect( array( 'action' => $return, 'message' => 'error_copy', 'table_id' => $return_item, 'error_details' => TablePress::get_wp_error_string( $copy_table_id ) ) );
1238 }
1239 $return_item = $copy_table_id;
1240
1241 /*
1242 * Slightly more complex redirect method, to account for sort, search, and pagination in the WP_List_Table on the List View,
1243 * but only if this action succeeds, to have everything fresh in the event of an error.
1244 */
1245 $sendback = wp_get_referer();
1246 if ( ! $sendback ) {
1247 $sendback = TablePress::url( array( 'action' => $return, 'message' => 'success_copy', 'table_id' => $return_item ) );
1248 } else {
1249 $sendback = remove_query_arg( array( 'action', 'message', 'table_id' ), $sendback );
1250 $sendback = add_query_arg( array( 'action' => $return, 'message' => 'success_copy', 'table_id' => $return_item ), $sendback );
1251 }
1252 wp_redirect( $sendback );
1253 exit;
1254 }
1255
1256 /**
1257 * Preview a table.
1258 *
1259 * @since 1.0.0
1260 */
1261 public function handle_get_action_preview_table(): void {
1262 $table_id = ( ! empty( $_GET['item'] ) ) ? $_GET['item'] : false;
1263 TablePress::check_nonce( 'preview_table', $table_id );
1264
1265 // Nonce check should actually catch this already.
1266 if ( false === $table_id ) {
1267 wp_die( __( 'The preview could not be loaded.', 'tablepress' ), __( 'Preview', 'tablepress' ) );
1268 }
1269
1270 if ( ! current_user_can( 'tablepress_preview_table', $table_id ) ) {
1271 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1272 }
1273
1274 // Load table, with table data, options, and visibility settings.
1275 $table = TablePress::$model_table->load( $table_id, true, true );
1276 if ( is_wp_error( $table ) ) {
1277 wp_die( __( 'The table could not be loaded.', 'tablepress' ), __( 'Preview', 'tablepress' ) );
1278 }
1279
1280 // Sanitize all table data to remove unsafe HTML from the preview output, if the user is not allowed to work with unfiltered HTML.
1281 if ( ! current_user_can( 'unfiltered_html' ) ) {
1282 $table = TablePress::$model_table->sanitize( $table );
1283 }
1284
1285 // Create a render class instance.
1286 $_render = TablePress::load_class( 'TablePress_Render', 'class-render.php', 'classes' );
1287 // Merge desired options with default render options (see TablePress_Controller_Frontend::shortcode_table()).
1288 $default_render_options = $_render->get_default_render_options();
1289 /** This filter is documented in controllers/controller-frontend.php */
1290 $default_render_options = apply_filters( 'tablepress_shortcode_table_default_shortcode_atts', $default_render_options );
1291 $render_options = shortcode_atts( $default_render_options, $table['options'] );
1292 /** This filter is documented in controllers/controller-frontend.php */
1293 $render_options = apply_filters( 'tablepress_shortcode_table_shortcode_atts', $render_options );
1294 $render_options['html_id'] = "tablepress-{$table['id']}";
1295 $_render->set_input( $table, $render_options );
1296 $view_data = array(
1297 'table_id' => $table_id,
1298 'head_html' => $_render->get_preview_css(),
1299 'body_html' => $_render->get_output( 'html' ),
1300 'site_uses_block_editor' => TablePress::site_uses_block_editor(),
1301 );
1302
1303 $custom_css = TablePress::$model_options->get( 'custom_css' );
1304 $use_custom_css = ( TablePress::$model_options->get( 'use_custom_css' ) && '' !== $custom_css );
1305 if ( $use_custom_css ) {
1306 $view_data['head_html'] .= "<style>\n{$custom_css}\n</style>\n";
1307 }
1308
1309 // Prepare, initialize, and render the view.
1310 $this->view = TablePress::load_view( 'preview_table', $view_data );
1311 $this->view->render();
1312 }
1313
1314 /**
1315 * Shows a list of tables in the Editor toolbar Thickbox (opened by TinyMCE or Quicktags button).
1316 *
1317 * @since 1.0.0
1318 */
1319 public function handle_get_action_editor_button_thickbox(): void {
1320 TablePress::check_nonce( 'editor_button_thickbox' );
1321
1322 if ( ! current_user_can( 'tablepress_list_tables' ) ) {
1323 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1324 }
1325
1326 $view_data = array(
1327 // Load all table IDs without priming the post meta cache, as table options/visibility are not needed.
1328 'table_ids' => TablePress::$model_table->load_all( false ),
1329 );
1330
1331 set_current_screen( 'tablepress_editor_button_thickbox' );
1332
1333 // Prepare, initialize, and render the view.
1334 $this->view = TablePress::load_view( 'editor_button_thickbox', $view_data );
1335 $this->view->render();
1336 }
1337
1338 /**
1339 * Uninstall TablePress, and delete all tables and options.
1340 *
1341 * @since 1.0.0
1342 */
1343 public function handle_get_action_uninstall_tablepress(): void {
1344 TablePress::check_nonce( 'uninstall_tablepress' );
1345
1346 $plugin = TABLEPRESS_BASENAME;
1347
1348 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 ) ) {
1349 wp_die( __( 'Sorry, you are not allowed to access this page.', 'default' ), 403 );
1350 }
1351
1352 // Deactivate TablePress for the site (but not for the network).
1353 deactivate_plugins( $plugin, false, false );
1354 update_option( 'recently_activated', array( $plugin => time() ) + (array) get_option( 'recently_activated', array() ) );
1355
1356 // Delete all tables, "Custom CSS" files, and options.
1357 TablePress::$model_table->delete_all();
1358 $tablepress_css = TablePress::load_class( 'TablePress_CSS', 'class-css.php', 'classes' );
1359 $css_files_deleted = $tablepress_css->delete_custom_css_files();
1360 TablePress::$model_options->remove_access_capabilities();
1361
1362 TablePress::$model_table->destroy();
1363 TablePress::$model_options->destroy();
1364
1365 $output = '<strong>' . __( 'TablePress was uninstalled successfully.', 'tablepress' ) . '</strong><br /><br />';
1366 $output .= __( 'All tables, data, and options were deleted.', 'tablepress' );
1367 if ( is_multisite() ) {
1368 $output .= ' ' . __( 'You may now ask the network admin to delete the plugin&#8217;s folder <code>tablepress</code> from the server, if no other site in the network uses it.', 'tablepress' );
1369 } else {
1370 $output .= ' ' . __( 'You may now manually delete the plugin&#8217;s folder <code>tablepress</code> from the <code>plugins</code> directory on your server or use the &#8220;Delete&#8221; link for TablePress on the WordPress &#8220;Plugins&#8221; page.', 'tablepress' );
1371 }
1372 if ( $css_files_deleted ) {
1373 $output .= ' ' . __( 'Your TablePress &#8220;Custom CSS&#8221; files have been deleted automatically.', 'tablepress' );
1374 } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found
1375 if ( is_multisite() ) {
1376 $output .= ' ' . __( 'Please also ask him to delete your TablePress &#8220;Custom CSS&#8221; files from the server.', 'tablepress' );
1377 } else {
1378 $output .= ' ' . __( 'You may now also delete your TablePress &#8220;Custom CSS&#8221; files in the <code>wp-content</code> folder.', 'tablepress' );
1379 }
1380 }
1381 $output .= "</p>\n<p>";
1382 if ( ! is_multisite() || is_super_admin() ) {
1383 $output .= '<a class="button" href="' . esc_url( admin_url( 'plugins.php' ) ) . '">' . __( 'Go to &#8220;Plugins&#8221; page', 'tablepress' ) . '</a> ';
1384 }
1385 $output .= '<a class="button" href="' . esc_url( admin_url( 'index.php' ) ) . '">' . __( 'Go to Dashboard', 'tablepress' ) . '</a>';
1386
1387 wp_die( $output, __( 'Uninstall TablePress', 'tablepress' ), array( 'response' => 200, 'back_link' => false ) );
1388 }
1389
1390 } // class TablePress_Admin_Controller
1391