PluginProbe
TablePress – Tables in WordPress made easy / 3.1.1
TablePress – Tables in WordPress made easy v3.1.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 / classes / class-tablepress.php

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

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