Completed
Push — branch-4.0 ( 8614e2...d4128e )
by
unknown
11:02
created

WPCOM_JSON_API_Post_Endpoint::get_post_by()   F

Complexity

Conditions 110
Paths > 20000

Size

Total Lines 387
Code Lines 297

Duplication

Lines 248
Ratio 64.08 %
Metric Value
dl 248
loc 387
rs 2
nc 21276
cc 110
eloc 297
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
abstract class WPCOM_JSON_API_Post_Endpoint extends WPCOM_JSON_API_Endpoint {
4
	public $post_object_format = array(
5
		// explicitly document and cast all output
6
		'ID'        => '(int) The post ID.',
7
		'site_ID'		=> '(int) The site ID.',
8
		'author'    => '(object>author) The author of the post.',
9
		'date'      => "(ISO 8601 datetime) The post's creation time.",
10
		'modified'  => "(ISO 8601 datetime) The post's most recent update time.",
11
		'title'     => '(HTML) <code>context</code> dependent.',
12
		'URL'       => '(URL) The full permalink URL to the post.',
13
		'short_URL' => '(URL) The wp.me short URL.',
14
		'content'   => '(HTML) <code>context</code> dependent.',
15
		'excerpt'   => '(HTML) <code>context</code> dependent.',
16
		'slug'      => '(string) The name (slug) for the post, used in URLs.',
17
		'guid'      => '(string) The GUID for the post.',
18
		'status'    => array(
19
			'publish' => 'The post is published.',
20
			'draft'   => 'The post is saved as a draft.',
21
			'pending' => 'The post is pending editorial approval.',
22
			'private' => 'The post is published privately',
23
			'future'  => 'The post is scheduled for future publishing.',
24
			'trash'   => 'The post is in the trash.',
25
			'auto-draft' => 'The post is a placeholder for a new post.',
26
		),
27
		'sticky'   => '(bool) Is the post sticky?',
28
		'password' => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
29
		'parent'   => "(object>post_reference|false) A reference to the post's parent, if it has one.",
30
		'type'     => "(string) The post's post_type. Post types besides post, page and revision need to be whitelisted using the <code>rest_api_allowed_post_types</code> filter.",
31
		'comments_open'  => '(bool) Is the post open for comments?',
32
		'pings_open'     => '(bool) Is the post open for pingbacks, trackbacks?',
33
		'likes_enabled' => "(bool) Is the post open to likes?",
34
		'sharing_enabled' => "(bool) Should sharing buttons show on this post?",
35
		'comment_count'  => '(int) The number of comments for this post.',
36
		'like_count'     => '(int) The number of likes for this post.',
37
		'i_like'         => '(bool) Does the current user like this post?',
38
		'is_reblogged'   => '(bool) Did the current user reblog this post?',
39
		'is_following'   => '(bool) Is the current user following this blog?',
40
		'global_ID'      => '(string) A unique WordPress.com-wide representation of a post.',
41
		'featured_image' => '(URL) The URL to the featured image for this post if it has one.',
42
		'post_thumbnail' => '(object>attachment) The attachment object for the featured image if it has one.',
43
		'format'         => array(), // see constructor
44
		'geo'            => '(object>geo|false)',
45
		'menu_order'     => '(int) (Pages Only) The order pages should appear in.',
46
		'publicize_URLs' => '(array:URL) Array of Twitter and Facebook URLs published by this post.',
47
		'tags'           => '(object:tag) Hash of tags (keyed by tag name) applied to the post.',
48
		'categories'     => '(object:category) Hash of categories (keyed by category name) applied to the post.',
49
		'attachments'	 => '(object:attachment) Hash of post attachments (keyed by attachment ID).',
50
		'metadata'	     => '(array) Array of post metadata keys and values. All unprotected meta keys are available by default for read requests. Both unprotected and protected meta keys are available for authenticated requests with access. Protected meta keys can be made available with the <code>rest_api_allowed_public_metadata</code> filter.',
51
		'meta'           => '(object) API result meta data',
52
		'current_user_can' => '(object) List of permissions. Note, deprecated in favor of `capabilities`',
53
		'capabilities'   => '(object) List of post-specific permissions for the user; publish_post, edit_post, delete_post',
54
	);
55
56
	// public $response_format =& $this->post_object_format;
57
58 View Code Duplication
	function __construct( $args ) {
59
		if ( is_array( $this->post_object_format ) && isset( $this->post_object_format['format'] ) ) {
60
			$this->post_object_format['format'] = get_post_format_strings();
61
		}
62
		if ( !$this->response_format ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->response_format of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
63
			$this->response_format =& $this->post_object_format;
64
		}
65
		parent::__construct( $args );
66
	}
67
68 View Code Duplication
	function is_metadata_public( $key ) {
69
		if ( empty( $key ) )
70
			return false;
71
72
		// Default whitelisted meta keys.
73
		$whitelisted_meta = array( '_thumbnail_id' );
74
75
		/**
76
		 * Filters the meta keys accessible by the REST API.
77
		 * @see https://developer.wordpress.com/2013/04/26/custom-post-type-and-metadata-support-in-the-rest-api/
78
		 *
79
		 * @module json-api
80
		 *
81
		 * @since 2.2.3
82
		 *
83
		 * @param array $whitelisted_meta Array of metadata that is accessible by the REST API.
84
		 */
85
 		if ( in_array( $key, apply_filters( 'rest_api_allowed_public_metadata', $whitelisted_meta ) ) )
86
			return true;
87
88
		if ( 0 === strpos( $key, 'geo_' ) )
89
			return true;
90
91
		if ( 0 === strpos( $key, '_wpas_' ) )
92
			return true;
93
94
 		return false;
95
 	}
96
97
	function the_password_form() {
98
		return __( 'This post is password protected.', 'jetpack' );
99
	}
100
101
	/**
102
	 * Get a post by a specified field and value
103
	 *
104
	 * @param string $field
105
	 * @param string $field_value
106
	 * @param string $context Post use context (e.g. 'display')
107
	 * @return array Post
108
	 **/
109
	function get_post_by( $field, $field_value, $context = 'display' ) {
110
		global $blog_id;
111
112
		/** This filter is documented in class.json-api-endpoints.php */
113
		$is_jetpack = true === apply_filters( 'is_jetpack_site', false, $blog_id );
114
115 View Code Duplication
		if ( defined( 'GEO_LOCATION__CLASS' ) && class_exists( GEO_LOCATION__CLASS ) ) {
116
			$geo = call_user_func( array( GEO_LOCATION__CLASS, 'init' ) );
117
		} else {
118
			$geo = false;
119
		}
120
121 View Code Duplication
		if ( 'display' === $context ) {
122
			$args = $this->query_args();
123
			if ( isset( $args['content_width'] ) && $args['content_width'] ) {
124
				$GLOBALS['content_width'] = (int) $args['content_width'];
125
			}
126
		}
127
128 View Code Duplication
		if ( strpos( $_SERVER['HTTP_USER_AGENT'], 'wp-windows8' ) ) {
129
			remove_shortcode( 'gallery', 'gallery_shortcode' );
130
			add_shortcode( 'gallery', array( &$this, 'win8_gallery_shortcode' ) );
131
		}
132
133 View Code Duplication
		switch ( $field ) {
134
		case 'name' :
135
			$post_id = $this->get_post_id_by_name( $field_value );
136
			if ( is_wp_error( $post_id ) ) {
137
				return $post_id;
138
			}
139
			break;
140
		default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
141
			$post_id = (int) $field_value;
142
			break;
143
		}
144
145
		$post = get_post( $post_id, OBJECT, $context );
146
147
		if ( !$post || is_wp_error( $post ) ) {
148
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
149
		}
150
151 View Code Duplication
		if ( ! $this->is_post_type_allowed( $post->post_type ) && ( ! function_exists( 'is_post_freshly_pressed' ) || ! is_post_freshly_pressed( $post->ID ) ) ) {
152
			return new WP_Error( 'unknown_post', 'Unknown post', 404 );
153
		}
154
155
		// Permissions
156
		$capabilities = $this->get_current_user_capabilities( $post );
157
158 View Code Duplication
		switch ( $context ) {
159
		case 'edit' :
160
			if ( ! $capabilities['edit_post'] ) {
161
				return new WP_Error( 'unauthorized', 'User cannot edit post', 403 );
162
			}
163
			break;
164
		case 'display' :
165
			break;
166
		default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
167
			return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 );
168
		}
169
170
		$can_view = $this->user_can_view_post( $post->ID );
171
		if ( !$can_view || is_wp_error( $can_view ) ) {
172
			return $can_view;
173
		}
174
175
		$GLOBALS['post'] = $post;
176
177
		if ( 'display' === $context ) {
178
			setup_postdata( $post );
179
		}
180
181
		$response = array();
182
183
		$fields = null;
184
		if ( 'display' === $context && ! empty( $this->api->query['fields'] )  ) {
185
			$fields = array_fill_keys( array_map( 'trim', explode( ',', $this->api->query['fields'] ) ), true );
186
		}
187
188
		foreach ( array_keys( $this->post_object_format ) as $key ) {
189
			if ( $fields !== null && ! isset( $fields[$key] ) ) {
190
				continue;
191
			}
192
			switch ( $key ) {
193
			case 'ID' :
194
				// explicitly cast all output
195
				$response[$key] = (int) $post->ID;
196
				break;
197
			case 'site_ID' :
198
				$response[$key] = (int) $this->api->get_blog_id_for_output();
199
				break;
200 View Code Duplication
			case 'author' :
201
				$response[$key] = (object) $this->get_author( $post, 'edit' === $context && $capabilities['edit_post'] );
202
				break;
203
			case 'date' :
204
				$response[$key] = (string) $this->format_date( $post->post_date_gmt, $post->post_date );
205
				break;
206
			case 'modified' :
207
				$response[$key] = (string) $this->format_date( $post->post_modified_gmt, $post->post_modified );
208
				break;
209 View Code Duplication
			case 'title' :
210
				if ( 'display' === $context ) {
211
					$response[$key] = (string) get_the_title( $post->ID );
212
				} else {
213
					$response[$key] = (string) htmlspecialchars_decode( $post->post_title, ENT_QUOTES );
214
				}
215
				break;
216 View Code Duplication
			case 'URL' :
217
				if ( 'revision' === $post->post_type ) {
218
					$response[$key] = (string) esc_url_raw( get_permalink( $post->post_parent ) );
219
				} else {
220
					$response[$key] = (string) esc_url_raw( get_permalink( $post->ID ) );
221
				}
222
				break;
223
			case 'short_URL' :
224
				$response[$key] = (string) esc_url_raw( wp_get_shortlink( $post->ID ) );
225
				break;
226 View Code Duplication
			case 'content' :
227
				if ( 'display' === $context ) {
228
					add_filter( 'the_password_form', array( $this, 'the_password_form' ) );
229
					$response[$key] = (string) $this->get_the_post_content_for_display();
230
					remove_filter( 'the_password_form', array( $this, 'the_password_form' ) );
231
				} else {
232
					$response[$key] = (string) $post->post_content;
233
				}
234
				break;
235 View Code Duplication
			case 'excerpt' :
236
				if ( 'display' === $context ) {
237
					add_filter( 'the_password_form', array( $this, 'the_password_form' ) );
238
					ob_start();
239
					the_excerpt();
240
					$response[$key] = (string) ob_get_clean();
241
					remove_filter( 'the_password_form', array( $this, 'the_password_form' ) );
242
				} else {
243
					$response[$key] = htmlspecialchars_decode( (string) $post->post_excerpt, ENT_QUOTES );
244
				}
245
				break;
246
			case 'status' :
247
				$response[$key] = (string) get_post_status( $post->ID );
248
				break;
249
			case 'sticky' :
250
				$response[$key] = (bool) is_sticky( $post->ID );
251
				break;
252
			case 'slug' :
253
				$response[$key] = (string) $post->post_name;
254
				break;
255
			case 'guid' :
256
				$response[$key] = (string) $post->guid;
257
				break;
258 View Code Duplication
			case 'password' :
259
				$response[$key] = (string) $post->post_password;
260
				if ( 'edit' === $context ) {
261
					$response[$key] = htmlspecialchars_decode( (string) $response[$key], ENT_QUOTES );
262
				}
263
				break;
264 View Code Duplication
			case 'parent' : // (object|false)
265
				if ( $post->post_parent ) {
266
					$parent         = get_post( $post->post_parent );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 9 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
267
					if ( 'display' === $context ) {
268
						$parent_title = (string) get_the_title( $parent->ID );
269
					} else {
270
						$parent_title = (string) htmlspecialchars_decode( $post->post_title, ENT_QUOTES );
271
					}
272
					$response[$key] = (object) array(
273
						'ID'   => (int) $parent->ID,
274
						'type' => (string) $parent->post_type,
275
						'link' => (string) $this->get_post_link( $this->api->get_blog_id_for_output(), $parent->ID ),
276
						'title' => $parent_title,
277
					);
278
				} else {
279
					$response[$key] = false;
280
				}
281
				break;
282
			case 'type' :
283
				$response[$key] = (string) $post->post_type;
284
				break;
285
			case 'comments_open' :
286
				$response[$key] = (bool) comments_open( $post->ID );
287
				break;
288
			case 'pings_open' :
289
				$response[$key] = (bool) pings_open( $post->ID );
290
				break;
291 View Code Duplication
			case 'likes_enabled' :
292
				/** This filter is documented in modules/likes.php */
293
				$sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
294
				$post_likes_switched    = (bool) get_post_meta( $post->ID, 'switch_like_status', true );
295
				$post_likes_enabled = $sitewide_likes_enabled;
296
				if ( $post_likes_switched ) {
297
					$post_likes_enabled = ! $post_likes_enabled;
298
				}
299
				$response[$key] = (bool) $post_likes_enabled;
300
				break;
301 View Code Duplication
			case 'sharing_enabled' :
302
				$show = true;
303
				/** This filter is documented in modules/sharedaddy/sharing-service.php */
304
				$show = apply_filters( 'sharing_show', $show, $post );
305
306
				$switched_status = get_post_meta( $post->ID, 'sharing_disabled', false );
307
308
				if ( !empty( $switched_status ) )
309
					$show = false;
310
				$response[$key] = (bool) $show;
311
				break;
312
			case 'comment_count' :
313
				$response[$key] = (int) $post->comment_count;
314
				break;
315
			case 'like_count' :
316
				$response[$key] = (int) $this->api->post_like_count( $blog_id, $post->ID );
317
				break;
318
			case 'i_like'     :
319
				$response[$key] = (bool) $this->api->is_liked( $blog_id, $post->ID );
320
				break;
321
			case 'is_reblogged':
322
				$response[$key] = (bool) $this->api->is_reblogged( $blog_id, $post->ID );
323
				break;
324
			case 'is_following':
325
				$response[$key] = (bool) $this->api->is_following( $blog_id );
326
				break;
327
			case 'global_ID':
328
				$response[$key] = (string) $this->api->add_global_ID( $blog_id, $post->ID );
329
				break;
330 View Code Duplication
			case 'featured_image' :
331
				if ( $is_jetpack && ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
332
					$response[ $key ] = get_post_meta( $post->ID, '_jetpack_featured_image', true );
333
				} else {
334
					$image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
335
					if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) {
336
						$response[ $key ] = (string) $image_attributes[0];
337
					} else {
338
						$response[ $key ] = '';
339
					}
340
				}
341
				break;
342 View Code Duplication
			case 'post_thumbnail' :
343
				$response[$key] = null;
344
345
				$thumb_id = get_post_thumbnail_id( $post->ID );
346
				if ( ! empty( $thumb_id ) ) {
347
					$attachment = get_post( $thumb_id );
348
					if ( ! empty( $attachment ) )
349
						$featured_image_object = $this->get_attachment( $attachment );
350
351
					if ( ! empty( $featured_image_object ) ) {
352
						$response[$key] = (object) $featured_image_object;
353
					}
354
				}
355
				break;
356 View Code Duplication
			case 'format' :
357
				$response[$key] = (string) get_post_format( $post->ID );
358
				if ( !$response[$key] ) {
359
					$response[$key] = 'standard';
360
				}
361
				break;
362 View Code Duplication
			case 'geo' : // (object|false)
363
				if ( !$geo ) {
364
					$response[$key] = false;
365
				} else {
366
					$geo_data       = $geo->get_geo( 'post', $post->ID );
367
					$response[$key] = false;
368
					if ( $geo_data ) {
369
						$geo_data = array_intersect_key( $geo_data, array( 'latitude' => true, 'longitude' => true, 'address' => true, 'public' => true ) );
370
						if ( $geo_data ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $geo_data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
371
							$response[$key] = (object) array(
372
								'latitude'  => isset( $geo_data['latitude']  ) ? (float)  $geo_data['latitude']  : 0,
373
								'longitude' => isset( $geo_data['longitude'] ) ? (float)  $geo_data['longitude'] : 0,
374
								'address'   => isset( $geo_data['address'] )   ? (string) $geo_data['address']   : '',
375
							);
376
						} else {
377
							$response[$key] = false;
378
						}
379
						// Private
380
						if ( !isset( $geo_data['public'] ) || !$geo_data['public'] ) {
381
							if ( 'edit' !== $context || ! $capabilities['edit_post'] ) {
382
								// user can't access
383
								$response[$key] = false;
384
							}
385
						}
386
					}
387
				}
388
				break;
389
			case 'menu_order':
390
				$response[$key] = (int) $post->menu_order;
391
				break;
392 View Code Duplication
			case 'publicize_URLs' :
393
				$publicize_URLs = array();
394
				$publicize      = get_post_meta( $post->ID, 'publicize_results', true );
395
				if ( $publicize ) {
396
					foreach ( $publicize as $service => $data ) {
397
						switch ( $service ) {
398
						case 'twitter' :
399
							foreach ( $data as $datum ) {
400
								$publicize_URLs[] = esc_url_raw( "https://twitter.com/{$datum['user_id']}/status/{$datum['post_id']}" );
401
							}
402
							break;
403
						case 'fb' :
404
							foreach ( $data as $datum ) {
405
								$publicize_URLs[] = esc_url_raw( "https://www.facebook.com/permalink.php?story_fbid={$datum['post_id']}&id={$datum['user_id']}" );
406
							}
407
							break;
408
						}
409
					}
410
				}
411
				$response[$key] = (array) $publicize_URLs;
412
				break;
413 View Code Duplication
			case 'tags' :
414
				$response[$key] = array();
415
				$terms = wp_get_post_tags( $post->ID );
416
				foreach ( $terms as $term ) {
417
					if ( !empty( $term->name ) ) {
418
						$response[$key][$term->name] = $this->format_taxonomy( $term, 'post_tag', 'display' );
419
					}
420
				}
421
				$response[$key] = (object) $response[$key];
422
				break;
423 View Code Duplication
			case 'categories':
424
				$response[$key] = array();
425
				$terms = wp_get_object_terms( $post->ID, 'category', array( 'fields' => 'all' ) );
426
				foreach ( $terms as $term ) {
427
					if ( !empty( $term->name ) ) {
428
						$response[$key][$term->name] = $this->format_taxonomy( $term, 'category', 'display' );
429
					}
430
				}
431
				$response[$key] = (object) $response[$key];
432
				break;
433
			case 'attachments':
434
				$response[$key] = array();
435
				$_attachments = get_posts( array( 'post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'posts_per_page' => 100 ) );
436
				foreach ( $_attachments as $attachment ) {
437
					$response[$key][$attachment->ID] = $this->get_attachment( $attachment );
438
				}
439
				$response[$key] = (object) $response[$key];
440
				break;
441 View Code Duplication
			case 'metadata' : // (array|false)
442
				$metadata = array();
443
				foreach ( (array) has_meta( $post_id ) as $meta ) {
444
					// Don't expose protected fields.
445
					$show = false;
446
					if ( $this->is_metadata_public( $meta['meta_key'] ) )
447
						$show = true;
448
					if ( current_user_can( 'edit_post_meta', $post_id , $meta['meta_key'] ) )
449
						$show = true;
450
451
					if ( !$show )
452
						continue;
453
454
					$metadata[] = array(
455
						'id'    => $meta['meta_id'],
456
						'key'   => $meta['meta_key'],
457
						'value' => maybe_unserialize( $meta['meta_value'] ),
458
					);
459
				}
460
461
				if ( ! empty( $metadata ) ) {
462
					$response[$key] = $metadata;
463
				} else {
464
					$response[$key] = false;
465
				}
466
				break;
467
			case 'meta' :
468
				$response[$key] = (object) array(
469
					'links' => (object) array(
470
						'self'    => (string) $this->get_post_link( $this->api->get_blog_id_for_output(), $post->ID ),
471
						'help'    => (string) $this->get_post_link( $this->api->get_blog_id_for_output(), $post->ID, 'help' ),
472
						'site'    => (string) $this->get_site_link( $this->api->get_blog_id_for_output() ),
473
//						'author'  => (string) $this->get_user_link( $post->post_author ),
474
//						'via'     => (string) $this->get_post_link( $reblog_origin_blog_id, $reblog_origin_post_id ),
475
						'replies' => (string) $this->get_post_link( $this->api->get_blog_id_for_output(), $post->ID, 'replies/' ),
476
						'likes'   => (string) $this->get_post_link( $this->api->get_blog_id_for_output(), $post->ID, 'likes/' ),
477
					),
478
				);
479
				break;
480
			case 'current_user_can' :
481
				$response[$key] = $capabilities;
482
				break;
483
			case 'capabilities' :
484
				$response[$key] = $capabilities;
485
				break;
486
487
			}
488
		}
489
490
		// WPCOM_JSON_API_Post_Endpoint::find_featured_worthy_media( $post );
491
		// $response['featured_media'] = self::find_featured_media( $response );
492
493
		unset( $GLOBALS['post'] );
494
		return $response;
495
	}
496
497
	// No Blog ID parameter.  No Post ID parameter.  Depends on globals.
498
	// Expects setup_postdata() to already have been run
499 View Code Duplication
	function get_the_post_content_for_display() {
500
		global $pages, $page;
501
502
		$old_pages = $pages;
503
		$old_page  = $page;
504
505
		$content = join( "\n\n", $pages );
506
		$content = preg_replace( '/<!--more(.*?)?-->/', '', $content );
507
		$pages   = array( $content );
508
		$page    = 1;
509
510
		ob_start();
511
		the_content();
512
		$return = ob_get_clean();
513
514
		$pages = $old_pages;
515
		$page  = $old_page;
516
517
		return $return;
518
	}
519
520 View Code Duplication
	function get_blog_post( $blog_id, $post_id, $context = 'display' ) {
521
		$blog_id = $this->api->get_blog_id( $blog_id );
522
		if ( !$blog_id || is_wp_error( $blog_id ) ) {
523
			return $blog_id;
524
		}
525
		switch_to_blog( $blog_id );
526
		$post = $this->get_post_by( 'ID', $post_id, $context );
527
		restore_current_blog();
528
		return $post;
529
	}
530
531
	/**
532
	 * Supporting featured media in post endpoints. Currently on for wpcom blogs
533
	 * since it's calling WPCOM_JSON_API_Read_Endpoint methods which presently
534
	 * rely on wpcom specific functionality.
535
	 *
536
	 * @param WP_Post $post
537
	 * @return object list of featured media
538
	 */
539
	public static function find_featured_media( &$post ) {
540
541
		if ( class_exists( 'WPCOM_JSON_API_Read_Endpoint' ) ) {
542
			return WPCOM_JSON_API_Read_Endpoint::find_featured_worthy_media( (array) $post );
543
		} else {
544
			return (object) array();
545
		}
546
547
	}
548
549
550
551 View Code Duplication
	function win8_gallery_shortcode( $attr ) {
552
		global $post;
553
554
		static $instance = 0;
555
		$instance++;
556
557
		$output = '';
558
559
		// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
560
		if ( isset( $attr['orderby'] ) ) {
561
			$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
562
			if ( !$attr['orderby'] )
563
				unset( $attr['orderby'] );
564
		}
565
566
		extract( shortcode_atts( array(
0 ignored issues
show
Bug introduced by
shortcode_atts(array('or...lse), $attr, 'gallery') cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
567
			'order'     => 'ASC',
568
			'orderby'   => 'menu_order ID',
569
			'id'        => $post->ID,
570
			'include'   => '',
571
			'exclude'   => '',
572
			'slideshow' => false
573
		), $attr, 'gallery' ) );
574
575
		// Custom image size and always use it
576
		add_image_size( 'win8app-column', 480 );
577
		$size = 'win8app-column';
578
579
		$id = intval( $id );
580
		if ( 'RAND' === $order )
581
			$orderby = 'none';
582
583
		if ( !empty( $include ) ) {
584
			$include      = preg_replace( '/[^0-9,]+/', '', $include );
585
			$_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
586
			$attachments  = array();
587
			foreach ( $_attachments as $key => $val ) {
588
				$attachments[$val->ID] = $_attachments[$key];
589
			}
590
		} elseif ( !empty( $exclude ) ) {
591
			$exclude     = preg_replace( '/[^0-9,]+/', '', $exclude );
592
			$attachments = get_children( array( 'post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
593
		} else {
594
			$attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
595
		}
596
597
		if ( ! empty( $attachments ) ) {
598
			foreach ( $attachments as $id => $attachment ) {
599
				$link = isset( $attr['link'] ) && 'file' === $attr['link'] ? wp_get_attachment_link( $id, $size, false, false ) : wp_get_attachment_link( $id, $size, true, false );
600
601
				if ( $captiontag && trim($attachment->post_excerpt) ) {
602
					$output .= "<div class='wp-caption aligncenter'>$link
603
						<p class='wp-caption-text'>" . wptexturize($attachment->post_excerpt) . "</p>
604
						</div>";
605
				} else {
606
					$output .= $link . ' ';
607
				}
608
			}
609
		}
610
	}
611
612
	/**
613
	 * Returns attachment object.
614
	 *
615
	 * @param $attachment attachment row
616
	 *
617
	 * @return (object)
618
	 */
619 View Code Duplication
	function get_attachment( $attachment ) {
620
		$metadata = wp_get_attachment_metadata( $attachment->ID );
621
622
		$result = array(
623
			'ID'		=> (int) $attachment->ID,
624
			'URL'           => (string) wp_get_attachment_url( $attachment->ID ),
625
			'guid'		=> (string) $attachment->guid,
626
			'mime_type'	=> (string) $attachment->post_mime_type,
627
			'width'		=> (int) isset( $metadata['width']  ) ? $metadata['width']  : 0,
628
			'height'	=> (int) isset( $metadata['height'] ) ? $metadata['height'] : 0,
629
		);
630
631
		if ( isset( $metadata['duration'] ) ) {
632
			$result['duration'] = (int) $metadata['duration'];
633
		}
634
635
		/** This filter is documented in class.jetpack-sync.php */
636
		return (object) apply_filters( 'get_attachment', $result );
637
	}
638
639
	/**
640
	 * Get post-specific user capabilities
641
	 * @param  WP_Post $post              post object
642
	 * @return array                     array of post-level permissions; 'publish_post', 'delete_post', 'edit_post'
643
	 */
644 View Code Duplication
	function get_current_user_capabilities( $post ) {
645
		return array(
646
			'publish_post' => current_user_can( 'publish_post', $post ),
647
			'delete_post'  => current_user_can( 'delete_post', $post ),
648
			'edit_post'    => current_user_can( 'edit_post', $post )
649
		);
650
	}
651
652
	/**
653
	 * Get post ID by name
654
	 *
655
	 * Attempts to match name on post title and page path
656
	 *
657
	 * @param string $name
658
	 *
659
	 * @return int|object Post ID on success, WP_Error object on failure
660
	 **/
661 View Code Duplication
	protected function get_post_id_by_name( $name ) {
662
		$name = sanitize_title( $name );
663
664
		if ( ! $name ) {
665
			return new WP_Error( 'invalid_post', 'Invalid post', 400 );
666
		}
667
668
		$posts = get_posts( array( 'name' => $name ) );
669
670
		if ( ! $posts || ! isset( $posts[0]->ID ) || ! $posts[0]->ID ) {
671
			$page = get_page_by_path( $name );
672
673
			if ( ! $page ) {
674
				return new WP_Error( 'unknown_post', 'Unknown post', 404 );
675
			}
676
677
			$post_id = $page->ID;
678
		} else {
679
			$post_id = (int) $posts[0]->ID;
680
		}
681
682
		return $post_id;
683
	}
684
}
685