PluginProbe
TablePress – Tables in WordPress made easy / trunk
TablePress – Tables in WordPress made easy vtrunk
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-tablepress.php

class-tablepress.php in TablePress – Tables in WordPress made easy trunk, at classes/class-tablepress.php

1,029 lines 38.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * TablePress Class
4 *
5 * @package TablePress
6 * @author Tobias Bäthge
7 * @since 1.0.0
8 */
9
10 // Prohibit direct script loading.
11 defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );
12
13 /**
14 * TablePress class
15 *
16 * @package TablePress
17 * @author Tobias Bäthge
18 * @since 1.0.0
19 */
20 abstract class TablePress {
21
22 /**
23 * TablePress version.
24 *
25 * Increases whenever a new plugin version is released.
26 *
27 * @since 1.0.0
28 * @const string
29 */
30 public const version = '3.3.4'; // phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
31
32 /**
33 * TablePress internal plugin version ("options scheme" version).
34 *
35 * Increases whenever the scheme for the plugin options changes, or on a plugin update.
36 *
37 * @since 1.0.0
38 * @const int
39 */
40 public const db_version = 131; // phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
41
42 /**
43 * TablePress "table scheme" (data format structure) version.
44 *
45 * Increases whenever the scheme for a $table changes,
46 * used to be able to update plugin options and table scheme independently.
47 *
48 * @since 1.0.0
49 * @const int
50 */
51 public const table_scheme_version = 3; // phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
52
53 /**
54 * Instance of the Options Model.
55 *
56 * @since 1.3.0
57 */
58 public static \TablePress_Options_Model $model_options;
59
60 /**
61 * Instance of the Table Model.
62 *
63 * @since 1.3.0
64 */
65 public static \TablePress_Table_Model $model_table;
66
67 /**
68 * Instance of the controller.
69 *
70 * @since 1.0.0
71 */
72 public static \TablePress_Frontend_Controller $controller;
73
74 /**
75 * Name of the Shortcode to show a TablePress table.
76 *
77 * Should only be modified through the filter hook 'tablepress_table_shortcode'.
78 *
79 * @since 1.0.0
80 * @var non-empty-string
81 */
82 public static string $shortcode = 'table';
83
84 /**
85 * Name of the Shortcode to show extra information of a TablePress table.
86 *
87 * Should only be modified through the filter hook 'tablepress_table_info_shortcode'.
88 *
89 * @since 1.0.0
90 * @var non-empty-string
91 */
92 public static string $shortcode_info = 'table-info';
93
94 /**
95 * List of TablePress premium modules.
96 *
97 * @since 2.1.0
98 * @var array<string, array<string, mixed>> $modules Array with module slugs as keys and module data as values.
99 */
100 public static array $modules = array();
101
102 /**
103 * Start-up TablePress (run on WordPress "init") and load the controller for the current state.
104 *
105 * @since 1.0.0
106 */
107 public static function run(): void {
108 /**
109 * Fires before TablePress is loaded.
110 *
111 * The `tablepress_loaded` action hook might be a better choice in most situations, as TablePress options will then be available.
112 *
113 * @since 1.0.0
114 */
115 do_action( 'tablepress_run' );
116
117 /**
118 * Filters the string that is used as the [table] Shortcode.
119 *
120 * @since 1.0.0
121 *
122 * @param non-empty-string $shortcode The [table] Shortcode string.
123 */
124 self::$shortcode = apply_filters( 'tablepress_table_shortcode', self::$shortcode );
125 /**
126 * Filters the string that is used as the [table-info] Shortcode.
127 *
128 * @since 1.0.0
129 *
130 * @param non-empty-string $shortcode_info The [table-info] Shortcode string.
131 */
132 self::$shortcode_info = apply_filters( 'tablepress_table_info_shortcode', self::$shortcode_info );
133
134 // Load modals for table and options, to be accessible from everywhere via `TablePress::$model_options` and `TablePress::$model_table`.
135 self::$model_options = self::load_model( 'options' );
136 self::$model_table = self::load_model( 'table' );
137
138 // Exit early, i.e. before a controller is loaded, if TablePress functionality is likely not needed.
139 $exit_early = false;
140 if ( ( isset( $_SERVER['SCRIPT_FILENAME'] ) && 'wp-login.php' === basename( $_SERVER['SCRIPT_FILENAME'] ) ) // Detect the WordPress Login screen.
141 || ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
142 || wp_doing_cron() ) {
143 $exit_early = true;
144 }
145 /**
146 * Filters whether TablePress should exit early, e.g. during wp-login.php, XML-RPC, and WP-Cron requests.
147 *
148 * @since 2.0.0
149 *
150 * @param bool $exit_early Whether TablePress should exit early.
151 */
152 if ( apply_filters( 'tablepress_exit_early', $exit_early ) ) {
153 return;
154 }
155
156 if ( is_admin() ) {
157 $controller = 'admin';
158 if ( wp_doing_ajax() ) {
159 $controller = 'admin_ajax';
160 }
161 self::load_controller( $controller );
162 }
163 // Load the frontend controller in all scenarios, so that Shortcode render functions are always available.
164 self::$controller = self::load_controller( 'frontend' );
165
166 // Add filters and actions for the integration into the WP WXR exporter and importer.
167 add_action( 'wp_import_insert_post', array( TablePress::$model_table, 'add_table_id_on_wp_import' ), 10, 4 ); // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
168 add_filter( 'wp_import_post_meta', array( TablePress::$model_table, 'prevent_table_id_post_meta_import_on_wp_import' ), 10, 3 ); // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
169 add_filter( 'wxr_export_skip_postmeta', array( TablePress::$model_table, 'add_table_id_to_wp_export' ), 10, 3 ); // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
170
171 /**
172 * Fires after TablePress is loaded.
173 *
174 * The `tablepress_run` action hook can be used if code has to run before TablePress is loaded.
175 *
176 * @since 2.0.0
177 */
178 do_action( 'tablepress_loaded' );
179 }
180
181 /**
182 * Load a file with require_once(), after running it through a filter.
183 *
184 * @since 1.0.0
185 *
186 * @param string $file Name of the PHP file.
187 * @param string $folder Name of the folder with the file.
188 */
189 public static function load_file( string $file, string $folder ): void {
190 $full_path = TABLEPRESS_ABSPATH . $folder . '/' . $file;
191 /**
192 * Filters the full path of a file that shall be loaded.
193 *
194 * @since 1.0.0
195 *
196 * @param string $full_path Full path of the file that shall be loaded.
197 * @param string $file File name of the file that shall be loaded.
198 * @param string $folder Folder name of the file that shall be loaded.
199 */
200 $full_path = apply_filters( 'tablepress_load_file_full_path', $full_path, $file, $folder );
201 if ( $full_path ) {
202 require_once $full_path;
203 }
204 }
205
206 /**
207 * Create a new instance of the $class_name, which is stored in $file in the $folder subfolder
208 * of the plugin's directory.
209 *
210 * @since 1.0.0
211 *
212 * @param string $class_name Name of the class.
213 * @param string $file Name of the PHP file with the class.
214 * @param string $folder Name of the folder with $class_name's $file.
215 * @param mixed[]|string|null $params Optional. Parameters that are passed to the constructor of $class_name.
216 * @return object Initialized instance of the class.
217 */
218 public static function load_class( string $class_name, string $file, string $folder, /* ?array|string */ $params = null ): object {
219 /**
220 * Filters name of the class that shall be loaded.
221 *
222 * @since 1.0.0
223 *
224 * @param string $class_name Name of the class that shall be loaded.
225 */
226 $class_name = apply_filters( 'tablepress_load_class_name', $class_name );
227 if ( ! class_exists( $class_name, false ) ) {
228 self::load_file( $file, $folder );
229 }
230 $the_class = new $class_name( $params );
231 return $the_class;
232 }
233
234 /**
235 * Create a new instance of the $model, which is stored in the "models" subfolder.
236 *
237 * @since 1.0.0
238 *
239 * @param string $model Name of the model.
240 * @return object Instance of the initialized model.
241 */
242 public static function load_model( string $model ): object {
243 // Model Base Class.
244 self::load_file( 'class-model.php', 'classes' );
245 // Make first letter uppercase for a better looking naming pattern.
246 $ucmodel = ucfirst( $model );
247 $the_model = self::load_class( "TablePress_{$ucmodel}_Model", "model-{$model}.php", 'models' );
248 return $the_model;
249 }
250
251 /**
252 * Create a new instance of the $view, which is stored in the "views" subfolder, and set it up with $data.
253 *
254 * @since 1.0.0
255 *
256 * @param string $view Name of the view to load.
257 * @param array<string, mixed> $data Optional. Parameters/PHP variables that shall be available to the view.
258 * @return object Instance of the initialized view, already set up, just needs to be rendered.
259 */
260 public static function load_view( string $view, array $data = array() ): object {
261 // View Base Class.
262 self::load_file( 'class-view.php', 'classes' );
263 // Make first letter uppercase for a better looking naming pattern.
264 $ucview = ucfirst( $view );
265 $the_view = self::load_class( "TablePress_{$ucview}_View", "view-{$view}.php", 'views' );
266 $the_view->setup( $view, $data );
267 return $the_view;
268 }
269
270 /**
271 * Create a new instance of the $controller, which is stored in the "controllers" subfolder.
272 *
273 * @since 1.0.0
274 *
275 * @param string $controller Name of the controller.
276 * @return object Instance of the initialized controller.
277 */
278 public static function load_controller( string $controller ): object {
279 // Controller Base Class.
280 self::load_file( 'class-controller.php', 'classes' );
281 // Make first letter uppercase for a better looking naming pattern.
282 $uccontroller = ucfirst( $controller );
283 $the_controller = self::load_class( "TablePress_{$uccontroller}_Controller", "controller-{$controller}.php", 'controllers' );
284 return $the_controller;
285 }
286
287 /**
288 * Generate the complete nonce string, from the nonce base, the action and an item, e.g. tablepress_delete_table_3.
289 *
290 * @since 1.0.0
291 *
292 * @param string $action Action for which the nonce is needed.
293 * @param string|false $item Optional. Item for which the action will be performed, like "table". false if no item should be used in the nonce.
294 * @return string The resulting nonce string.
295 */
296 public static function nonce( string $action, /* string|false */ $item = false ): string {
297 $nonce = "tablepress_{$action}";
298 if ( $item ) {
299 $nonce .= "_{$item}";
300 }
301 return $nonce;
302 }
303
304 /**
305 * Check whether a nonce string is valid.
306 *
307 * @since 1.0.0
308 *
309 * @param string $action Action for which the nonce should be checked.
310 * @param string|false $item Optional. Item for which the action should be performed, like "table". false if no item should be used in the nonce.
311 * @param string $query_arg Optional. Name of the nonce query string argument in $_POST.
312 * @param bool $ajax Whether the nonce comes from an AJAX request.
313 */
314 public static function check_nonce( string $action, /* string|false */ $item = false, string $query_arg = '_wpnonce', bool $ajax = false ): void {
315 $nonce_action = self::nonce( $action, $item );
316 if ( $ajax ) {
317 check_ajax_referer( $nonce_action, $query_arg );
318 } else {
319 check_admin_referer( $nonce_action, $query_arg );
320 }
321 }
322
323 /**
324 * Calculate the column index (number) of a column header string (example: A is 1, AA is 27, ...).
325 *
326 * For the opposite, @see number_to_letter().
327 *
328 * @since 1.0.0
329 *
330 * @param string $column Column string.
331 * @return int Column number, 1-based.
332 */
333 public static function letter_to_number( string $column ): int {
334 $column = (string) preg_replace( '/[^A-Za-z]/', '', $column );
335 $column = strtoupper( $column );
336 $count = strlen( $column );
337 $number = 0;
338 for ( $i = 0; $i < $count; $i++ ) {
339 $number += ( ord( $column[ $count - 1 - $i ] ) - 64 ) * 26 ** $i;
340 }
341 return $number;
342 }
343
344 /**
345 * "Calculate" the column header string of a column index (example: 2 is B, AB is 28, ...).
346 *
347 * For the opposite, @see letter_to_number().
348 *
349 * @since 1.0.0
350 *
351 * @param int $number Column number, 1-based.
352 * @return string Column string.
353 */
354 public static function number_to_letter( int $number ): string {
355 $column = '';
356 while ( $number > 0 ) {
357 $column = chr( 65 + ( ( $number - 1 ) % 26 ) ) . $column;
358 $number = intdiv( $number - 1, 26 );
359 }
360 return $column;
361 }
362
363 /**
364 * Get a nice looking date and time string from the mySQL format of datetime strings for output.
365 *
366 * @since 1.0.0
367 *
368 * @param string $datetime_string DateTime string, often in mySQL format..
369 * @param string $separator_or_format Optional. Separator between date and time, or format string.
370 * @return string Nice looking string with the date and time.
371 */
372 public static function format_datetime( string $datetime_string, string $separator_or_format = ' ' ): string {
373 $timezone = wp_timezone();
374 $datetime = date_create( $datetime_string, $timezone );
375 if ( false === $datetime ) {
376 return $datetime_string;
377 }
378 $timestamp = $datetime->getTimestamp();
379
380 switch ( $separator_or_format ) {
381 case ' ':
382 case '<br />':
383 case '<br/>':
384 case '<br>':
385 $date = wp_date( get_option( 'date_format' ), $timestamp, $timezone );
386 $time = wp_date( get_option( 'time_format' ), $timestamp, $timezone );
387 $output = "{$date}{$separator_or_format}{$time}";
388 break;
389 default:
390 $output = (string) wp_date( $separator_or_format, $timestamp, $timezone );
391 break;
392 }
393
394 return $output;
395 }
396
397 /**
398 * Get the name from a WP user ID (used to store information on last editor of a table).
399 *
400 * @since 1.0.0
401 *
402 * @param int $user_id WP user ID.
403 * @return string Nickname of the WP user with the $user_id.
404 */
405 public static function get_user_display_name( int $user_id ): string {
406 $user = get_userdata( $user_id );
407 /* translators: %s: Label for unknown user */
408 return $user->display_name ?? sprintf( '<em>%s</em>', __( 'unknown', 'tablepress' ) );
409 }
410
411 /**
412 * Sanitizes a CSS class to ensure it only contains valid characters.
413 *
414 * Strips the string down to A-Z, a-z, 0-9, :, _, -.
415 * This is an extension to WP's `sanitize_html_class()`, to also allow `:` which are used in some CSS frameworks.
416 *
417 * @since 1.11.0
418 *
419 * @param string $css_class The CSS class name to be sanitized.
420 * @return string The sanitized CSS class.
421 */
422 public static function sanitize_css_class( string $css_class ): string {
423 // Strip out any %-encoded octets.
424 $sanitized_css_class = (string) preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $css_class );
425 // Limit to A-Z, a-z, 0-9, ':', '_', and '-'.
426 $sanitized_css_class = (string) preg_replace( '/[^A-Za-z0-9:_-]/', '', $sanitized_css_class );
427 return $sanitized_css_class;
428 }
429
430 /**
431 * Extracts the top-level keys from a JavaScript object string.
432 *
433 * This function is used to extract the keys of the "Custom Commands" JavaScript object string, to check for overrides.
434 * It covers most cases, like normal object properties with and without quotes, shorthand properties, and shorthand methods,
435 * and also ignores single-line and multi-line comments.
436 * It does not cover all possible JavaScript syntax (like template literals, special characters, ...),
437 * but should be sufficient for the use case.
438 *
439 * @since 3.0.0
440 *
441 * @param string $js_object_string A JavaScript object as a string.
442 * @return string[] Array of top-level keys of the object.
443 */
444 public static function extract_keys_from_js_object_string( string $js_object_string ): array {
445 $object_keys = array();
446 $length = strlen( $js_object_string );
447 $depth = 0;
448 $key_expected = true;
449 $in_quotes = false;
450 $quote_char = '';
451 $in_function_declaration = false;
452 $in_single_line_comment = false;
453 $in_multi_line_comment = false;
454 $object_key = '';
455
456 for ( $i = 0; $i < $length; $i++ ) {
457 $char = $js_object_string[ $i ];
458
459 // Skip parsing single-line comments.
460 if ( $in_single_line_comment ) {
461 if ( "\n" === $char ) {
462 $in_single_line_comment = false;
463 }
464 continue;
465 } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found
466 if ( '/' === $char && $i + 1 < $length && '/' === $js_object_string[ $i + 1 ] ) {
467 $in_single_line_comment = true;
468 ++$i; // Skip the second '/'.
469 continue;
470 }
471 }
472
473 // Skip parsing multi-line comments.
474 if ( $in_multi_line_comment ) {
475 if ( '*' === $char && $i + 1 < $length && '/' === $js_object_string[ $i + 1 ] ) {
476 $in_multi_line_comment = false;
477 ++$i; // Skip the '/' that ends the multi-line comment.
478 }
479 continue;
480 } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found
481 if ( '/' === $char && $i + 1 < $length && '*' === $js_object_string[ $i + 1 ] ) {
482 $in_multi_line_comment = true;
483 ++$i; // Skip the '*'.
484 continue;
485 }
486 }
487
488 // Skip parsing while inside a quoted string.
489 if ( $in_quotes ) {
490 if ( $quote_char === $char ) {
491 $in_quotes = false;
492 }
493 continue;
494 } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found
495 if ( '"' === $char || "'" === $char ) {
496 $in_quotes = true;
497 $quote_char = $char;
498 continue;
499 }
500 }
501
502 /*
503 * Skip parsing while inside a `function abc( ... )` declaration string.
504 * The `$key_expected` check limits search the "function" string to object values.
505 * The check for the plain `f` reduces expensive `substr()` calls.
506 */
507 if ( ! $key_expected ) {
508 if ( $in_function_declaration ) {
509 if ( ')' === $char ) {
510 $in_function_declaration = false;
511 }
512 continue;
513 } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found
514 if ( 'f' === $char && 'function' === substr( $js_object_string, $i, 8 ) ) {
515 $in_function_declaration = true;
516 $i += 7; // Skip the rest of the "function" string.
517 continue;
518 }
519 }
520 }
521
522 // Handle object depth, so that most parsing can be limited to the top level.
523 if ( '{' === $char || '[' === $char ) {
524 ++$depth;
525 }
526
527 // Extract only keys at the top level.
528 if ( 1 === $depth ) {
529 if ( $key_expected ) {
530 if ( ':' === $char ) {
531 // Check for normal keys, with value after :.
532
533 // Go backwards to find the start of the key.
534 $j = $i - 1;
535 while ( $j >= 0 && preg_match( '/\s/', $js_object_string[ $j ] ) ) {
536 --$j;
537 }
538 $key_end = $j; // Position of the last character of the key (potentially with quote).
539 if ( '"' === $js_object_string[ $j ] || "'" === $js_object_string[ $j ] ) {
540 // Quoted key.
541 $quote_char = $js_object_string[ $j ];
542 --$j;
543 while ( $j >= 0 && $quote_char !== $js_object_string[ $j ] ) {
544 --$j;
545 }
546 $key_start = $j + 1;
547 } else {
548 // Unquoted key.
549 while ( $j >= 0 && preg_match( '/[\w]/', $js_object_string[ $j ] ) ) {
550 --$j;
551 }
552 $key_start = $j + 1;
553 }
554 $object_key = substr( $js_object_string, $key_start, $key_end - $key_start + 1 );
555 $object_key = trim( $object_key, "\"'" );
556 if ( '' !== $object_key && ! in_array( $object_key, $object_keys, true ) ) {
557 $object_keys[] = $object_key;
558 }
559 $key_expected = false;
560 } elseif ( ( ',' === $char || '}' === $char ) ) { // The `}` case is for the last key.
561 // Check for shorthand properties (which must be unquoted).
562
563 // Go backwards to find the start of the shorthand key.
564 $j = $i - 1;
565 while ( $j >= 0 && preg_match( '/\s/', $js_object_string[ $j ] ) ) {
566 --$j;
567 }
568 $key_end = $j; // Position of the last character of the key (without a quote).
569 while ( $j >= 0 && preg_match( '/[\w]/', $js_object_string[ $j ] ) ) {
570 --$j;
571 }
572 $key_start = $j + 1;
573 $object_key = substr( $js_object_string, $key_start, $key_end - $key_start + 1 );
574 if ( '' !== $object_key && ! in_array( $object_key, $object_keys, true ) ) {
575 $object_keys[] = $object_key;
576 }
577 } elseif ( '(' === $char ) {
578 // Detect shorthand method definitions.
579
580 // Go back to find the start of the method name.
581 $j = $i - 1;
582 while ( $j >= 0 && preg_match( '/\s/', $js_object_string[ $j ] ) ) {
583 --$j;
584 }
585 $key_end = $j;
586 while ( $j >= 0 && preg_match( '/[\w]/', $js_object_string[ $j ] ) ) {
587 --$j;
588 }
589 $key_start = $j + 1;
590 $object_key = substr( $js_object_string, $key_start, $key_end - $key_start + 1 );
591 if ( '' !== $object_key && ! in_array( $object_key, $object_keys, true ) ) {
592 $object_keys[] = $object_key;
593 }
594 }
595 }
596
597 // Reset the "key expected" flag after a comma or closing brace.
598 if ( ',' === $char || '}' === $char ) {
599 $key_expected = true;
600 }
601 }
602
603 // Handle object depth.
604 if ( '}' === $char || ']' === $char ) {
605 --$depth;
606 }
607 }
608
609 return $object_keys;
610 }
611
612 /**
613 * Converts old DataTables 1.x CSS classes and parameters to the DataTables 2 variants.
614 *
615 * This function is used to modernize "Custom CSS" and "Custom Commands" for compatibility with DataTables 2.x.
616 * It probably does not catch all possible cases.
617 *
618 * @since 3.0.0
619 *
620 * @param string $code Code that contains DataTables 1.x CSS classes and parameters.
621 * @return string Updated code with DataTables 2.x CSS classes and parameters.
622 */
623 public static function convert_datatables_api_data( string $code ): string {
624 /**
625 * Mappings for DataTables 1.x CSS class or parameter to DataTables 2 variants.
626 * As this array is used in `strtr()`, it's pre-sorted for descending string length of the array keys.
627 */
628 static $datatables_api_data_mappings = array(
629 // CSS classes.
630 '.tablepress thead .sorting:hover' => '.tablepress thead .dt-orderable-asc:hover,.tablepress thead .dt-orderable-desc:hover',
631 '.tablepress thead .sorting_desc' => '.tablepress thead .dt-ordering-desc',
632 '.dataTables_filter label input' => '.dt-container .dt-search input',
633 '.tablepress thead .sorting_asc' => '.tablepress thead .dt-ordering-asc',
634 '.dataTables_scrollFootInner' => '.dt-scroll-footInner',
635 '.dataTables_scrollHeadInner' => '.dt-scroll-headInner',
636 '.tablepress thead .sorting' => '.tablepress thead .dt-orderable-asc,.tablepress thead .dt-orderable-desc',
637 '.dataTables_processing' => '.dt-processing',
638 '.dataTables_scrollBody' => '.dt-scroll-body',
639 '.dataTables_scrollFoot' => '.dt-scroll-foot',
640 '.dataTables_scrollHead' => '.dt-scroll-head',
641 '.dataTables_paginate' => '.dt-paging',
642 '.tablepress .even td' => '.tablepress>:where(tbody.row-striping)>:nth-child(odd)>*',
643 '.dataTables_wrapper' => '.dt-container',
644 '.tablepress .odd td' => '.tablepress>:where(tbody.row-striping)>:nth-child(even)>*',
645 '.dataTables_filter' => '.dt-search',
646 '.dataTables_length' => '.dt-length',
647 '.dataTables_scroll' => '.dt-scroll',
648 '.dataTables_empty' => '.dt-empty',
649 '.dataTables_info' => '.dt-info',
650 '.paginate_button' => '.dt-paging-button',
651 // DataTables API functions.
652 '$.fn.dataTable.' => 'DataTable.',
653 );
654 $code = strtr( $code, $datatables_api_data_mappings );
655
656 // HTML ID mappings, which were removed.
657 if ( str_contains( $code, '#tablepress-' ) ) {
658 $code = (string) preg_replace(
659 array(
660 '/#tablepress-([A-Za-z1-9_-]|[A-Za-z0-9_-]{2,})_paginate/',
661 '/#tablepress-([A-Za-z1-9_-]|[A-Za-z0-9_-]{2,})_filter/',
662 '/#tablepress-([A-Za-z1-9_-]|[A-Za-z0-9_-]{2,})_length/',
663 '/#tablepress-([A-Za-z1-9_-]|[A-Za-z0-9_-]{2,})_info/',
664 ),
665 array(
666 '#tablepress-$1_wrapper .dt-paging',
667 '#tablepress-$1_wrapper .dt-search',
668 '#tablepress-$1_wrapper .dt-length',
669 '#tablepress-$1_wrapper .dt-info',
670 ),
671 $code,
672 );
673 }
674
675 return $code;
676 }
677
678 /**
679 * Retrieves all information of a WP_Error object as a string.
680 *
681 * @since 1.4.0
682 *
683 * @param WP_Error $wp_error A WP_Error object.
684 * @return string All error codes, messages, and data of the WP_Error.
685 */
686 public static function get_wp_error_string( WP_Error $wp_error ): string {
687 $error_strings = array();
688 $error_codes = $wp_error->get_error_codes();
689 // Reverse order to get latest errors first.
690 $error_codes = array_reverse( $error_codes );
691 foreach ( $error_codes as $error_code ) {
692 $error_strings[ $error_code ] = $error_code;
693 $error_messages = $wp_error->get_error_messages( $error_code );
694 $error_messages = implode( ', ', $error_messages );
695 if ( ! empty( $error_messages ) ) {
696 $error_strings[ $error_code ] .= " ({$error_messages})";
697 }
698 $error_data = $wp_error->get_error_data( $error_code );
699 if ( is_string( $error_data ) ) {
700 $error_strings[ $error_code ] .= " [{$error_data}]";
701 } elseif ( is_array( $error_data ) ) {
702 foreach ( $error_data as $key => $value ) {
703 $error_data[ $key ] = "{$key}: {$value}";
704 }
705 $error_data = implode( ', ', $error_data );
706 $error_strings[ $error_code ] .= " [{$error_data}]";
707 }
708 }
709 return implode( ";\n", $error_strings );
710 }
711
712 /**
713 * Generate the action URL, to be used as a link within the plugin (e.g. in the submenu navigation or List of Tables).
714 *
715 * @since 1.0.0
716 *
717 * @param array<string, mixed> $params Optional. Parameters to form the query string of the URL.
718 * @param bool $add_nonce Optional. Whether the URL shall be nonced by WordPress.
719 * @param string $target Optional. Target File, e.g. "admin-post.php" for POST requests.
720 * @return string The URL for the given parameters (already run through esc_url() with $add_nonce === true!).
721 */
722 public static function url( array $params = array(), bool $add_nonce = false, string $target = '' ): string {
723 // Default action is "list", if no action given.
724 if ( ! isset( $params['action'] ) ) {
725 $params['action'] = 'list';
726 }
727 $nonce_action = $params['action'];
728
729 if ( '' !== $target ) {
730 $params['action'] = "tablepress_{$params['action']}";
731 } else {
732 $params['page'] = 'tablepress';
733 // Top-level parent page needs special treatment for better action strings.
734 if ( self::$controller->is_top_level_page ) {
735 $target = 'admin.php';
736 if ( ! in_array( $params['action'], array( 'list', 'edit' ), true ) ) {
737 $params['page'] = "tablepress_{$params['action']}";
738 }
739 if ( ! in_array( $params['action'], array( 'edit' ), true ) ) {
740 $params['action'] = false;
741 }
742 } else {
743 $target = self::$controller->parent_page;
744 }
745 }
746
747 // $default_params also determines the order of the values in the query string.
748 $default_params = array(
749 'page' => false,
750 'action' => false,
751 'item' => false,
752 );
753 $params = array_merge( $default_params, $params );
754
755 if ( isset( $params['error_details'] ) ) {
756 $params['error_details'] = rawurlencode( $params['error_details'] );
757 }
758
759 $url = add_query_arg( $params, admin_url( $target ) );
760 if ( $add_nonce ) {
761 $url = wp_nonce_url( $url, self::nonce( $nonce_action, $params['item'] ) ); // wp_nonce_url() does esc_html().
762 }
763 return $url;
764 }
765
766 /**
767 * Create a redirect URL from the $target_parameters and redirect the user.
768 *
769 * @since 1.0.0
770 *
771 * @param array<string, mixed> $params Optional. Parameters from which the target URL is constructed.
772 * @param bool $add_nonce Optional. Whether the URL shall be nonced by WordPress.
773 */
774 public static function redirect( array $params = array(), bool $add_nonce = false ): void {
775 $redirect = self::url( $params );
776 if ( $add_nonce ) {
777 if ( ! isset( $params['item'] ) ) {
778 $params['item'] = false;
779 }
780 // Don't use wp_nonce_url(), as that uses esc_html().
781 $redirect = add_query_arg( '_wpnonce', wp_create_nonce( self::nonce( $params['action'], $params['item'] ) ), $redirect );
782 }
783 wp_redirect( $redirect );
784 exit;
785 }
786
787 /**
788 * Determines the editor that the site uses, so that certain text and input fields referring to Shortcodes can be displayed or not.
789 *
790 * @since 3.1.0
791 *
792 * @return string The editor that the site uses, either "block", "elementor", or "other".
793 */
794 public static function site_used_editor(): string {
795 if ( is_plugin_active( 'elementor/elementor.php' ) ) {
796 return 'elementor';
797 }
798
799 // Checking for Elementor is not needed anymore in this condition.
800 $site_uses_block_editor = use_block_editor_for_post_type( 'post' )
801 && ! is_plugin_active( 'classic-editor/classic-editor.php' )
802 && ! is_plugin_active( 'classic-editor-addon/classic-editor-addon.php' )
803 && ! is_plugin_active( 'siteorigin-panels/siteorigin-panels.php' )
804 && ! is_plugin_active( 'beaver-builder-lite-version/fl-builder.php' );
805 /**
806 * Filters the outcome of the check whether the site uses the block editor.
807 *
808 * This can be used when certain conditions (e.g. new site builders) are not (yet) accounted for.
809 *
810 * @since 2.0.1
811 *
812 * @param bool $site_uses_block_editor True if the site uses the block editor, false otherwise.
813 */
814 $site_uses_block_editor = (bool) apply_filters( 'tablepress_site_uses_block_editor', $site_uses_block_editor );
815 if ( $site_uses_block_editor ) {
816 return 'block';
817 }
818
819 return 'other';
820 }
821
822 /**
823 * Adds the (translated) names and descriptions to the list of feature modules.
824 *
825 * @since 3.3.0
826 */
827 public static function load_modules_data(): void {
828 // Prevent repeated execution of expensive translation functions via a static variable.
829 static $modules_initialized = false;
830 if ( $modules_initialized ) {
831 return;
832 }
833 $modules_initialized = true;
834
835 $modules = array(
836 'advanced-access-rights' => array(
837 'name' => __( 'Advanced Access Rights', 'tablepress' ),
838 'description' => __( 'Restrict access to individual tables for individual users.', 'tablepress' ),
839 ),
840 'automatic-periodic-table-import' => array(
841 'name' => __( 'Automatic Periodic Table Import', 'tablepress' ),
842 'description' => __( 'Periodically update tables from a configured import source.', 'tablepress' ),
843 ),
844 'automatic-table-export' => array(
845 'name' => __( 'Automatic Table Export', 'tablepress' ),
846 'description' => __( 'Export and save tables to files on the server after they were modified.', 'tablepress' ),
847 ),
848 'cell-highlighting' => array(
849 'name' => __( 'Cell Highlighting', 'tablepress' ),
850 'description' => __( 'Add CSS classes to cells for highlighting based on their content.', 'tablepress' ),
851 ),
852 'column-order' => array(
853 'name' => __( 'Column Order', 'tablepress' ),
854 'description' => __( 'Order the columns in different ways when a table is shown.', 'tablepress' ),
855 ),
856 'datatables-advanced-loading' => array(
857 'name' => __( 'Advanced Loading', 'tablepress' ),
858 'description' => __( 'Load the table data from a JSON array for faster loading.', 'tablepress' ),
859 ),
860 'datatables-alphabetsearch' => array(
861 'name' => __( 'Alphabet Search', 'tablepress' ),
862 'description' => __( 'Show Alphabet buttons above the table to filter rows by their first letter.', 'tablepress' ),
863 ),
864 'datatables-auto-filter' => array(
865 'name' => __( 'Automatic Filter', 'tablepress' ),
866 'description' => __( 'Pre-filter a table when it is shown.', 'tablepress' ),
867 ),
868 'datatables-buttons' => array(
869 'name' => __( 'User Action Buttons', 'tablepress' ),
870 'description' => __( 'Add buttons for downloading, copying, printing, and changing column visibility of tables.', 'tablepress' ),
871 ),
872 'datatables-columnfilterwidgets' => array(
873 'name' => __( 'Column Filter Dropdowns', 'tablepress' ),
874 'description' => __( 'Add a search dropdown for each column above the table.', 'tablepress' ),
875 ),
876 'datatables-column-filter' => array(
877 'name' => __( 'Individual Column Filtering', 'tablepress' ),
878 'description' => __( 'Add a search field or filter dropdown for each column to a table head or foot row.', 'tablepress' ),
879 ),
880 'datatables-counter-column' => array(
881 'name' => __( 'Index Column', 'tablepress' ),
882 'description' => __( 'Make the first column an index or counter column with the row position.', 'tablepress' ),
883 ),
884 'datatables-fixedheader-fixedcolumns' => array(
885 'name' => __( 'Fixed Rows and Columns', 'tablepress' ),
886 'description' => __( 'Fix the header and footer row and the first and last column when scrolling the table.', 'tablepress' ),
887 ),
888 'datatables-layout' => array(
889 'name' => __( 'Table Layout', 'tablepress' ),
890 'description' => __( 'Customize the layout and position of features around a table.', 'tablepress' ),
891 ),
892 'datatables-fuzzysearch' => array(
893 'name' => __( 'Fuzzy Search', 'tablepress' ),
894 'description' => __( 'Let the search account for spelling mistakes and typos and find similar matches.', 'tablepress' ),
895 ),
896 'datatables-inverted-filter' => array(
897 'name' => __( 'Inverted Filtering', 'tablepress' ),
898 'description' => __( 'Turn the filtering into a search and hide the table if no search term is entered.', 'tablepress' ),
899 ),
900 'datatables-pagination' => array(
901 'name' => __( 'Advanced Pagination Settings', 'tablepress' ),
902 'description' => __( 'Customize the pagination settings of the table.', 'tablepress' ),
903 ),
904 'datatables-rowgroup' => array(
905 'name' => __( 'Row Grouping', 'tablepress' ),
906 'description' => __( 'Group table rows by a common keyword, category, or title.', 'tablepress' ),
907 ),
908 'datatables-searchbuilder' => array(
909 'name' => __( 'Custom Search Builder', 'tablepress' ),
910 'description' => __( 'Show a search builder interface for filtering from groups and using conditions.', 'tablepress' ),
911 ),
912 'datatables-searchhighlight' => array(
913 'name' => __( 'Search Highlighting', 'tablepress' ),
914 'description' => __( 'Highlight found search terms in the table.', 'tablepress' ),
915 ),
916 'datatables-searchpanes' => array(
917 'name' => __( 'Search Panes', 'tablepress' ),
918 'description' => __( 'Show panes for filtering the columns.', 'tablepress' ),
919 ),
920 'datatables-serverside-processing' => array(
921 'name' => __( 'Server-side Processing', 'tablepress' ),
922 'description' => __( 'Process sorting, filtering, and pagination on the server for faster loading of large tables.', 'tablepress' ),
923 ),
924 'default-style-customizer' => array(
925 'name' => __( 'Default Style Customizer', 'tablepress' ),
926 'description' => __( 'Change the default styling of your tables in the visual style customizer.', 'tablepress' ),
927 ),
928 'email-notifications' => array(
929 'name' => __( 'Email Notifications', 'tablepress' ),
930 'description' => __( 'Get email notifications when certain actions are performed on tables.', 'tablepress' ),
931 ),
932 'responsive-tables' => array(
933 'name' => __( 'Responsive Tables', 'tablepress' ),
934 'description' => __( 'Make your tables look good on different screen sizes.', 'tablepress' ),
935 ),
936 'rest-api' => array(
937 'name' => __( 'REST API', 'tablepress' ),
938 'description' => __( 'Read table data via the WordPress REST API, e.g. in external apps.', 'tablepress' ),
939 ),
940 'row-filtering' => array(
941 'name' => __( 'Row Filtering', 'tablepress' ),
942 'description' => __( 'Show only table rows that contain defined keywords.', 'tablepress' ),
943 ),
944 'row-highlighting' => array(
945 'name' => __( 'Row Highlighting', 'tablepress' ),
946 'description' => __( 'Add CSS classes to rows for highlighting based on their content.', 'tablepress' ),
947 ),
948 'row-order' => array(
949 'name' => __( 'Row Order', 'tablepress' ),
950 'description' => __( 'Order the rows in different ways when a table is shown.', 'tablepress' ),
951 ),
952 );
953
954 // Append translated module names and descriptions to potentially existing module meta data.
955 self::$modules = array_merge_recursive( self::$modules, $modules );
956 }
957
958 /**
959 * Enqueues a CSS file, possibly with dependencies.
960 *
961 * @since 3.3.0
962 *
963 * @param string $name Name of the CSS file, without extension.
964 * @param string[] $dependencies Optional. List of names of CSS stylesheets that this stylesheet depends on, and which need to be included before this one.
965 * @param string $path Optional. Path to the CSS file.
966 */
967 public static function enqueue_style( string $name, array $dependencies = array(), string $path = 'admin/css/build/' ): void {
968 $css_file = "{$path}{$name}.css";
969 $css_url = plugins_url( $css_file, TABLEPRESS__FILE__ );
970 wp_enqueue_style( "tablepress-{$name}", $css_url, $dependencies, self::version );
971 }
972
973 /**
974 * Enqueues a JavaScript file, possibly with dependencies and extra information.
975 *
976 * @since 3.3.0
977 *
978 * @param string $name Name of the JS file, without extension.
979 * @param string[] $dependencies Optional. List of names of JS scripts that this script depends on, and which need to be included before this one.
980 * @param array<string, mixed> $script_data Optional. JS data that is printed to the page before the script is included. The array key will be used as the name, the value will be JSON encoded.
981 * @param string $path Optional. Path to the JS file.
982 */
983 public static function enqueue_script( string $name, array $dependencies = array(), array $script_data = array(), string $path = 'admin/js/build/' ): void {
984 $js_file = "{$path}{$name}.js";
985 $js_url = plugins_url( $js_file, TABLEPRESS__FILE__ );
986
987 $version = self::version;
988
989 // Load dependencies and version from the auto-generated asset PHP file.
990 $script_asset_path = TABLEPRESS_ABSPATH . "{$path}{$name}.asset.php";
991 if ( file_exists( $script_asset_path ) ) {
992 $script_asset = require $script_asset_path;
993 if ( isset( $script_asset['dependencies'] ) ) {
994 $dependencies = array_merge( $dependencies, $script_asset['dependencies'] );
995 }
996 if ( isset( $script_asset['version'] ) ) {
997 $version = $script_asset['version'];
998 }
999 }
1000
1001 /**
1002 * Filters the dependencies of a TablePress script file.
1003 *
1004 * @since 2.0.0
1005 *
1006 * @param string[] $dependencies List of the dependencies that the $name script relies on.
1007 * @param string $name Name of the JS script, without extension.
1008 */
1009 $dependencies = apply_filters( 'tablepress_admin_page_script_dependencies', $dependencies, $name );
1010
1011 $script_name = "tablepress-{$name}";
1012
1013 wp_enqueue_script( $script_name, $js_url, $dependencies, $version, array( 'in_footer' => true ) );
1014
1015 // Load JavaScript translation files, for all scripts that rely on `wp-i18n`.
1016 if ( in_array( 'wp-i18n', $dependencies, true ) ) {
1017 wp_set_script_translations( $script_name, 'tablepress' );
1018 }
1019
1020 if ( ! empty( $script_data ) ) {
1021 foreach ( $script_data as $var_name => $var_data ) {
1022 $var_data = wp_json_encode( $var_data, JSON_FORCE_OBJECT | JSON_HEX_TAG | JSON_UNESCAPED_SLASHES );
1023 wp_add_inline_script( $script_name, "const tablepress_{$var_name} = {$var_data};", 'before' );
1024 }
1025 }
1026 }
1027
1028 } // class TablePress
1029