class.wpcom-json-api-list-media-endpoint.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. new WPCOM_JSON_API_List_Media_Endpoint( array(
  3. 'description' => 'Get a list of items in the media library.',
  4. 'group' => 'media',
  5. 'stat' => 'media',
  6. 'method' => 'GET',
  7. 'path' => '/sites/%s/media/',
  8. 'deprecated' => true,
  9. 'new_version' => '1.1',
  10. 'max_version' => '1',
  11. 'path_labels' => array(
  12. '$site' => '(int|string) Site ID or domain',
  13. ),
  14. 'query_parameters' => array(
  15. 'number' => '(int=20) The number of media items to return. Limit: 100.',
  16. 'offset' => '(int=0) 0-indexed offset.',
  17. 'parent_id' => '(int) Default is showing all items. The post where the media item is attached. 0 shows unattached media items.',
  18. '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).",
  19. ),
  20. 'response_format' => array(
  21. 'media' => '(array) Array of media',
  22. 'found' => '(int) The number of total results found'
  23. ),
  24. 'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/82974409/media/?number=2',
  25. 'example_request_data' => array(
  26. 'headers' => array(
  27. 'authorization' => 'Bearer YOUR_API_TOKEN'
  28. )
  29. )
  30. ) );
  31. class WPCOM_JSON_API_List_Media_Endpoint extends WPCOM_JSON_API_Endpoint {
  32. function callback( $path = '', $blog_id = 0 ) {
  33. $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
  34. if ( is_wp_error( $blog_id ) ) {
  35. return $blog_id;
  36. }
  37. //upload_files can probably be used for other endpoints but we want contributors to be able to use media too
  38. if ( !current_user_can( 'edit_posts' ) ) {
  39. return new WP_Error( 'unauthorized', 'User cannot view media', 403 );
  40. }
  41. $args = $this->query_args();
  42. if ( $args['number'] < 1 ) {
  43. $args['number'] = 20;
  44. } elseif ( 100 < $args['number'] ) {
  45. return new WP_Error( 'invalid_number', 'The NUMBER parameter must be less than or equal to 100.', 400 );
  46. }
  47. $media = get_posts( array(
  48. 'post_type' => 'attachment',
  49. 'post_parent' => $args['parent_id'],
  50. 'offset' => $args['offset'],
  51. 'numberposts' => $args['number'],
  52. 'post_mime_type' => $args['mime_type']
  53. ) );
  54. $response = array();
  55. foreach ( $media as $item ) {
  56. $response[] = $this->get_media_item( $item->ID );
  57. }
  58. $_num = (array) wp_count_attachments();
  59. $_total_media = array_sum( $_num ) - $_num['trash'];
  60. $return = array(
  61. 'found' => $_total_media,
  62. 'media' => $response
  63. );
  64. return $return;
  65. }
  66. }