PluginProbe
TablePress – Tables in WordPress made easy / 3.2
TablePress – Tables in WordPress made easy v3.2
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 / classes / class-view.php

class-view.php in TablePress – Tables in WordPress made easy 3.2, at classes/class-view.php

574 lines 20.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * TablePress Base View with members and methods for all views
4 *
5 * @package TablePress
6 * @subpackage Views
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 * TablePress Base View class
16 *
17 * @package TablePress
18 * @subpackage Views
19 * @author Tobias Bäthge
20 * @since 1.0.0
21 */
22 abstract class TablePress_View {
23
24 /**
25 * Data for the view.
26 *
27 * @since 1.0.0
28 * @var array<string, mixed>
29 */
30 protected array $data = array();
31
32 /**
33 * Number of screen columns for post boxes.
34 *
35 * @since 1.0.0
36 */
37 protected int $screen_columns = 0;
38
39 /**
40 * User action for this screen.
41 *
42 * @since 1.0.0
43 */
44 protected string $action = '';
45
46 /**
47 * Instance of the Admin Page Helper Class, with necessary functions.
48 *
49 * @since 1.0.0
50 */
51 protected \TablePress_Admin_Page $admin_page;
52
53 /**
54 * List of text boxes (similar to post boxes, but just with text and without extra functionality).
55 *
56 * @since 1.0.0
57 * @var array<string, array<string, array<string, mixed>>>
58 */
59 protected array $textboxes = array();
60
61 /**
62 * List of messages that are to be displayed as boxes below the page title.
63 *
64 * @since 1.0.0
65 * @var string[]
66 */
67 protected array $header_messages = array();
68
69 /**
70 * Whether there are post boxes registered for this screen,
71 * is automatically set to true, when a meta box is added.
72 *
73 * @since 1.0.0
74 */
75 protected bool $has_meta_boxes = false;
76
77 /**
78 * List of WP feature pointers for this view.
79 *
80 * @since 1.0.0
81 * @var string[]
82 */
83 protected array $wp_pointers = array();
84
85 /**
86 * Initializes the View class, by setting the correct screen columns and adding help texts.
87 *
88 * @since 1.0.0
89 */
90 public function __construct() {
91 $screen = get_current_screen();
92 if ( 0 !== $this->screen_columns ) {
93 $screen->add_option( 'layout_columns', array( 'max' => $this->screen_columns ) ); // @phpstan-ignore method.nonObject
94 }
95 // Enable two column layout.
96 add_filter( "get_user_option_screen_layout_{$screen->id}", array( $this, 'set_current_screen_layout_columns' ) ); // @phpstan-ignore property.nonObject
97
98 /* translators: %1$s: URL to TablePress website, %2$s: URL to WordPress Plugin Directory */
99 $common_content = '<p>' . sprintf( __( 'More information about TablePress can be found on the <a href="%1$s">plugin website</a> or on its page in the <a href="%2$s">WordPress Plugin Directory</a>.', 'tablepress' ), 'https://tablepress.org/', 'https://wordpress.org/plugins/tablepress/' ) . '</p>';
100 /* translators: %s: URL to Documentation page */
101 $common_content .= '<p>' . sprintf( __( 'For technical information, please see the <a href="%s">Documentation</a>.', 'tablepress' ), 'https://tablepress.org/documentation/' ) . ' ';
102 /* translators: %s: URL to FAQ page */
103 $common_content .= sprintf( __( 'Common questions are answered in the <a href="%s">FAQ</a>.', 'tablepress' ), 'https://tablepress.org/faq/' ) . '</p>';
104
105 if ( tb_tp_fs()->is_free_plan() ) {
106 $common_content .= '<p>'
107 . sprintf( __( '<a href="%1$s">Support</a> is provided through the <a href="%2$s">WordPress Support Forums</a>.', 'tablepress' ), 'https://tablepress.org/support/', 'https://wordpress.org/tags/tablepress' )
108 . ' '
109 . sprintf( __( 'Before asking for support, please carefully read the <a href="%s">Frequently Asked Questions</a>, where you will find answers to the most common questions, and search through the forums.', 'tablepress' ), 'https://tablepress.org/faq/' )
110 . '</p>';
111 $common_content .= '<p><strong>' . sprintf( __( 'More great features for you and your site’s visitors and priority email support are available with a Premium license plan of TablePress. <a href="%s">Go check them out!</a>', 'tablepress' ), 'https://tablepress.org/premium/?utm_source=plugin&utm_medium=textlink&utm_content=help-tab' ) . '</strong></p>';
112 }
113
114 $screen->add_help_tab( array( // @phpstan-ignore method.nonObject
115 'id' => 'tablepress-help', // This should be unique for the screen.
116 'title' => __( 'TablePress Help', 'tablepress' ),
117 'content' => '<p>' . $this->help_tab_content() . '</p>' . $common_content,
118 ) );
119 // "Sidebar" in the help tab.
120 $screen->set_help_sidebar( // @phpstan-ignore method.nonObject
121 '<p><strong>' . __( 'For more information:', 'tablepress' ) . '</strong></p>'
122 . '<p><a href="https://tablepress.org/">TablePress Website</a></p>'
123 . '<p><a href="https://tablepress.org/faq/">TablePress FAQ</a></p>'
124 . '<p><a href="https://tablepress.org/documentation/">TablePress Documentation</a></p>'
125 . '<p><a href="https://tablepress.org/support/">TablePress Support</a></p>'
126 );
127 }
128
129 /**
130 * Changes the value of the user option "screen_layout_{$screen->id}" through a filter.
131 *
132 * @since 1.0.0
133 *
134 * @param int|false $result Current value of the user option.
135 * @return int New value for the user option.
136 */
137 public function set_current_screen_layout_columns( /* int|false */ $result ): int {
138 if ( false === $result ) {
139 // The user option does not yet exist.
140 $result = $this->screen_columns;
141 } elseif ( $result > $this->screen_columns ) {
142 // The value of the user option is bigger than what is possible on this screen (e.g. because the number of columns was reduced in an update).
143 $result = $this->screen_columns;
144 }
145 return $result;
146 }
147
148 /**
149 * Sets up the view with data and do things that are necessary for all views.
150 *
151 * @since 1.0.0
152 *
153 * @param string $action Action for this view.
154 * @param array<string, mixed> $data Data for this view.
155 */
156 public function setup( /* string */ $action, array $data ) /* : void */ {
157 // Don't use type hints (except array $data) in method declaration, as the method is extended in some TablePress Extensions which are no longer updated.
158
159 $this->action = $action;
160 $this->data = $data;
161
162 // Set page title.
163 $GLOBALS['title'] = sprintf( __( '%1$s &lsaquo; %2$s', 'tablepress' ), $this->data['view_actions'][ $this->action ]['page_title'], 'TablePress' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
164
165 // Admin page helpers, like script/style loading, could be moved to view.
166 $this->admin_page = TablePress::load_class( 'TablePress_Admin_Page', 'class-admin-page-helper.php', 'classes' );
167 $this->admin_page->enqueue_style( 'common', array( 'wp-components' ) );
168 // RTL styles for the admin interface.
169 if ( is_rtl() ) {
170 $this->admin_page->enqueue_style( 'common-rtl', array( 'tablepress-common' ) );
171 }
172 $this->admin_page->enqueue_script( 'common', array( 'jquery-core', 'postbox' ) );
173
174 $this->admin_page->add_admin_footer_text();
175
176 // Initialize WP feature pointers for TablePress.
177 $this->_init_wp_pointers();
178
179 // Necessary fields for all views.
180 $this->add_text_box( 'default_nonce_fields', array( $this, 'default_nonce_fields' ), 'header', false );
181 $this->add_text_box( 'action_nonce_field', array( $this, 'action_nonce_field' ), 'header', false );
182 $this->add_text_box( 'action_field', array( $this, 'action_field' ), 'header', false );
183 }
184
185 /**
186 * Registers a header message for the view.
187 *
188 * @since 1.0.0
189 *
190 * @param string $text Text for the header message.
191 * @param string $css_class Optional. Additional CSS class for the header message.
192 * @param string $title Optional. Text for the header title.
193 */
194 protected function add_header_message( string $text, string $css_class = 'is-success', string $title = '' ): void {
195 if ( ! str_contains( $css_class, 'not-dismissible' ) ) {
196 $css_class .= ' is-dismissible';
197 }
198 if ( '' !== $title ) {
199 $title = "<h3>{$title}</h3>";
200 }
201 // Wrap the message text in HTML <p> tags if it does not already start with one (potentially with attributes), indicating custom message HTML.
202 if ( '' !== $text && ! str_starts_with( $text, '<p' ) ) {
203 $text = "<p>{$text}</p>";
204 }
205 $this->header_messages[] = "<div class=\"notice components-notice {$css_class}\"><div class=\"components-notice__content\">{$title}{$text}</div></div>\n";
206 }
207
208 /**
209 * Processes header action messages, i.e. check if a message should be added to the page.
210 *
211 * @since 1.0.0
212 *
213 * @param array<string, string> $action_messages Action messages for the screen.
214 */
215 protected function process_action_messages( array $action_messages ): void {
216 if ( $this->data['message'] && isset( $action_messages[ $this->data['message'] ] ) ) {
217 $class = ( str_starts_with( $this->data['message'], 'error' ) ) ? 'is-error' : 'is-success';
218
219 if ( '' !== $this->data['error_details'] ) {
220 $this->data['error_details'] = '</p><p>' . sprintf( __( 'Error code: %s', 'tablepress' ), '<code>' . esc_html( $this->data['error_details'] ) . '</code>' );
221 }
222
223 $this->add_header_message( "<strong>{$action_messages[ $this->data['message'] ]}</strong>{$this->data['error_details']}", $class );
224 }
225 }
226
227 /**
228 * Registers a text box for the view.
229 *
230 * @since 1.0.0
231 *
232 * @param string $id Unique HTML ID for the text box container (only visible with $wrap = true).
233 * @param callable $callback Callback that prints the contents of the text box.
234 * @param string $context Optional. Context/position of the text box (normal, side, additional, header, submit).
235 * @param bool $wrap Whether the content of the text box shall be wrapped in a <div> container.
236 */
237 protected function add_text_box( string $id, callable $callback, string $context = 'normal', bool $wrap = false ): void {
238 if ( ! isset( $this->textboxes[ $context ] ) ) {
239 $this->textboxes[ $context ] = array();
240 }
241
242 $long_id = "tablepress_{$this->action}-{$id}";
243 $this->textboxes[ $context ][ $id ] = array(
244 'id' => $long_id,
245 'callback' => $callback,
246 'context' => $context,
247 'wrap' => $wrap,
248 );
249 }
250
251 /**
252 * Registers a post meta box for the view, that is drag/droppable with WordPress functionality.
253 *
254 * @since 1.0.0
255 *
256 * @param string $id Unique ID for the meta box.
257 * @param string $title Title for the meta box.
258 * @param callable $callback Callback that prints the contents of the post meta box.
259 * @param 'normal'|'side'|'additional' $context Optional. Context/position of the post meta box (normal, side, additional).
260 * @param 'core'|'default'|'high'|'low' $priority Optional. Order of the post meta box for the $context position (high, default, low).
261 * @param mixed[]|null $callback_args Optional. Additional data for the callback function (e.g. useful when in different class).
262 */
263 protected function add_meta_box( string $id, string $title, callable $callback, string $context = 'normal', string $priority = 'default', ?array $callback_args = null ): void {
264 $this->has_meta_boxes = true;
265 add_meta_box( "tablepress_{$this->action}-{$id}", $title, $callback, null, $context, $priority, $callback_args );
266 }
267
268 /**
269 * Renders all text boxes for the given context.
270 *
271 * @since 1.0.0
272 *
273 * @param string $context Context (normal, side, additional, header, submit) for which registered text boxes shall be rendered.
274 */
275 protected function do_text_boxes( string $context ): void {
276 if ( empty( $this->textboxes[ $context ] ) ) {
277 return;
278 }
279
280 foreach ( $this->textboxes[ $context ] as $box ) {
281 if ( $box['wrap'] ) {
282 echo "<div id=\"{$box['id']}\" class=\"textbox\">\n";
283 }
284 call_user_func( $box['callback'], $this->data, $box );
285 if ( $box['wrap'] ) {
286 echo "</div>\n";
287 }
288 }
289 }
290
291 /**
292 * Renders all post meta boxes for the given context, if there are post meta boxes.
293 *
294 * @since 1.0.0
295 *
296 * @param string $context Context (normal, side, additional) for which registered post meta boxes shall be rendered.
297 */
298 protected function do_meta_boxes( string $context ): void {
299 if ( $this->has_meta_boxes ) {
300 do_meta_boxes( get_current_screen(), $context, $this->data ); // @phpstan-ignore argument.type
301 }
302 }
303
304 /**
305 * Prints hidden fields with nonces for post meta box AJAX handling, if there are post meta boxes on the screen.
306 *
307 * The check is possible as this function is executed after post meta boxes have to be registered.
308 *
309 * @since 1.0.0
310 *
311 * @param array<string, mixed> $data Data for this screen.
312 * @param array<string, mixed> $box Information about the text box.
313 */
314 protected function default_nonce_fields( array $data, array $box ): void {
315 if ( ! $this->has_meta_boxes ) {
316 return;
317 }
318 wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
319 echo "\n";
320 wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
321 echo "\n";
322 }
323
324 /**
325 * Prints hidden field with a nonce for the screen's action, to be transmitted in HTTP requests.
326 *
327 * @since 1.0.0
328 *
329 * @param array<string, mixed> $data Data for this screen.
330 * @param array<string, mixed> $box Information about the text box.
331 */
332 protected function action_nonce_field( array $data, array $box ): void {
333 wp_nonce_field( TablePress::nonce( $this->action ) );
334 echo "\n";
335 }
336
337 /**
338 * Prints hidden field with the screen action.
339 *
340 * @since 1.0.0
341 *
342 * @param array<string, mixed> $data Data for this screen.
343 * @param array<string, mixed> $box Information about the text box.
344 */
345 protected function action_field( array $data, array $box ): void {
346 echo "<input type=\"hidden\" name=\"action\" value=\"tablepress_{$this->action}\">\n";
347 }
348
349 /**
350 * Renders the current view.
351 *
352 * @since 1.0.0
353 */
354 public function render(): void {
355 ?>
356 <div id="tablepress-page" class="wrap">
357 <?php
358 $this->print_nav_tab_menu();
359 ?>
360 <div id="tablepress-body">
361 <hr class="wp-header-end">
362 <?php
363 // Print all header messages.
364 foreach ( $this->header_messages as $message ) {
365 echo $message;
366 }
367 // "Import" screen has file upload.
368 $enctype = ( 'import' === $this->action ) ? ' enctype="multipart/form-data"' : '';
369 ?>
370 <form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post"<?php echo $enctype; ?> id="tablepress-page-form">
371 <?php
372 $this->do_text_boxes( 'header' );
373 $hide_if_no_js = ( in_array( $this->action, array( 'export', 'import' ), true ) ) ? ' class="hide-if-no-js"' : '';
374 ?>
375 <div id="poststuff"<?php echo $hide_if_no_js; ?>>
376 <div id="post-body" class="metabox-holder columns-<?php echo ( isset( $GLOBALS['screen_layout_columns'] ) && ( 2 === $GLOBALS['screen_layout_columns'] ) ) ? '2' : '1'; ?>">
377 <div id="postbox-container-2" class="postbox-container">
378 <?php
379 $this->do_text_boxes( 'normal' );
380 $this->do_meta_boxes( 'normal' );
381
382 $this->do_text_boxes( 'additional' );
383 $this->do_meta_boxes( 'additional' );
384
385 // Print all submit buttons.
386 $this->do_text_boxes( 'submit' );
387 ?>
388 </div>
389 <div id="postbox-container-1" class="postbox-container">
390 <?php
391 // Print all boxes in the sidebar.
392 $this->do_text_boxes( 'side' );
393 $this->do_meta_boxes( 'side' );
394 ?>
395 </div>
396 </div>
397 <br class="clear">
398 </div>
399 </form>
400 </div>
401 </div>
402 <?php
403 }
404
405 /**
406 * Renders the navigation menu with links to the possible actions, highlighting the current one.
407 *
408 * @since 1.0.0
409 */
410 protected function print_nav_tab_menu(): void {
411 $name = __( 'TablePress', 'tablepress' );
412 $filename = 'admin/img/tablepress.svg';
413 ?>
414 <div id="tablepress-header" class="header">
415 <h1 class="name">
416 <img src="<?php echo plugins_url( $filename, TABLEPRESS__FILE__ ); ?>" alt="<?php esc_attr_e( 'TablePress plugin logo', 'tablepress' ); ?>">
417 <span class="screen-reader-text"><?php echo $name; ?></span>
418 </h1>
419 <?php if ( ! TABLEPRESS_IS_PLAYGROUND_PREVIEW && tb_tp_fs()->is_free_plan() ) : ?>
420 <div class="buttons">
421 <a href="<?php echo esc_url( tb_tp_fs()->pricing_url( WP_FS__PERIOD_ANNUALLY, false ) ); ?>" class="tablepress-button">
422 <span><?php _e( 'Upgrade to Premium', 'tablepress' ); ?></span>
423 <span class="dashicons dashicons-arrow-right-alt"></span>
424 </a>
425 </div>
426 <?php endif; ?>
427 </div>
428 <nav id="tablepress-nav">
429 <ul class="nav-menu">
430 <?php
431 foreach ( $this->data['view_actions'] as $action => $entry ) {
432 if ( '' === $entry['nav_tab_title'] ) {
433 continue;
434 }
435 if ( ! current_user_can( $entry['required_cap'] ) ) {
436 continue;
437 }
438
439 $url = esc_url( TablePress::url( array( 'action' => $action ) ) );
440 $active = ( $action === $this->action ) ? ' active' : '';
441 $separator = ( 'export' === $action ) ? ' separator' : ''; // Make the "Export" entry a separator, for some spacing.
442 echo "<li class=\"nav-item\"><a id=\"tablepress-nav-item-{$action}\" class=\"nav-link{$active}{$separator}\" href=\"{$url}\">{$entry['nav_tab_title']}</a></li>";
443 }
444 ?>
445 </ul>
446 </nav>
447 <?php
448 }
449
450 /**
451 * Prints a notification about JavaScript not being activated in the browser.
452 *
453 * @since 2.0.0
454 *
455 * @param array<string, mixed> $data Data for this screen.
456 * @param array<string, mixed> $box Information about the text box.
457 */
458 public function textbox_no_javascript( array $data, array $box ): void {
459 ?>
460 <div class="notice components-notice is-error hide-if-js">
461 <div class="components-notice__content">
462 <h3><em>
463 <?php _e( 'Attention: Unfortunately, there is a problem!', 'tablepress' ); ?>
464 </em></h3>
465 <p style="font-size:14px">
466 <strong><?php _e( 'This screen requires JavaScript. Please enable JavaScript in your browser settings.', 'tablepress' ); ?></strong><br>
467 <?php _e( 'For help, please follow <a href="https://www.enable-javascript.com/">the instructions on how to enable JavaScript in your browser</a>.', 'tablepress' ); ?>
468 </p>
469 <p>
470 <?php echo '<a href="' . esc_url( TablePress::url( array( 'action' => 'list' ) ) ) . '">' . __( 'Back to the List of Tables', 'tablepress' ) . '</a>'; ?>
471 </p>
472 </div>
473 </div>
474 <?php
475 }
476
477 /**
478 * Prints a submit button (only done when function is used as a callback for a text box).
479 *
480 * This method is soft-deprecated. It's no longer used in TablePress, but e.g. in the "TablePress Debug Extension".
481 *
482 * @since 1.0.0
483 *
484 * @param array<string, mixed> $data Data for this screen.
485 * @param array<string, mixed> $box Information about the text box.
486 */
487 protected function textbox_submit_button( array $data, array $box ): void {
488 ?>
489 <p class="submit"><input type="submit" class="components-button is-primary button-save-changes" value="<?php esc_attr_e( 'Save Changes', 'tablepress' ); ?>"></p>
490 <?php
491 }
492
493 /**
494 * Returns a safe JSON representation of a variable for printing inside of JavaScript code.
495 *
496 * @since 2.0.0
497 *
498 * @param mixed $data Variable to convert to JSON.
499 * @return string Safe JSON representation of a variable for printing inside of JavaScript code.
500 */
501 public function convert_to_json_parse_output( /* string|array|bool|int|float|null */ $data ): string {
502 $json = wp_json_encode( $data, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES );
503 if ( false === $json ) {
504 // JSON encoding failed, return an error object. Use a prefixed "_error" key to avoid conflicts with intentionally added "error" keys.
505 $json = '{ "_error": "The data could not be encoded to JSON!" }';
506 }
507 // Print the JSON data inside a `JSON.parse()` call in JS for speed gains, with necessary escaping of `\` and `'`.
508 $json = str_replace( array( '\\', "'" ), array( '\\\\', "\'" ), $json );
509 return "JSON.parse( '{$json}' )";
510 }
511
512 /**
513 * Prints JavaScript variables for the screen.
514 *
515 * @since 3.1.0
516 *
517 * @param string $variable Name of the JavaScript variable.
518 * @param array<string, mixed> $data Information about the text box.
519 */
520 protected function print_script_data_json( string $variable, array $data ): void {
521 echo "<script>\n";
522 echo "window.tp = window.tp || {};\n";
523 echo "tp.{$variable} = {\n";
524 foreach ( $data as $key => $value ) {
525 $value = $this->convert_to_json_parse_output( $value );
526 echo "\t{$key}: {$value},\n";
527 }
528 echo "};\n";
529 echo "</script>\n";
530 }
531
532 /**
533 * Returns the content for the help tab for this screen.
534 *
535 * Has to be implemented for every view that is visible in the WP Dashboard!
536 *
537 * @since 1.0.0
538 *
539 * @return string Help tab content for the view.
540 */
541 protected function help_tab_content(): string {
542 // Has to be implemented for every view that is visible in the WP Dashboard!
543 return '';
544 }
545
546 /**
547 * Initializes the WP feature pointers for TablePress.
548 *
549 * @since 1.0.0
550 */
551 protected function _init_wp_pointers(): void {
552 // Check if there are WP pointers for this view.
553 if ( empty( $this->wp_pointers ) ) {
554 return;
555 }
556
557 // Get dismissed pointers.
558 $dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
559
560 $pointers_on_page = false;
561 foreach ( array_diff( $this->wp_pointers, $dismissed ) as $pointer ) {
562 // Bind pointer print function.
563 add_action( "admin_footer-{$GLOBALS['hook_suffix']}", array( $this, 'wp_pointer_' . $pointer ) ); // @phpstan-ignore argument.type
564 $pointers_on_page = true;
565 }
566
567 if ( $pointers_on_page ) {
568 wp_enqueue_style( 'wp-pointer' );
569 wp_enqueue_script( 'wp-pointer' );
570 }
571 }
572
573 } // class TablePress_View
574