PluginProbe
TablePress – Tables in WordPress made easy / 3.3.3
TablePress – Tables in WordPress made easy v3.3.3
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-post.php

model-post.php in TablePress – Tables in WordPress made easy 3.3.3, at models/model-post.php

367 lines 11.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Post 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 * Post Model class
16 *
17 * @package TablePress
18 * @subpackage Models
19 * @author Tobias Bäthge
20 * @since 1.0.0
21 */
22 class TablePress_Post_Model extends TablePress_Model {
23
24 /**
25 * Name of the "Custom Post Type" for the tables.
26 *
27 * @since 1.0.0
28 * @var lowercase-string&non-empty-string
29 */
30 protected string $post_type = 'tablepress_table';
31
32 /**
33 * Inits the model by registering the Custom Post Type.
34 *
35 * @since 1.0.0
36 */
37 public function __construct() {
38 parent::__construct();
39 $this->_register_post_type(); // We are on WP "init" hook already.
40 }
41
42 /**
43 * Registers the Custom Post Type which the tables use.
44 *
45 * @since 1.0.0
46 */
47 protected function _register_post_type(): void {
48 /**
49 * Filters the "Custom Post Type" that TablePress uses for storing tables in the database.
50 *
51 * @since 1.0.0
52 *
53 * @param lowercase-string&non-empty-string $post_type The "Custom Post Type" that TablePress uses.
54 */
55 $this->post_type = apply_filters( 'tablepress_post_type', $this->post_type );
56 $post_type_args = array(
57 'labels' => array(
58 'name' => 'TablePress Tables',
59 ),
60 'public' => false,
61 'show_ui' => false,
62 'query_var' => false,
63 'rewrite' => false,
64 'capability_type' => 'tablepress_table', // This ensures, that WP's regular CPT UI respects our capabilities.
65 'map_meta_cap' => false, // Integrated WP mapping does not fit our needs, therefore use our own in a filter.
66 'supports' => array( 'title', 'editor', 'excerpt', 'revisions' ),
67 'can_export' => true,
68 );
69 /**
70 * Filters the arguments for the registration of the "Custom Post Type" that TablePress uses.
71 *
72 * @since 1.0.0
73 *
74 * @param array<string, mixed> $post_type_args Arguments for the registration of the TablePress "Custom Post Type".
75 */
76 $post_type_args = apply_filters( 'tablepress_post_type_args', $post_type_args );
77 register_post_type( $this->post_type, $post_type_args );
78 }
79
80 /**
81 * Inserts a post with the correct Custom Post Type and default values in the wp_posts table in the database.
82 *
83 * @since 1.0.0
84 *
85 * @param array<string, mixed> $post Post to insert.
86 * @return int|WP_Error Post ID of the inserted post on success, WP_Error on error.
87 */
88 public function insert( array $post ) /* : int|WP_Error */ {
89 $default_post = array(
90 'ID' => false, // false on new insert, but existing post ID on update.
91 'comment_status' => 'closed',
92 'ping_status' => 'closed',
93 'post_category' => false,
94 'post_content' => '',
95 'post_excerpt' => '',
96 'post_parent' => 0,
97 'post_password' => '',
98 'post_status' => 'publish',
99 'post_title' => '',
100 'post_type' => $this->post_type,
101 'tags_input' => '',
102 'to_ping' => '',
103 );
104 $post = array_merge( $default_post, $post );
105 // WP expects everything to be slashed.
106 $post = wp_slash( $post );
107
108 // Remove balanceTags() from sanitize_post(), as it can destroy the JSON when messing with HTML.
109 remove_filter( 'content_save_pre', 'balanceTags', 50 );
110 remove_filter( 'excerpt_save_pre', 'balanceTags', 50 );
111
112 /*
113 * Remove possible KSES filtering, as it can destroy the JSON when messing with HTML.
114 * KSES filtering is done to table cells individually, when saving.
115 */
116 $has_kses = ( false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ) );
117 if ( $has_kses ) {
118 kses_remove_filters();
119 }
120
121 $post_id = wp_insert_post( $post, true );
122
123 // Restore removed content filters.
124 add_filter( 'content_save_pre', 'balanceTags', 50 );
125 add_filter( 'excerpt_save_pre', 'balanceTags', 50 );
126 if ( $has_kses ) {
127 kses_init_filters();
128 }
129
130 // In rare cases, `wp_insert_post()` returns 0 as the post ID, when an error happens, so it's converted to a WP_Error here.
131 if ( 0 === $post_id ) { // @phpstan-ignore identical.alwaysFalse (False-positive in the PHPStan WordPress stubs.)
132 return new WP_Error( 'post_insert', '' );
133 }
134
135 return $post_id;
136 }
137
138 /**
139 * Updates an existing post with the correct Custom Post Type and default values in the wp_posts table in the database.
140 *
141 * @since 1.0.0
142 *
143 * @param array<string, mixed> $post Post.
144 * @return int|WP_Error Post ID of the updated post on success, WP_Error on error.
145 */
146 public function update( array $post ) /* : int|WP_Error */ {
147 $default_post = array(
148 'ID' => false, // false on new insert, but existing post ID on update.
149 'comment_status' => 'closed',
150 'ping_status' => 'closed',
151 'post_category' => false,
152 'post_content' => '',
153 'post_excerpt' => '',
154 'post_parent' => 0,
155 'post_password' => '',
156 'post_status' => 'publish',
157 'post_title' => '',
158 'post_type' => $this->post_type,
159 'tags_input' => '',
160 'to_ping' => '',
161 );
162 $post = array_merge( $default_post, $post );
163 // WP expects everything to be slashed.
164 $post = wp_slash( $post );
165
166 // Remove balanceTags() from sanitize_post(), as it can destroy the JSON when messing with HTML.
167 remove_filter( 'content_save_pre', 'balanceTags', 50 );
168 remove_filter( 'excerpt_save_pre', 'balanceTags', 50 );
169
170 /*
171 * Remove possible KSES filtering, as it can destroy the JSON when messing with HTML.
172 * KSES filtering is done to table cells individually, when saving.
173 */
174 $has_kses = ( false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ) );
175 if ( $has_kses ) {
176 kses_remove_filters();
177 }
178
179 $post_id = wp_update_post( $post, true );
180
181 // Restore removed content filters.
182 add_filter( 'content_save_pre', 'balanceTags', 50 );
183 add_filter( 'excerpt_save_pre', 'balanceTags', 50 );
184 if ( $has_kses ) {
185 kses_init_filters();
186 }
187
188 return $post_id;
189 }
190
191 /**
192 * Gets a post from the wp_posts table in the database.
193 *
194 * @since 1.0.0
195 *
196 * @param int $post_id Post ID.
197 * @return WP_Post|false Post on success, false on error.
198 */
199 public function get( int $post_id ) /* : WP_Post|false */ {
200 $post = get_post( $post_id );
201 if ( is_null( $post ) ) {
202 return false;
203 }
204 return $post;
205 }
206
207 /**
208 * Deletes a post (and all revisions) from the wp_posts table in the database.
209 *
210 * @since 1.0.0
211 *
212 * @param int $post_id Post ID.
213 * @return WP_Post|false|null Post data on success, false or null on failure.
214 */
215 public function delete( int $post_id ) /* : WP_Post|false|null */ {
216 return wp_delete_post( $post_id, true ); // true means force delete, although for CPTs this is automatic in this function.
217 }
218
219 /**
220 * Moves a post to the trash (if trash is globally enabled), instead of directly deleting the post.
221 * (yet unused)
222 *
223 * @since 1.0.0
224 *
225 * @param int $post_id Post ID.
226 * @return WP_Post|false|null Post data on success, false or null on failure.
227 */
228 public function trash( int $post_id ) /* : WP_Post|false|null */ {
229 return wp_trash_post( $post_id );
230 }
231
232 /**
233 * Restores a post from the trash.
234 * (yet unused)
235 *
236 * @since 1.0.0
237 *
238 * @param int $post_id Post ID.
239 * @return WP_Post|false|null Post on success, false or null on error.
240 */
241 public function untrash( int $post_id ) /* : WP_Post|false */ {
242 return wp_untrash_post( $post_id );
243 }
244
245 /**
246 * Loads all posts with one query, to prime the cache.
247 *
248 * @since 1.0.0
249 *
250 * @global wpdb $wpdb WordPress database abstraction object.
251 * @see get_post()
252 *
253 * @param int[] $all_post_ids List of Post IDs.
254 * @param bool $update_meta_cache Optional. Whether to update the Post Meta Cache (for table options and visibility).
255 */
256 public function load_posts( array $all_post_ids, bool $update_meta_cache = true ): void {
257 global $wpdb;
258
259 // Split post loading, to save memory.
260 while ( ! empty( $all_post_ids ) ) {
261 $post_ids = array_splice( $all_post_ids, 0, 100 ); // Extract 100 posts at a time.
262 // Don't load posts that are in the cache already.
263 $post_ids = _get_non_cached_ids( $post_ids, 'posts' );
264 if ( ! empty( $post_ids ) ) {
265 $post_ids_list = implode( ',', $post_ids );
266 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
267 $posts = $wpdb->get_results( "SELECT {$wpdb->posts}.* FROM {$wpdb->posts} WHERE ID IN ({$post_ids_list})" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
268 update_post_cache( $posts );
269 if ( $update_meta_cache ) {
270 // Get all post meta data for all table posts, @see get_post_meta().
271 update_meta_cache( 'post', $post_ids );
272 }
273 }
274 }
275 }
276
277 /**
278 * Counts the number of posts with the model's CPT in the wp_posts table in the database.
279 * (currently for debug only)
280 *
281 * @since 1.0.0
282 *
283 * @return int Number of posts.
284 */
285 public function count_posts(): int {
286 return array_sum( (array) wp_count_posts( $this->post_type ) ); // Original return value is object with the counts for each post_status.
287 }
288
289 /**
290 * Adds a post meta field to a post.
291 *
292 * @since 1.0.0
293 *
294 * @param int $post_id ID of the post for which the field shall be added.
295 * @param string $field Name of the post meta field.
296 * @param string $value Value of the post meta field (not slashed).
297 * @return bool True on success, false on error.
298 */
299 public function add_meta_field( int $post_id, string $field, string $value ): bool {
300 $success = add_post_meta( $post_id, wp_slash( $field ), wp_slash( $value ), true ); // WP expects slashed values, `true` means unique.
301 // Make sure that $success is a boolean, as add_post_meta() returns an ID or false.
302 $success = ( false === $success ) ? false : true;
303 return $success;
304 }
305
306 /**
307 * Updatse the value of a post meta field of a post.
308 *
309 * If the field does not yet exist, it is added.
310 *
311 * @since 1.0.0
312 *
313 * @param int $post_id ID of the post for which the field shall be updated.
314 * @param string $field Name of the post meta field.
315 * @param string $value Value of the post meta field (not slashed).
316 * @return bool True on success, false on error.
317 */
318 public function update_meta_field( int $post_id, string $field, string $value ): bool {
319 $prev_value = (string) get_post_meta( $post_id, $field, true );
320 // No need to update, if values are equal (also, update_post_meta() would return false for this).
321 if ( $prev_value === $value ) {
322 return true;
323 }
324
325 return (bool) update_post_meta( $post_id, wp_slash( $field ), wp_slash( $value ), $prev_value ); // WP expects slashed values.
326 }
327
328 /**
329 * Gets the value of a post meta field of a post.
330 *
331 * @since 1.0.0
332 *
333 * @param int $post_id ID of the post for which the field shall be retrieved.
334 * @param string $field Name of the post meta field.
335 * @return string Value of the meta field.
336 */
337 public function get_meta_field( int $post_id, string $field ): string {
338 return get_post_meta( $post_id, $field, true ); // `true` means single value.
339 }
340
341 /**
342 * Deletes a post meta field of a post.
343 * (yet unused)
344 *
345 * @since 1.0.0
346 *
347 * @param int $post_id ID of the post of which the field shall be deleted.
348 * @param string $field Name of the post meta field.
349 * @return bool True on success, false on error.
350 */
351 public function delete_meta_field( int $post_id, string $field ): bool {
352 return delete_post_meta( $post_id, wp_slash( $field ) ); // WP expects a slashed value.
353 }
354
355 /**
356 * Returns the Custom Post Type that TablePress uses.
357 *
358 * @since 1.5.0
359 *
360 * @return string The used Custom Post Type.
361 */
362 public function get_post_type(): string {
363 return $this->post_type;
364 }
365
366 } // class TablePress_Post_Model
367