PluginProbe
TablePress – Tables in WordPress made easy / 2.1.8
TablePress – Tables in WordPress made easy v2.1.8
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 / models / model-table.php

model-table.php in TablePress – Tables in WordPress made easy 2.1.8, at models/model-table.php

1,223 lines 39.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Table Model
4 *
5 * @package TablePress
6 * @subpackage Models
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 * Table Model class
16 *
17 * @package TablePress
18 * @subpackage Models
19 * @author Tobias Bäthge
20 * @since 1.0.0
21 */
22 class TablePress_Table_Model extends TablePress_Model {
23
24 /**
25 * Instance of the Post Type Model.
26 *
27 * @since 1.0.0
28 * @var TablePress_Post_Model
29 */
30 protected $model_post;
31
32 /**
33 * Name of the Post Meta Field for table options.
34 *
35 * @since 1.0.0
36 * @var string
37 */
38 protected $table_options_field_name = '_tablepress_table_options';
39
40 /**
41 * Name of the Post Meta Field for table visibility.
42 *
43 * @since 1.0.0
44 * @var string
45 */
46 protected $table_visibility_field_name = '_tablepress_table_visibility';
47
48 /**
49 * Default set of tables.
50 *
51 * @since 1.0.0
52 * @var array $args {
53 * @type int $last_id Last table ID that was given to a new table.
54 * @type array $table_post Connections between table ID and post ID (key: table ID, value: post ID).
55 * }
56 */
57 protected $default_tables = array(
58 'last_id' => 0,
59 'table_post' => array(),
60 );
61
62 /**
63 * Instance of WP_Option class for the list of tables.
64 *
65 * @since 1.0.0
66 * @var TablePress_WP_Option
67 */
68 protected $tables;
69
70 /**
71 * Init the Table model by instantiating a Post model and loading the list of tables option.
72 *
73 * @since 1.0.0
74 */
75 public function __construct() {
76 parent::__construct();
77 $this->model_post = TablePress::load_model( 'post' );
78
79 $params = array(
80 'option_name' => 'tablepress_tables',
81 'default_value' => $this->default_tables,
82 );
83 $this->tables = TablePress::load_class( 'TablePress_WP_Option', 'class-wp_option.php', 'classes', $params );
84 }
85
86 /**
87 * Get the tables option, which holds the connection between table ID and post ID.
88 *
89 * @since 1.0.0
90 *
91 * @return array Current set of tables.
92 */
93 public function _debug_get_tables() {
94 return $this->tables->get();
95 }
96
97 /**
98 * Update the tables option, which holds the connection between table ID and post ID.
99 *
100 * @since 1.0.0
101 *
102 * @param array $tables New set of tables.
103 */
104 public function _debug_update_tables( array $tables ) {
105 $this->tables->update( $tables );
106 }
107
108 /**
109 * Convert a table to a post, which can be stored in the database.
110 *
111 * @since 1.0.0
112 *
113 * @param array $table Table.
114 * @param int $post_id Post ID of an existing table, or -1 for a new table.
115 * @return array Post.
116 */
117 protected function _table_to_post( array $table, $post_id ) {
118 // Run filters on content in each cell and other fields.
119 $table = $this->filter_content( $table );
120
121 // Sanitize each cell, table name, and table description, if the user is not allowed to work with unfiltered HTML.
122 if ( ! current_user_can( 'unfiltered_html' ) ) {
123 $table = $this->sanitize( $table );
124 }
125
126 // New posts have a post ID of false in WordPress.
127 if ( -1 === $post_id ) {
128 $post_id = false;
129 }
130
131 $post = array(
132 'ID' => $post_id,
133 'post_title' => $table['name'],
134 'post_excerpt' => $table['description'],
135 'post_content' => wp_json_encode( $table['data'], TABLEPRESS_JSON_OPTIONS ),
136 'post_mime_type' => 'application/json',
137 );
138
139 return $post;
140 }
141
142 /**
143 * Convert a post (from the database) to a table.
144 *
145 * @since 1.0.0
146 *
147 * @param WP_Post $post Post.
148 * @param string $table_id Table ID.
149 * @param bool $load_data Whether the table data shall be loaded.
150 * @return array Table.
151 */
152 protected function _post_to_table( $post, $table_id, $load_data ) {
153 $table = array(
154 'id' => $table_id,
155 'name' => $post->post_title,
156 'description' => $post->post_excerpt,
157 'author' => $post->post_author,
158 // 'created' => $post->post_date,
159 'last_modified' => $post->post_modified,
160 );
161
162 if ( ! $load_data ) {
163 return $table;
164 }
165
166 $table['data'] = json_decode( $post->post_content, true );
167
168 // Check if JSON could be decoded.
169 if ( is_null( $table['data'] ) ) {
170 $table['data'] = array( array( "The internal data of table {$table_id} is corrupted." ) ); // Set a single cell as the cell content.
171 $table['is_corrupted'] = true;
172 $table['json_error'] = json_last_error_msg();
173 $table['description'] = "[ERROR] TABLE IS CORRUPTED (JSON error: {$table['json_error']})! DO NOT EDIT THIS TABLE NOW!\nInstead, please see https://tablepress.org/faq/corrupted-tables/ for instructions.\n-\n{$table['description']}";
174 } else {
175 // Specifically cast to an array again.
176 $table['data'] = (array) $table['data'];
177 }
178
179 return $table;
180 }
181
182 /**
183 * Load a table.
184 *
185 * @since 1.0.0
186 *
187 * @param string $table_id Table ID.
188 * @param bool $load_data Whether the table data shall be loaded.
189 * @param bool $load_options_visibility Whether the table options and table visibility shall be loaded.
190 * @return array|WP_Error Table as an array on success, WP_Error on error.
191 */
192 public function load( $table_id, $load_data = true, $load_options_visibility = true ) {
193 if ( empty( $table_id ) ) {
194 return new WP_Error( 'table_load_empty_table_id' );
195 }
196
197 $post_id = $this->_get_post_id( $table_id );
198 if ( false === $post_id ) {
199 return new WP_Error( 'table_load_no_post_id_for_table_id', '', $table_id );
200 }
201
202 $post = $this->model_post->get( $post_id );
203 if ( false === $post ) {
204 return new WP_Error( 'table_load_no_post_for_post_id', '', $post_id );
205 }
206
207 $table = $this->_post_to_table( $post, $table_id, $load_data );
208 if ( $load_options_visibility ) {
209 $table['options'] = $this->_get_table_options( $post_id );
210 $table['visibility'] = $this->_get_table_visibility( $post_id );
211 }
212 return $table;
213 }
214
215 /**
216 * Load the IDs of all tables that can be loaded from the database.
217 *
218 * @since 1.0.0
219 *
220 * @param bool $prime_meta_cache Optional. Whether the prime the post meta cache when loading the posts.
221 * @param bool $run_filter Optional. Whether to run a filter on the list of table IDs.
222 * @return array Array of table IDs.
223 */
224 public function load_all( $prime_meta_cache = true, $run_filter = true ) {
225 $table_post = $this->tables->get( 'table_post' );
226 if ( empty( $table_post ) ) {
227 return array();
228 }
229
230 // Load all table posts with one query, to prime the cache.
231 $this->model_post->load_posts( array_values( $table_post ), $prime_meta_cache );
232
233 // This loop now uses the WP cache.
234 $table_ids = array();
235 foreach ( $table_post as $table_id => $post_id ) {
236 $table_id = (string) $table_id;
237 // Load table without data and options to save memory.
238 $table = $this->load( $table_id, false, false );
239 // Skip tables that could not be loaded properly.
240 if ( ! is_wp_error( $table ) ) {
241 $table_ids[] = $table_id;
242 }
243 }
244
245 if ( $run_filter ) {
246 /**
247 * Filters all table IDs that are loaded.
248 *
249 * @since 1.4.0
250 *
251 * @param array $table_ids The table IDs that are loaded.
252 */
253 $table_ids = apply_filters( 'tablepress_load_all_tables', $table_ids );
254 }
255
256 return $table_ids;
257 }
258
259 /**
260 * Sanitize the table to remove undesired HTML code using KSES.
261 *
262 * @since 1.8.0
263 *
264 * @param array $table Table.
265 * @return array Sanitized table.
266 */
267 public function sanitize( array $table ) {
268 // Sanitize the table name and description.
269 $fields = array( 'name', 'description' );
270 foreach ( $fields as $field ) {
271 $table[ $field ] = wp_kses_post( $table[ $field ] );
272 }
273
274 // Sanitize each cell.
275 foreach ( $table['data'] as $row_idx => $row ) {
276 foreach ( $row as $column_idx => $cell_content ) {
277 $table['data'][ $row_idx ][ $column_idx ] = wp_kses_post( $cell_content ); // Equals wp_filter_post_kses(), but without the unncessary slashes handling.
278 }
279 }
280
281 return $table;
282 }
283
284 /**
285 * Filter/modify the content of table cells and other fields, e.g. for security hardening.
286 *
287 * This is similar to the `sanitize()` method, but executed for all users.
288 * In 1.10.0, adding `rel="noopener noreferrer"` to all HTML link elements like `<a target=` was added. See https://core.trac.wordpress.org/ticket/43187.
289 * Since 1.13.0, and on WP 5.6, only `rel="noopener"` is added. See https://core.trac.wordpress.org/ticket/49558.
290 *
291 * @since 1.10.0
292 *
293 * @param array $table Table.
294 * @return array Filtered/modified table.
295 */
296 public function filter_content( array $table ) {
297 /**
298 * Filters whether the contents of table cells and fields should be filtered/modified.
299 *
300 * @since 1.10.0
301 *
302 * @param bool $filter Whether to filter the content of table cells and other fields. Default true.
303 */
304 if ( ! apply_filters( 'tablepress_filter_table_cell_content', true ) ) {
305 return $table;
306 }
307
308 // Filter the table name and description.
309 $fields = array( 'name', 'description' );
310 foreach ( $fields as $field ) {
311 $table[ $field ] = wp_targeted_link_rel( $table[ $field ] );
312 }
313
314 foreach ( $table['data'] as $row_idx => $row ) {
315 foreach ( $row as $column_idx => $cell_content ) {
316 $table['data'][ $row_idx ][ $column_idx ] = wp_targeted_link_rel( $cell_content );
317 }
318 }
319
320 return $table;
321 }
322
323 /**
324 * Save a table.
325 *
326 * @since 1.0.0
327 *
328 * @param array $table Table (needs to have $table['id']!).
329 * @return string|WP_Error WP_Error on error, string table ID on success.
330 */
331 public function save( array $table ) {
332 if ( empty( $table['id'] ) ) {
333 return new WP_Error( 'table_save_empty_table_id' );
334 }
335
336 $post_id = $this->_get_post_id( $table['id'] );
337 if ( false === $post_id ) {
338 return new WP_Error( 'table_save_no_post_id_for_table_id', '', $table['id'] );
339 }
340
341 $post = $this->_table_to_post( $table, $post_id );
342 $new_post_id = $this->model_post->update( $post );
343 if ( is_wp_error( $new_post_id ) ) {
344 $error = new WP_Error( 'table_save_post_update', '', $post_id );
345 $error->merge_from( $new_post_id );
346 return $error;
347 }
348 if ( $post_id !== $new_post_id ) {
349 return new WP_Error( 'table_save_new_post_id_does_not_match', '', $new_post_id );
350 }
351
352 $options_saved = $this->_update_table_options( $new_post_id, $table['options'] );
353 if ( ! $options_saved ) {
354 return new WP_Error( 'table_save_update_table_options_failed', '', $new_post_id );
355 }
356
357 $visibility_saved = $this->_update_table_visibility( $new_post_id, $table['visibility'] );
358 if ( ! $visibility_saved ) {
359 return new WP_Error( 'table_save_update_table_visibility_failed', '', $new_post_id );
360 }
361
362 // At this point, post was successfully added.
363
364 // Invalidate table output caches that belong to this table.
365 $this->invalidate_table_output_cache( $table['id'] );
366 // Flush caching plugins' caches.
367 $this->_flush_caching_plugins_caches();
368
369 /**
370 * Fires after a table has been saved.
371 *
372 * @since 1.5.0
373 *
374 * @param string $table_id ID of the added table.
375 */
376 do_action( 'tablepress_event_saved_table', $table['id'] );
377
378 return $table['id'];
379 }
380
381 /**
382 * Add a new table.
383 *
384 * @since 1.0.0
385 *
386 * @param array $table Table ($table['id'] is not necessary).
387 * @param string $copy_or_add Optional. 'copy' if the table is copied, 'add' if it is a new table. Default 'add'.
388 * @return string|WP_Error WP_Error on error, string table ID of the new table on success.
389 */
390 public function add( array $table, $copy_or_add = 'add' ) {
391 $post_id = -1; // To insert table.
392 $post = $this->_table_to_post( $table, $post_id );
393 $new_post_id = $this->model_post->insert( $post );
394 if ( is_wp_error( $new_post_id ) ) {
395 $error = new WP_Error( 'table_add_post_insert', '' );
396 $error->merge_from( $new_post_id );
397 return $error;
398 }
399
400 $options_saved = $this->_add_table_options( $new_post_id, $table['options'] );
401 if ( ! $options_saved ) {
402 return new WP_Error( 'table_add_update_table_options_failed', '', $new_post_id );
403 }
404
405 $visibility_saved = $this->_add_table_visibility( $new_post_id, $table['visibility'] );
406 if ( ! $visibility_saved ) {
407 return new WP_Error( 'table_add_update_table_visibility_failed', '', $new_post_id );
408 }
409
410 // At this point, post was successfully added, now get an unused table ID.
411 $table_id = $this->_get_new_table_id();
412 $this->_update_post_id( $table_id, $new_post_id );
413
414 if ( 'add' === $copy_or_add ) {
415 /**
416 * Fires after a new table has been added.
417 *
418 * @since 1.1.0
419 *
420 * @param string $table_id ID of the added table.
421 */
422 do_action( 'tablepress_event_added_table', $table_id );
423 }
424
425 return $table_id;
426 }
427
428 /**
429 * Create a copy of a table and add it.
430 *
431 * @since 1.0.0
432 *
433 * @param string $table_id ID of the table to be copied.
434 * @return string|WP_Error WP_Error on error, string table ID of the new table on success.
435 */
436 public function copy( $table_id ) {
437 $table = $this->load( $table_id, true, true );
438 if ( is_wp_error( $table ) ) {
439 $error = new WP_Error( 'table_copy_table_load', '', $table_id );
440 $error->merge_from( $table );
441 return $error;
442 }
443
444 // Adjust name of copied table.
445 if ( '' === trim( $table['name'] ) ) {
446 $table['name'] = __( '(no name)', 'tablepress' );
447 }
448 $table['name'] = sprintf( __( 'Copy of %s', 'tablepress' ), $table['name'] );
449
450 // Merge this data into an empty table template.
451 $table = $this->prepare_table( $this->get_table_template(), $table, false );
452 if ( is_wp_error( $table ) ) {
453 $error = new WP_Error( 'table_copy_table_prepare', '', $table_id );
454 $error->merge_from( $table );
455 return $error;
456 }
457
458 // Add the copied table.
459 $new_table_id = $this->add( $table, 'copy' );
460 if ( is_wp_error( $new_table_id ) ) {
461 $error = new WP_Error( 'table_copy_table_add', '', $table_id );
462 $error->merge_from( $new_table_id );
463 return $error;
464 }
465
466 /**
467 * Fires after an existing table has been copied.
468 *
469 * @since 1.1.0
470 *
471 * @param string $new_table_id ID of the copy of the table.
472 * @param string $table_id ID of the existing table that is copied.
473 */
474 do_action( 'tablepress_event_copied_table', $new_table_id, $table_id );
475
476 return $new_table_id;
477 }
478
479 /**
480 * Delete a table (and its options).
481 *
482 * @since 1.0.0
483 *
484 * @param string $table_id ID of the table to be deleted.
485 * @return bool|WP_Error WP_Error on error, true on success.
486 */
487 public function delete( $table_id ) {
488 if ( ! $this->table_exists( $table_id ) ) {
489 return new WP_Error( 'table_delete_table_does_not_exist', '', $table_id );
490 }
491
492 $post_id = $this->_get_post_id( $table_id ); // No ! false check necessary, as this is covered by table_exists() check above.
493 $deleted = $this->model_post->delete( $post_id ); // Post Meta fields will be deleted automatically by that function.
494 if ( false === $deleted ) {
495 return new WP_Error( 'table_delete_post_could_not_be_deleted', '', $post_id );
496 }
497
498 // If post was deleted successfully, remove the table ID from the list of tables.
499 $this->_remove_post_id( $table_id );
500
501 // Invalidate table output caches that belong to this table.
502 $this->invalidate_table_output_cache( $table_id );
503 // Flush caching plugins' caches.
504 $this->_flush_caching_plugins_caches();
505
506 /**
507 * Fires after a table has been deleted.
508 *
509 * @since 1.1.0
510 *
511 * @param string $table_id ID of the deleted table.
512 */
513 do_action( 'tablepress_event_deleted_table', $table_id );
514
515 return true;
516 }
517
518 /**
519 * Delete all tables.
520 *
521 * @since 1.0.0
522 */
523 public function delete_all() {
524 $tables = $this->tables->get();
525 if ( empty( $tables['table_post'] ) ) {
526 return;
527 }
528
529 foreach ( $tables['table_post'] as $table_id => $post_id ) {
530 $table_id = (string) $table_id;
531 $this->model_post->delete( $post_id ); // Post Meta fields will be deleted automatically by that function.
532 unset( $tables['table_post'][ $table_id ] );
533 // Invalidate table output caches that belong to this table.
534 $this->invalidate_table_output_cache( $table_id );
535 }
536
537 $this->tables->update( $tables );
538 // Flush caching plugins' caches.
539 $this->_flush_caching_plugins_caches();
540
541 /**
542 * Fires after all tables have been deleted.
543 *
544 * @since 1.1.0
545 */
546 do_action( 'tablepress_event_deleted_all_tables' );
547 }
548
549 /**
550 * Check if a table ID exists in the list of tables (this does not guarantee that the post with the table data exists!).
551 *
552 * @since 1.0.0
553 *
554 * @param string $table_id Table ID.
555 * @return bool Whether the table ID exists.
556 */
557 public function table_exists( $table_id ) {
558 $table_post = $this->tables->get( 'table_post' );
559 return isset( $table_post[ $table_id ] );
560 }
561
562 /**
563 * Count the number of tables from either just the list, or by also counting the posts in the database.
564 *
565 * @since 1.0.0
566 *
567 * @param bool $single_value Optional. Whether to return just the number of tables from the list, or also count in the database.
568 * @return int|array Number of Tables (if $single_value), or array of Numbers from list/DB (if ! $single_value).
569 */
570 public function count_tables( $single_value = true ) {
571 $count_list = count( $this->tables->get( 'table_post' ) );
572 if ( $single_value ) {
573 return $count_list;
574 }
575
576 $count_db = $this->model_post->count_posts();
577 return array(
578 'list' => $count_list,
579 'db' => $count_db,
580 );
581 }
582
583 /**
584 * Delete all transients used for output caching of a table (e.g. when the table is updated or deleted).
585 *
586 * @since 1.0.0
587 * @since 1.8.0 Renamed from _invalidate_table_output_cache to invalidate_table_output_cache and made public.
588 *
589 * @param string $table_id Table ID.
590 */
591 public function invalidate_table_output_cache( $table_id ) {
592 $caches_list_transient_name = 'tablepress_c_' . md5( $table_id );
593 $caches_list = get_transient( $caches_list_transient_name );
594 if ( false !== $caches_list ) {
595 $caches_list = (array) json_decode( $caches_list, true );
596 foreach ( $caches_list as $cache_transient_name ) {
597 delete_transient( $cache_transient_name );
598 }
599 }
600 delete_transient( $caches_list_transient_name );
601 }
602
603 /**
604 * Flush the caches of common caching plugins.
605 *
606 * @since 1.0.0
607 */
608 public function _flush_caching_plugins_caches() {
609 /**
610 * Filters whether the caches of common caching plugins shall be flushed.
611 *
612 * @since 1.0.0
613 *
614 * @param bool $flush Whether caches of caching plugins shall be flushed. Default true.
615 */
616 if ( ! apply_filters( 'tablepress_flush_caching_plugins_caches', true ) ) {
617 return;
618 }
619
620 // Common cache flush callback.
621 $cache_flush_callbacks = array(
622 array( 'Breeze_PurgeCache', 'breeze_cache_flush' ), // Breeze.
623 array( 'comet_cache', 'clear' ), // Comet Cache.
624 'pantheon_wp_clear_edge_all', // Pantheon.
625 'sg_cachepress_purge_cache', // SG Optimizer.
626 array( 'Swift_Performance_Cache', 'clear_all_cache' ), // Swift Performance.
627 'w3tc_pgcache_flush', // W3 Total Cache.
628 array( 'WpeCommon', 'purge_memcached' ), // WP Engine.
629 array( 'WpeCommon', 'clear_maxcdn_cache' ), // WP Engine.
630 array( 'WpeCommon', 'purge_varnish_cache' ), // WP Engine.
631 'wpfc_clear_all_cache', // WP Fastest Cache.
632 'rocket_clean_domain', // WP Rocket.
633 'wp_cache_clear_cache', // WP Super Cache.
634 array( 'zencache', 'clear' ), // Zen Cache.
635 );
636 foreach ( $cache_flush_callbacks as $cache_flush_callback ) {
637 if ( is_callable( $cache_flush_callback ) ) {
638 call_user_func( $cache_flush_callback );
639 }
640 }
641
642 // Common cache flush hooks.
643 $cache_flush_hooks = array(
644 'ce_clear_cache', // Cache Enabler.
645 'cachify_flush_cache', // Cachify.
646 'autoptimize_action_cachepurged', // Hyper Cache.
647 );
648 foreach ( $cache_flush_hooks as $cache_flush_hook ) {
649 do_action( $cache_flush_hook );
650 }
651
652 // Kinsta.
653 if ( isset( $GLOBALS['kinsta_cache'] ) && ! empty( $GLOBALS['kinsta_cache']->kinsta_cache_purge ) && is_callable( array( $GLOBALS['kinsta_cache']->kinsta_cache_purge, 'purge_complete_caches' ) ) ) {
654 $GLOBALS['kinsta_cache']->kinsta_cache_purge->purge_complete_caches();
655 }
656 // LiteSpeed Cache.
657 if ( is_callable( array( 'LiteSpeed_Cache_Tags', 'add_purge_tag' ) ) ) {
658 LiteSpeed_Cache_Tags::add_purge_tag( '*' );
659 }
660 // Pagely.
661 if ( class_exists( 'PagelyCachePurge' ) ) {
662 $_pagely = new PagelyCachePurge();
663 if ( is_callable( array( $_pagely, 'purgeAll' ) ) ) {
664 $_pagely->purgeAll();
665 }
666 }
667 // Pressidum.
668 if ( is_callable( array( 'Ninukis_Plugin', 'get_instance' ) ) ) {
669 $_pressidum = Ninukis_Plugin::get_instance();
670 if ( is_callable( array( $_pressidum, 'purgeAllCaches' ) ) ) {
671 $_pressidum->purgeAllCaches();
672 }
673 }
674 // Savvii.
675 if ( defined( '\Savvii\CacheFlusherPlugin::NAME_DOMAINFLUSH_NOW' ) ) {
676 $_savvii = new \Savvii\CacheFlusherPlugin();
677 if ( is_callable( array( $_savvii, 'domainflush' ) ) ) {
678 $_savvii->domainflush();
679 }
680 }
681 // WP Fastest Cache.
682 if ( isset( $GLOBALS['wp_fastest_cache'] ) && is_callable( array( $GLOBALS['wp_fastest_cache'], 'deleteCache' ) ) ) {
683 $GLOBALS['wp_fastest_cache']->deleteCache( true );
684 }
685 // WP-Optimize.
686 if ( function_exists( 'WP_Optimize' ) ) {
687 WP_Optimize()->get_page_cache()->purge();
688 }
689 }
690
691 /**
692 * Get the post ID of a given table ID (if the table ID exists).
693 *
694 * @since 1.0.0
695 *
696 * @param string $table_id Table ID.
697 * @return int|false Post ID on success, false on error.
698 */
699 protected function _get_post_id( $table_id ) {
700 $table_post = $this->tables->get( 'table_post' );
701 if ( ! isset( $table_post[ $table_id ] ) ) {
702 return false;
703 }
704 return $table_post[ $table_id ];
705 }
706
707 /**
708 * Update/Add a post ID for a given table ID, and sort the list of tables by their key in natural sort order.
709 *
710 * @since 1.0.0
711 *
712 * @param string $table_id Table ID.
713 * @param int $post_id Post ID.
714 */
715 protected function _update_post_id( $table_id, $post_id ) {
716 $tables = $this->tables->get();
717 $tables['table_post'][ $table_id ] = $post_id;
718 uksort( $tables['table_post'], 'strnatcasecmp' );
719 $this->tables->update( $tables );
720 }
721
722 /**
723 * Remove a table ID/post ID connection from the list of tables.
724 *
725 * @since 1.0.0
726 *
727 * @param string $table_id Table ID.
728 */
729 protected function _remove_post_id( $table_id ) {
730 $tables = $this->tables->get();
731 unset( $tables['table_post'][ $table_id ] );
732 $this->tables->update( $tables );
733 }
734
735 /**
736 * Change the table ID of a table.
737 *
738 * @since 1.0.0
739 *
740 * @param string $old_id Old table ID.
741 * @param string $new_id New table ID.
742 * @return bool|WP_Error True on success, WP_Error on error.
743 */
744 public function change_table_id( $old_id, $new_id ) {
745 $post_id = $this->_get_post_id( $old_id );
746 if ( false === $post_id ) {
747 return new WP_Error( 'table_change_id_no_post_id_for_table_id', '', $old_id );
748 }
749
750 // Check new ID for correct format (string from letters, numbers, -, and _ only, except the '0' string).
751 if ( empty( $new_id ) || 0 !== preg_match( '/[^a-zA-Z0-9_-]/', $new_id ) ) {
752 return new WP_Error( 'table_change_id_new_id_is_invalid', '', $new_id );
753 }
754
755 if ( $this->table_exists( $new_id ) ) {
756 return new WP_Error( 'table_change_table_new_id_exists', '', $new_id );
757 }
758
759 $this->_update_post_id( $new_id, $post_id );
760 $this->_remove_post_id( $old_id );
761
762 /**
763 * Fires after the ID of a table has been changed.
764 *
765 * @since 1.1.0
766 *
767 * @param string $new_id New ID of the table.
768 * @param string $old_id Old ID of the table.
769 */
770 do_action( 'tablepress_event_changed_table_id', $new_id, $old_id );
771
772 return true;
773 }
774
775 /**
776 * Get an unused table ID (e.g. for a new table).
777 *
778 * @since 1.0.0
779 *
780 * @return string Unused table ID (e.g. for a new table).
781 */
782 protected function _get_new_table_id() {
783 $tables = $this->tables->get();
784 // Need to check new ID candidate in a loop, because a higher ID might already be in use, if a table ID was changed manually.
785 do {
786 ++$tables['last_id'];
787 $last_id_string = (string) $tables['last_id'];
788 } while ( $this->table_exists( $last_id_string ) );
789 $this->tables->update( $tables );
790 return $last_id_string;
791 }
792
793 /**
794 * Get the template for an empty table.
795 *
796 * Important: This scheme is versioned via TablePress::table_scheme_version; changes likely need a version update!
797 *
798 * @since 1.0.0
799 *
800 * @return array Empty table.
801 */
802 public function get_table_template() {
803 // Attention: Array keys have to be lowercase, to make it possible to match them with Shortcode attributes!
804 $table = array(
805 'id' => false,
806 'name' => '',
807 'description' => '',
808 'data' => array( array( '' ) ), // One empty cell.
809 'last_modified' => wp_date( 'Y-m-d H:i:s' ),
810 'author' => get_current_user_id(),
811 'options' => array(
812 'last_editor' => get_current_user_id(),
813 'table_head' => true,
814 'table_foot' => false,
815 'alternating_row_colors' => true,
816 'row_hover' => true,
817 'print_name' => false,
818 'print_name_position' => 'above',
819 'print_description' => false,
820 'print_description_position' => 'below',
821 'extra_css_classes' => '',
822 // DataTables JavaScript library.
823 'use_datatables' => true,
824 'datatables_sort' => true,
825 'datatables_filter' => true,
826 'datatables_paginate' => true,
827 'datatables_lengthchange' => true,
828 'datatables_paginate_entries' => 10,
829 'datatables_info' => true,
830 'datatables_scrollx' => false,
831 'datatables_custom_commands' => '',
832 ),
833 'visibility' => array(
834 'rows' => array( 1 ), // One visbile row.
835 'columns' => array( 1 ), // One visible column.
836 ),
837 );
838 /**
839 * Filters the default template/structure of an empty table.
840 *
841 * @since 1.0.0
842 *
843 * @param array $table Default template/structure of an empty table.
844 */
845 return apply_filters( 'tablepress_table_template', $table );
846 }
847
848 /**
849 * Combine two tables (e.g. an existing one with the updated data, or an empty one with new data).
850 *
851 * Performs consistency checks on data and visibility settings.
852 *
853 * @since 1.0.0
854 *
855 * @param array $table Table to merge into.
856 * @param array $new_table Table to merge.
857 * @param bool $table_size_check Optional. Whether to check the number of rows and columns (e.g. not necessary for added or copied tables).
858 * @return array|WP_Error Merged table on success, WP_Error on error.
859 */
860 public function prepare_table( array $table, array $new_table, $table_size_check = true ) {
861 // Table ID must be the same (if there was an ID already).
862 if ( false !== $table['id'] && $table['id'] !== $new_table['id'] ) {
863 return new WP_Error( 'table_prepare_no_id_match', '', $new_table['id'] );
864 }
865
866 // Name, description, and data array need to exist, data must not be empty, the others could be ''.
867 if ( ! isset( $new_table['name'], $new_table['description'] )
868 || empty( $new_table['data'] ) || empty( $new_table['data'][0] ) ) {
869 return new WP_Error( 'table_prepare_name_description_or_data_not_set' );
870 }
871
872 // Visibility needs to exist.
873 if ( ! isset( $new_table['visibility']['rows'], $new_table['visibility']['columns'] ) ) {
874 return new WP_Error( 'table_prepare_visibility_not_set' );
875 }
876 $new_table['visibility']['rows'] = array_map( 'intval', $new_table['visibility']['rows'] );
877 $new_table['visibility']['columns'] = array_map( 'intval', $new_table['visibility']['columns'] );
878
879 // Check dimensions of table data array (not done for newly added, copied, or imported tables).
880 if ( $table_size_check ) {
881 if ( ! isset( $new_table['number']['rows'], $new_table['number']['columns'] ) ) {
882 return new WP_Error( 'table_prepare_size_check_numbers_not_set' );
883 }
884 // Table data needs to be ok, and have the correct number of rows and columns.
885 $new_table['number']['rows'] = (int) $new_table['number']['rows'];
886 $new_table['number']['columns'] = (int) $new_table['number']['columns'];
887 if ( 0 === $new_table['number']['rows']
888 || 0 === $new_table['number']['columns']
889 || count( $new_table['data'] ) !== $new_table['number']['rows']
890 || count( $new_table['data'][0] ) !== $new_table['number']['columns'] ) {
891 return new WP_Error( 'table_prepare_size_check_numbers_dont_match' );
892 }
893 // Visibility also needs to have correct dimensions.
894 if ( count( $new_table['visibility']['rows'] ) !== $new_table['number']['rows']
895 || count( $new_table['visibility']['columns'] ) !== $new_table['number']['columns'] ) {
896 return new WP_Error( 'table_prepare_size_check_visibility_doesnt_match' );
897 }
898 }
899
900 // All checks were successful, replace original values with new ones.
901
902 // $table['id'] is either false (and remains false) or already equal to $new_table['id'].
903 $table['new_id'] = isset( $new_table['new_id'] ) ? $new_table['new_id'] : $table['id'];
904 $table['name'] = $new_table['name'];
905 $table['description'] = $new_table['description'];
906 $table['data'] = $new_table['data'];
907 // Make sure that cells are stored as strings.
908 array_walk_recursive(
909 $table['data'],
910 static function( &$cell_content, $col_idx ) {
911 $cell_content = (string) $cell_content;
912 }
913 );
914 // Table Options.
915 if ( isset( $new_table['options'] ) ) { // Options are for example not set for newly added tables.
916 // Specials check for certain options.
917 if ( isset( $new_table['options']['extra_css_classes'] ) ) {
918 $new_table['options']['extra_css_classes'] = explode( ' ', $new_table['options']['extra_css_classes'] );
919 $new_table['options']['extra_css_classes'] = array_map( array( 'TablePress', 'sanitize_css_class' ), $new_table['options']['extra_css_classes'] );
920 $new_table['options']['extra_css_classes'] = array_unique( $new_table['options']['extra_css_classes'] );
921 $new_table['options']['extra_css_classes'] = trim( implode( ' ', $new_table['options']['extra_css_classes'] ) );
922 }
923 if ( isset( $new_table['options']['datatables_paginate_entries'] ) ) {
924 $new_table['options']['datatables_paginate_entries'] = (int) $new_table['options']['datatables_paginate_entries'];
925 if ( $new_table['options']['datatables_paginate_entries'] < 1 ) {
926 $new_table['options']['datatables_paginate_entries'] = 10; // Default value.
927 }
928 }
929 // Merge new options.
930 $default_table = $this->get_table_template();
931 $table['options'] = array_intersect_key( $table['options'], $default_table['options'] );
932 $new_table['options'] = array_intersect_key( $new_table['options'], $default_table['options'] );
933 $table['options'] = array_merge( $table['options'], $new_table['options'] );
934 }
935 // Table Visibility.
936 $table['visibility']['rows'] = $new_table['visibility']['rows'];
937 $table['visibility']['columns'] = $new_table['visibility']['columns'];
938
939 // $table['author'] = get_current_user_id(); // We don't want this, as it would override the original author.
940 // $table['created'] = wp_date( 'Y-m-d H:i:s' ); // We don't want this, as it would override the original datetime.
941 $table['last_modified'] = wp_date( 'Y-m-d H:i:s' );
942 $table['options']['last_editor'] = get_current_user_id();
943
944 return $table;
945 }
946
947 /**
948 * Save the table options of a table (in a post meta field of the table's post).
949 *
950 * @since 1.0.0
951 *
952 * @param int $post_id Post ID.
953 * @param array $options Table options.
954 * @return bool True on success, false on error.
955 */
956 protected function _add_table_options( $post_id, array $options ) {
957 $options = wp_json_encode( $options, TABLEPRESS_JSON_OPTIONS );
958 return $this->model_post->add_meta_field( $post_id, $this->table_options_field_name, $options );
959 }
960
961 /**
962 * Update the table options of a table (in a post meta field in the table's post).
963 *
964 * @since 1.0.0
965 *
966 * @param int $post_id Post ID.
967 * @param array $options Table options.
968 * @return bool True on success, false on error.
969 */
970 protected function _update_table_options( $post_id, array $options ) {
971 $options = wp_json_encode( $options, TABLEPRESS_JSON_OPTIONS );
972 return $this->model_post->update_meta_field( $post_id, $this->table_options_field_name, $options );
973 }
974
975 /**
976 * Get the table options of a table (from a post meta field of the table's post).
977 *
978 * @since 1.0.0
979 *
980 * @param int $post_id Post ID.
981 * @return array Table options on success, empty array on error.
982 */
983 protected function _get_table_options( $post_id ) {
984 $options = $this->model_post->get_meta_field( $post_id, $this->table_options_field_name );
985 if ( empty( $options ) ) {
986 return array();
987 }
988 return (array) json_decode( $options, true );
989 }
990
991 /**
992 * Save the table visibility of a table (in a post meta field of the table's post).
993 *
994 * @since 1.0.0
995 *
996 * @param int $post_id Post ID.
997 * @param array $visibility Table visibility.
998 * @return bool True on success, false on error.
999 */
1000 protected function _add_table_visibility( $post_id, array $visibility ) {
1001 $visibility = wp_json_encode( $visibility, TABLEPRESS_JSON_OPTIONS );
1002 return $this->model_post->add_meta_field( $post_id, $this->table_visibility_field_name, $visibility );
1003 }
1004
1005 /**
1006 * Update the table visibility of a table (in a post meta field in the table's post).
1007 *
1008 * @since 1.0.0
1009 *
1010 * @param int $post_id Post ID.
1011 * @param array $visibility Table visibility.
1012 * @return bool True on success, false on error.
1013 */
1014 protected function _update_table_visibility( $post_id, array $visibility ) {
1015 $visibility = wp_json_encode( $visibility, TABLEPRESS_JSON_OPTIONS );
1016 return $this->model_post->update_meta_field( $post_id, $this->table_visibility_field_name, $visibility );
1017 }
1018
1019 /**
1020 * Get the table visibility of a table (from a post meta field of the table's post).
1021 *
1022 * @since 1.0.0
1023 *
1024 * @param int $post_id Post ID.
1025 * @return array Table visibility on success, empty array on error.
1026 */
1027 protected function _get_table_visibility( $post_id ) {
1028 $visibility = $this->model_post->get_meta_field( $post_id, $this->table_visibility_field_name );
1029 if ( empty( $visibility ) ) {
1030 return array();
1031 }
1032 return json_decode( $visibility, true );
1033 }
1034
1035 /**
1036 * Merge existing Table Options with default Table Options,
1037 * remove (no longer) existing options, after a table scheme change,
1038 * for all tables.
1039 *
1040 * @since 1.0.0
1041 * @since 2.0.0 Add optional $remove_old_options parameter.
1042 *
1043 * @param bool $remove_old_options Optional. Whether old table options should be removed from the database. Default true.
1044 */
1045 public function merge_table_options_defaults( $remove_old_options = true ) {
1046 $table_post = $this->tables->get( 'table_post' );
1047 if ( empty( $table_post ) ) {
1048 return;
1049 }
1050
1051 // Prime the meta cache with the table options of all tables.
1052 update_meta_cache( 'post', array_values( $table_post ) );
1053
1054 // Get default Table with default Table Options.
1055 $default_table = $this->get_table_template();
1056
1057 // Go through all tables (this loop now uses the WP cache).
1058 foreach ( $table_post as $table_id => $post_id ) {
1059 $table_options = $this->_get_table_options( $post_id );
1060 if ( $remove_old_options ) {
1061 // Remove old (i.e. no longer existing) Table Options.
1062 $table_options = array_intersect_key( $table_options, $default_table['options'] );
1063 }
1064 // Merge current into new Table Options.
1065 $table_options = array_merge( $default_table['options'], $table_options );
1066 $this->_update_table_options( $post_id, $table_options );
1067 }
1068 }
1069
1070 /**
1071 * Invalidate all table output caches, e.g. after a plugin update.
1072 *
1073 * @since 1.0.0
1074 */
1075 public function invalidate_table_output_caches() {
1076 $table_post = $this->tables->get( 'table_post' );
1077 if ( empty( $table_post ) ) {
1078 return;
1079 }
1080
1081 foreach ( $table_post as $table_id => $post_id ) {
1082 $this->invalidate_table_output_cache( $table_id );
1083 }
1084 }
1085
1086 /**
1087 * Add mime type field to existing posts with the TablePress Custom Post Type,
1088 * so that other plugins know that they are not dealing with plain text.
1089 *
1090 * @since 1.5.0
1091 *
1092 * @global wpdb $wpdb WordPress database abstraction object.
1093 */
1094 public function add_mime_type_to_posts() {
1095 global $wpdb;
1096 $wpdb->update( $wpdb->posts, array( 'post_mime_type' => 'application/json' ), array( 'post_type' => $this->model_post->get_post_type() ) );
1097 }
1098
1099 /**
1100 * Add a table ID for a post (table) that was imported through the WP WXR importer to the table ID to post ID map.
1101 *
1102 * @since 1.5.0
1103 *
1104 * @param int|WP_Error $post_id Post ID of the imported post on success. 0 or WP_Error on failure.
1105 * @param int $original_post_id Original post ID that the post had on the site where it was exported from.
1106 * @param array $postdata Post data that was imported into the database.
1107 * @param array $post Original post data as it was exported.
1108 */
1109 public function add_table_id_on_wp_import( $post_id, $original_post_id, array $postdata, array $post ) {
1110 // Bail if the post could not be imported or if the post is not a TablePress table.
1111 if ( is_wp_error( $post_id ) || $this->model_post->get_post_type() !== $postdata['post_type'] ) {
1112 return;
1113 }
1114
1115 // Extract the table IDs from the `_tablepress_export_table_id` post meta field.
1116 $table_ids = array();
1117 if ( isset( $post['postmeta'] ) && is_array( $post['postmeta'] ) ) {
1118 foreach ( $post['postmeta'] as $postmeta ) {
1119 if ( '_tablepress_export_table_id' === $postmeta['key'] ) {
1120 $table_ids = $postmeta['value'];
1121 $table_ids = explode( ',', $table_ids );
1122 break;
1123 }
1124 }
1125 }
1126
1127 // Save the post ID for each of the table IDs.
1128 $post_id_saved = false;
1129 foreach ( $table_ids as $table_id ) {
1130 $table_id = preg_replace( '/[^a-zA-Z0-9_-]/', '', $table_id );
1131 if ( '' === $table_id || $this->table_exists( $table_id ) ) {
1132 continue;
1133 }
1134 $this->_update_post_id( $table_id, $post_id );
1135 $post_id_saved = true;
1136 }
1137
1138 // Save the post ID for a new table ID if it could not be saved for any of the imported table IDs.
1139 if ( ! $post_id_saved ) {
1140 $table_id = $this->_get_new_table_id();
1141 $this->_update_post_id( $table_id, $post_id );
1142 }
1143 }
1144
1145 /**
1146 * Remove the `_tablepress_export_table_id` post meta field from the fields that are imported during a WP WXR import.
1147 *
1148 * @since 1.5.0
1149 *
1150 * @param array $postmeta Post meta fields for the post.
1151 * @param int $post_id Post ID.
1152 * @param array $post Post.
1153 * @return array Modified post meta fields.
1154 */
1155 public function prevent_table_id_post_meta_import_on_wp_import( array $postmeta, $post_id, array $post ) {
1156 // Bail if the post is not a TablePress table.
1157 if ( $this->model_post->get_post_type() !== $post['post_type'] ) {
1158 return $postmeta;
1159 }
1160
1161 // Remove the `_tablepress_export_table_id` post meta field from the post meta fields.
1162 foreach ( $postmeta as $index => $meta ) {
1163 if ( '_tablepress_export_table_id' === $meta['key'] ) {
1164 unset( $postmeta[ $index ] );
1165 }
1166 }
1167
1168 return $postmeta;
1169 }
1170
1171 /**
1172 * Add the table IDs for an exported post (table) to the WP WXR export file.
1173 *
1174 * The table IDs for a table are exported in a faked post meta field.
1175 * As there's no action for adding extra data to the WXR export file, we hijack the `wxr_export_skip_postmeta` filter hook.
1176 *
1177 * @since 1.5.0
1178 *
1179 * @param bool $skip Whether to skip the current post meta. Default false.
1180 * @param string $meta_key Current meta key.
1181 * @param stdClass $meta Current meta object.
1182 */
1183 public function add_table_id_to_wp_export( $skip, $meta_key, $meta ) {
1184 // Bail if the exporter doesn't process a TablePress table right now.
1185 if ( $this->table_options_field_name !== $meta_key ) {
1186 return $skip;
1187 }
1188
1189 // Find all table IDs that map to the post ID of the table that is currently being exported.
1190 $table_post = $this->tables->get( 'table_post' );
1191 $table_ids = array_keys( $table_post, (int) $meta->post_id, true );
1192
1193 // Bail if no table IDs are mapped to this post ID.
1194 if ( empty( $table_ids ) ) {
1195 return $skip;
1196 }
1197
1198 // Pretend that there is a `_tablepress_export_table_id` post meta field with the list of table IDs.
1199 $key = '_tablepress_export_table_id';
1200 $value = wxr_cdata( implode( ',', $table_ids ) );
1201
1202 // Hijack the filter and print extra XML code for our faked post meta field.
1203 echo <<<WXR
1204 <wp:postmeta>
1205 <wp:meta_key>{$key}</wp:meta_key>
1206 <wp:meta_value>{$value}</wp:meta_value>
1207 </wp:postmeta>\n
1208 WXR;
1209
1210 return $skip;
1211 }
1212
1213 /**
1214 * Delete the WP_Option of the model.
1215 *
1216 * @since 1.0.0
1217 */
1218 public function destroy() {
1219 $this->tables->delete();
1220 }
1221
1222 } // class TablePress_Table_Model
1223