summaryrefslogtreecommitdiff
blob: 712909d9ea0f5133916e7c0f8a55a5214c220ef0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php

new WPCOM_JSON_API_List_Media_v1_1_Endpoint( array(
	'description' => 'Get a list of items in the media library.',
	'group'       => 'media',
	'stat'        => 'media',
	'min_version' => '1.1',
	'max_version' => '1.1',
	'method'      => 'GET',
	'path'        => '/sites/%s/media/',
	'path_labels' => array(
		'$site' => '(int|string) Site ID or domain',
	),

	'query_parameters' => array(
		'number'    => '(int=20) The number of media items to return. Limit: 100.',
		'offset'    => '(int=0) 0-indexed offset.',
		'page'     => '(int) Return the Nth 1-indexed page of posts. Takes precedence over the <code>offset</code> parameter.',
		'page_handle' => '(string) A page handle, returned from a previous API call as a <code>meta.next_page</code> property. This is the most efficient way to fetch the next page of results.',
		'order'    => array(
			'DESC' => 'Return files in descending order. For dates, that means newest to oldest.',
			'ASC'  => 'Return files in ascending order. For dates, that means oldest to newest.',
		),
		'order_by' => array(
			'date'          => 'Order by the uploaded time of each file.',
			'title'         => "Order lexicographically by file titles.",
			'ID'            => 'Order by media ID.',
		),
		'search'    => '(string) Search query.',
		'post_ID'   => '(int) Default is showing all items. The post where the media item is attached. 0 shows unattached media items.',
		'mime_type' => "(string) Default is empty. Filter by mime type (e.g., 'image/jpeg', 'application/pdf'). Partial searches also work (e.g. passing 'image' will search for all image files).",
		'after'     => '(ISO 8601 datetime) Return media items uploaded after the specified datetime.',
		'before'    => '(ISO 8601 datetime) Return media items uploaded before the specified datetime.',
	),

	'response_format' => array(
		'media' => '(array) Array of media objects',
		'found' => '(int) The number of total results found',
		'meta'  => '(object) Meta data',
	),

	'example_request'      => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/media',
	'example_request_data' =>  array(
		'headers' => array(
			'authorization' => 'Bearer YOUR_API_TOKEN'
		)
	)
) );

class WPCOM_JSON_API_List_Media_v1_1_Endpoint extends WPCOM_JSON_API_Endpoint {

	public $date_range = array();
	public $page_handle = array();

	function callback( $path = '', $blog_id = 0 ) {
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
		if ( is_wp_error( $blog_id ) ) {
			return $blog_id;
		}

		//upload_files can probably be used for other endpoints but we want contributors to be able to use media too
		if ( ! current_user_can( 'edit_posts' ) ) {
			return new WP_Error( 'unauthorized', 'User cannot view media', 403 );
		}

		$args = $this->query_args();
		$is_eligible_for_page_handle = true;

		if ( $args['number'] < 1 ) {
			$args['number'] = 20;
		} elseif ( 100 < $args['number'] ) {
			return new WP_Error( 'invalid_number',  'The NUMBER parameter must be less than or equal to 100.', 400 );
		}

		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
			$this->load_theme_functions();
		}

		if ( isset( $args['before'] ) ) {
			$this->date_range['before'] = $args['before'];
		}
		if ( isset( $args['after'] ) ) {
			$this->date_range['after'] = $args['after'];
		}

		$query = array(
			'post_type'      => 'attachment',
			'post_status'    => 'inherit',
			'post_parent'    => isset( $args['post_ID'] ) ? $args['post_ID'] : null,
			'posts_per_page' => $args['number'],
			'post_mime_type' => isset( $args['mime_type'] ) ? $args['mime_type'] : null,
			'order'          => isset( $args['order'] ) ? $args['order'] : 'DESC',
			'orderby'        => isset( $args['order_by'] ) ? $args['order_by'] : 'date',
			's'              => isset( $args['search'] ) ? $args['search'] : null,
		);

		if ( isset( $args['page'] ) ) {
			if ( $args['page'] < 1 ) {
				$args['page'] = 1;
			}

			$query['paged'] = $args['page'];
			if ( $query['paged'] !== 1 ) {
				$is_eligible_for_page_handle = false;
			}
		} else {
			if ( $args['offset'] < 0 ) {
				$args['offset'] = 0;
			}

			$query['offset'] = $args['offset'];
			if ( $query['offset'] !== 0 ) {
				$is_eligible_for_page_handle = false;
			}
		}

		if ( isset( $args['page_handle'] ) ) {
			$page_handle = wp_parse_args( $args['page_handle'] );
			if ( isset( $page_handle['value'] ) && isset( $page_handle['id'] ) ) {
				// we have a valid looking page handle
				$this->page_handle = $page_handle;
				add_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
			}
		}

		if ( $this->date_range ) {
			add_filter( 'posts_where', array( $this, 'handle_date_range' ) );
		}

		$this->performed_query = $query;
		add_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );

		$media = new WP_Query( $query );

		remove_filter( 'posts_orderby', array( $this, 'handle_orderby_for_page_handle' ) );

		if ( $this->date_range ) {
			remove_filter( 'posts_where', array( $this, 'handle_date_range' ) );
			$this->date_range = array();
		}

		if ( $this->page_handle ) {
			remove_filter( 'posts_where', array( $this, 'handle_where_for_page_handle' ) );
		}

		$response = array();

		foreach ( $media->posts as $item ) {
			$response[] = $this->get_media_item_v1_1( $item->ID );
		}

		$return = array(
			'found' => (int) $media->found_posts,
			'media' => $response
		);

		if ( $is_eligible_for_page_handle && $return['media'] ) {
			$last_post = end( $return['media'] );
			reset( $return['media'] );

			if ( ( $return['found'] > count( $return['media'] ) ) && $last_post ) {
				$return['meta'] = array();
				$return['meta']['next_page'] = $this->build_page_handle( $last_post, $query );
			}
		}

		return $return;
	}

	function build_page_handle( $post, $query ) {
		$column = $query['orderby'];
		if ( ! $column ) {
			$column = 'date';
		}
		return build_query( array( 'value' => urlencode( $post->$column ), 'id' => $post->ID ) );
	}

	function handle_where_for_page_handle( $where ) {
		global $wpdb;

		$column = $this->performed_query['orderby'];
		if ( ! $column ) {
			$column = 'date';
		}
		$order = $this->performed_query['order'];
		if ( ! $order ) {
			$order = 'DESC';
		}

		if ( ! in_array( $column, array( 'ID', 'title', 'date', 'modified', 'comment_count' ) ) ) {
			return $where;
		}

		if ( ! in_array( $order, array( 'DESC', 'ASC' ) ) ) {
			return $where;
		}

		$db_column = '';
		$db_value = '';
		switch( $column ) {
			case 'ID':
				$db_column = 'ID';
				$db_value = '%d';
				break;
			case 'title':
				$db_column = 'post_title';
				$db_value = '%s';
				break;
			case 'date':
				$db_column = 'post_date';
				$db_value = 'CAST( %s as DATETIME )';
				break;
			case 'modified':
				$db_column = 'post_modified';
				$db_value = 'CAST( %s as DATETIME )';
				break;
			case 'comment_count':
				$db_column = 'comment_count';
				$db_value = '%d';
				break;
		}

		if ( 'DESC'=== $order ) {
			$db_order = '<';
		} else {
			$db_order = '>';
		}

		// Add a clause that limits the results to items beyond the passed item, or equivalent to the passed item
		// but with an ID beyond the passed item. When we're ordering by the ID already, we only ask for items
		// beyond the passed item.
		$where .= $wpdb->prepare( " AND ( ( `$wpdb->posts`.`$db_column` $db_order $db_value ) ", $this->page_handle['value'] );
		if ( $db_column !== 'ID' ) {
			$where .= $wpdb->prepare( "OR ( `$wpdb->posts`.`$db_column` = $db_value AND `$wpdb->posts`.ID $db_order %d )", $this->page_handle['value'], $this->page_handle['id'] );
		}
		$where .= ' )';

		return $where;
	}

	function handle_date_range( $where ) {
		global $wpdb;

		switch ( count( $this->date_range ) ) {
		case 2 :
			$where .= $wpdb->prepare(
				" AND `$wpdb->posts`.post_date BETWEEN CAST( %s AS DATETIME ) AND CAST( %s AS DATETIME ) ",
				$this->date_range['after'],
				$this->date_range['before']
			);
			break;
		case 1 :
			if ( isset( $this->date_range['before'] ) ) {
				$where .= $wpdb->prepare(
					" AND `$wpdb->posts`.post_date <= CAST( %s AS DATETIME ) ",
					$this->date_range['before']
				);
			} else {
				$where .= $wpdb->prepare(
					" AND `$wpdb->posts`.post_date >= CAST( %s AS DATETIME ) ",
					$this->date_range['after']
				);
			}
			break;
		}

		return $where;
	}

	function handle_orderby_for_page_handle( $orderby ) {
		global $wpdb;
		if ( $this->performed_query['orderby'] === 'ID' ) {
			// bail if we're already ordering by ID
			return $orderby;
		}

		if ( $orderby ) {
			$orderby .= ' ,';
		}
		$order = $this->performed_query['order'];
		if ( ! $order ) {
			$order = 'DESC';
		}
		$orderby .= " `$wpdb->posts`.ID $order";
		return $orderby;
	}

}