PluginProbe
TablePress – Tables in WordPress made easy / 2.4.1
TablePress – Tables in WordPress made easy v2.4.1
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.4.1, at controllers/controller-admin.php

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