<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[2268] 2013/rmccue/trunk: First pass at media</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://gsoc.trac.wordpress.org/changeset/2268">2268</a></dd>
<dt>Author</dt> <dd>rmccue</dd>
<dt>Date</dt> <dd>2013-09-10 18:32:12 +0000 (Tue, 10 Sep 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>First pass at media

See <a href="http://gsoc.trac.wordpress.org/ticket/272">#272</a>. This has been a long time coming, and it's finally at a point where
I'm happy to push it out. Good luck.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#2013rmccuetrunklibclasswpjsonpostsphp">2013/rmccue/trunk/lib/class-wp-json-posts.php</a></li>
<li><a href="#2013rmccuetrunklibclasswpjsonserverphp">2013/rmccue/trunk/lib/class-wp-json-server.php</a></li>
<li><a href="#2013rmccuetrunkpluginphp">2013/rmccue/trunk/plugin.php</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#2013rmccuetrunklibclasswpjsonmediaphp">2013/rmccue/trunk/lib/class-wp-json-media.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="2013rmccuetrunklibclasswpjsonmediaphp"></a>
<div class="addfile"><h4>Added: 2013/rmccue/trunk/lib/class-wp-json-media.php (0 => 2268)</h4>
<pre class="diff"><span>
<span class="info">--- 2013/rmccue/trunk/lib/class-wp-json-media.php                            (rev 0)
+++ 2013/rmccue/trunk/lib/class-wp-json-media.php       2013-09-10 18:32:12 UTC (rev 2268)
</span><span class="lines">@@ -0,0 +1,234 @@
</span><ins>+<?php
+
+class WP_JSON_Media extends WP_JSON_Posts {
+       /**
+        * Retrieve pages
+        *
+        * Overrides the $type to set to 'attachment', then passes through to the post
+        * endpoints.
+        *
+        * @see WP_JSON_Posts::getPosts()
+        */
+       public function getPosts( $filter = array(), $context = 'view', $type = 'attachment', $page = 1 ) {
+               if ( $type !== 'attachment' )
+                       return new WP_Error( 'json_post_invalid_type', __( 'Invalid post type' ), array( 'status' => 400 ) );
+
+               return parent::getPosts( $filter, $context, 'attachment', $page );
+       }
+
+       /**
+        * Retrieve a attachment
+        *
+        * @see WP_JSON_Posts::getPost()
+        */
+       public function getPost( $id, $context = 'view' ) {
+               global $wp_json_server;
+               $id = (int) $id;
+
+               if ( empty( $id ) )
+                       return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
+
+               $post = get_post( $id, ARRAY_A );
+
+               if ( $post['post_type'] !== 'attachment' )
+                       return new WP_Error( 'json_post_invalid_type', __( 'Invalid post type' ), array( 'status' => 400 ) );
+
+               return parent::getPost( $id, $context );
+       }
+
+       /**
+        * Get attachment-specific data
+        *
+        * @param array $post
+        * @return array
+        */
+       public function prepare_post( $post, $fields, $context = 'single' ) {
+               $data = parent::prepare_post( $post, $fields, $context );
+
+               // $thumbnail_size = current_theme_supports( 'post-thumbnail' ) ? 'post-thumbnail' : 'thumbnail';
+               $data['source'] = wp_get_attachment_url( $post['ID'] );
+               $data['is_image'] = wp_attachment_is_image( $post['ID'] );
+
+               $data['attachment_meta'] = wp_get_attachment_metadata( $post['ID'] );
+
+               if ( ! empty( $data['attachment_meta']['sizes'] ) ) {
+                       $img_url_basename = wp_basename( $data['source'] );
+
+                       foreach ($data['attachment_meta']['sizes'] as $size => &$size_data) {
+                               // Use the same method image_downsize() does
+                               $size_data['url'] = str_replace( $img_url_basename, $size_data['file'], $data['source'] );
+                       }
+               }
+
+               return $data;
+       }
+
+       /**
+        * Edit a attachment
+        *
+        * @see WP_JSON_Posts::editPost()
+        */
+       public function editPost( $id, $data, $_headers = array() ) {
+               $id = (int) $id;
+               if ( empty( $id ) )
+                       return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
+
+               $post = get_post( $id, ARRAY_A );
+
+               if ( empty( $post['ID'] ) )
+                       return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
+
+               if ( $post['post_type'] !== 'attachment' )
+                       return new WP_Error( 'json_post_invalid_type', __( 'Invalid post type' ), array( 'status' => 400 ) );
+
+               return parent::editPost( $id, $data, $_headers );
+       }
+
+       /**
+        * Delete a attachment
+        *
+        * @see WP_JSON_Posts::deletePost()
+        */
+       public function deletePost( $id, $force = false ) {
+               $id = (int) $id;
+
+               if ( empty( $id ) )
+                       return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
+
+               $post = get_post( $id, ARRAY_A );
+
+               if ( $post['post_type'] !== 'attachment' )
+                       return new WP_Error( 'json_post_invalid_type', __( 'Invalid post type' ), array( 'status' => 400 ) );
+
+               return parent::deletePost( $id, $force );
+       }
+
+       public function uploadAttachment( $_files, $_headers ) {
+               global $wp_json_server;
+
+               if ( empty( $_files ) ) {
+                       $file = $this->uploadFromData( $_files, $_headers );
+                       if ( is_wp_error( $file ) )
+                               return $file;
+               }
+               else {
+                       if ( empty( $_files['file'] ) )
+                               return new WP_Error( 'json_upload_no_data', __( 'No data supplied' ), array( 'status' => 400 ) );
+
+                       $overrides = array(
+                               'test_form' => false,
+                       );
+                       $file = wp_handle_upload( $_files['file'], $overrides );
+
+                       if ( isset($file['error']) )
+                               return new WP_Error( 'json_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
+               }
+
+               $name = basename( $file['file'] );
+               $name_parts = pathinfo( $name );
+               $name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
+
+               $url = $file['url'];
+               $type = $file['type'];
+               $file = $file['file'];
+               $title = $name;
+               $content = '';
+
+               // use image exif/iptc data for title and caption defaults if possible
+               if ( $image_meta = @wp_read_image_metadata($file) ) {
+                       if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
+                               $title = $image_meta['title'];
+                       if ( trim( $image_meta['caption'] ) )
+                               $content = $image_meta['caption'];
+               }
+
+               // Construct the attachment array
+               $post_data = array();
+               $attachment = array(
+                       'post_mime_type' => $type,
+                       'guid' => $url,
+                       // 'post_parent' => $post_id,
+                       'post_title' => $title,
+                       'post_content' => $content,
+               );
+
+               // This should never be set as it would then overwrite an existing attachment.
+               if ( isset( $attachment['ID'] ) )
+                       unset( $attachment['ID'] );
+
+               // Save the data
+               $id = wp_insert_attachment($attachment, $file /*, $post_id */);
+               if ( !is_wp_error($id) ) {
+                       wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
+               }
+
+               return $id;
+       }
+
+       protected function uploadFromData( $_files, $_headers ) {
+               global $wp_json_server;
+               $data = $wp_json_server->get_raw_data();
+
+               if ( empty( $data ) ) {
+                       return new WP_Error( 'json_upload_no_data', __( 'No data supplied' ), array( 'status' => 400 ) );
+               }
+
+               if ( empty( $_headers['CONTENT_TYPE'] ) ) {
+                       return new WP_Error( 'json_upload_no_type', __( 'No Content-Type supplied' ), array( 'status' => 400 ) );
+               }
+
+               if ( empty( $_headers['CONTENT_DISPOSITION'] ) ) {
+                       return new WP_Error( 'json_upload_no_disposition', __( 'No Content-Disposition supplied' ), array( 'status' => 400 ) );
+               }
+
+               // Get the filename
+               $disposition_parts = explode(';', $_headers['CONTENT_DISPOSITION']);
+               $filename = null;
+               foreach ($disposition_parts as $part) {
+                       $part = trim($part);
+
+                       if (strpos($part, 'filename') !== 0)
+                               continue;
+
+                       $filenameparts = explode('=', $part);
+                       $filename = trim($filenameparts[1]);
+               }
+
+               if ( empty( $filename ) ) {
+                       return new WP_Error( 'json_upload_invalid_disposition', __( 'Invalid Content-Disposition supplied' ), array( 'status' => 400 ) );
+               }
+
+               // Get the content-type
+               $type = $_headers['CONTENT_TYPE'];
+
+               // Save the file
+               $tmpfname = wp_tempnam( $filename );
+
+               $fp = fopen( $tmpfname, 'w+' );
+               if ( ! $fp ) {
+                       return new WP_Error( 'json_upload_file_error', __( 'Could not open file handle' ), array( 'status' => 500 ) );
+               }
+
+               fwrite( $fp, $data );
+               fclose( $fp );
+
+               // Now, sideload it in
+               $file_data = array(
+                       'error' => null,
+                       'tmp_name' => $tmpfname,
+                       'name' => $filename,
+                       'type' => $type,
+               );
+               $overrides = array(
+                       'test_form' => false,
+               );
+               $sideloaded = wp_handle_sideload( $file_data, $overrides );
+
+               if ( isset( $sideloaded['error'] ) ) {
+                       @unlink( $tmpfname );
+                       return new WP_Error( 'json_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
+               }
+
+               return $sideloaded;
+       }
+}
</ins><span class="cx">\ No newline at end of file
</span><span class="cx">Property changes on: 2013/rmccue/trunk/lib/class-wp-json-media.php
</span><span class="cx">___________________________________________________________________
</span></span></pre></div>
<a id="svnexecutable"></a>
<div class="addfile"><h4>Added: svn:executable</h4></div>
<ins>+*
</ins><span class="cx">\ No newline at end of property
</span><a id="2013rmccuetrunklibclasswpjsonpostsphp"></a>
<div class="modfile"><h4>Modified: 2013/rmccue/trunk/lib/class-wp-json-posts.php (2267 => 2268)</h4>
<pre class="diff"><span>
<span class="info">--- 2013/rmccue/trunk/lib/class-wp-json-posts.php    2013-09-10 18:32:06 UTC (rev 2267)
+++ 2013/rmccue/trunk/lib/class-wp-json-posts.php       2013-09-10 18:32:12 UTC (rev 2268)
</span><span class="lines">@@ -457,12 +457,11 @@
</span><span class="cx">          }
</span><span class="cx"> 
</span><span class="cx">          // Thumbnail
</span><del>-               /*$post_fields_extended['post_thumbnail'] = array();
</del><ins>+                $post_fields_extended['featured_image'] = null;
</ins><span class="cx">           $thumbnail_id = get_post_thumbnail_id( $post['ID'] );
</span><span class="cx">          if ( $thumbnail_id ) {
</span><del>-                       $thumbnail_size = current_theme_supports( 'post-thumbnail' ) ? 'post-thumbnail' : 'thumbnail';
-                       $post_fields_extended['post_thumbnail'] = $this->_prepare_media_item( get_post( $thumbnail_id ), $thumbnail_size );
-               }*/
</del><ins>+                        $post_fields_extended['featured_image'] = $GLOBALS['wp_json_media']->getAttachment( $thumbnail_id, 'child' );
+               }
</ins><span class="cx"> 
</span><span class="cx">          // Consider future posts as published
</span><span class="cx">          if ( $post_fields['status'] === 'future' )
</span></span></pre></div>
<a id="2013rmccuetrunklibclasswpjsonserverphp"></a>
<div class="modfile"><h4>Modified: 2013/rmccue/trunk/lib/class-wp-json-server.php (2267 => 2268)</h4>
<pre class="diff"><span>
<span class="info">--- 2013/rmccue/trunk/lib/class-wp-json-server.php   2013-09-10 18:32:06 UTC (rev 2267)
+++ 2013/rmccue/trunk/lib/class-wp-json-server.php      2013-09-10 18:32:12 UTC (rev 2268)
</span><span class="lines">@@ -31,6 +31,7 @@
</span><span class="cx">  /**
</span><span class="cx">   * Does the endpoint accept raw JSON entities?
</span><span class="cx">   */
</span><ins>+       const ACCEPT_RAW = 64;
</ins><span class="cx">   const ACCEPT_JSON = 128;
</span><span class="cx"> 
</span><span class="cx">  /**
</span><span class="lines">@@ -214,6 +215,7 @@
</span><span class="cx">  public function getRoutes() {
</span><span class="cx">          $GLOBALS['wp_json_posts'] = $posts = new WP_JSON_Posts();
</span><span class="cx">          $GLOBALS['wp_json_pages'] = $pages = new WP_JSON_Pages();
</span><ins>+               $GLOBALS['wp_json_media'] = $media = new WP_JSON_Media();
</ins><span class="cx"> 
</span><span class="cx">          $endpoints = array(
</span><span class="cx">                  // Meta endpoints
</span><span class="lines">@@ -306,6 +308,17 @@
</span><span class="cx">                          array( '__return_null', self::READABLE ),
</span><span class="cx">                          array( '__return_null', self::CREATABLE | self::ACCEPT_JSON ),
</span><span class="cx">                  ),
</span><ins>+
+                       '/media' => array(
+                               array( array( $media, 'getPosts' ),   self::READABLE ),
+                               array( array( $media, 'uploadAttachment' ), self::CREATABLE ),
+                       ),
+
+                       '/media/(?P<id>\d+)' => array(
+                               array( array( $media, 'getPost' ),    self::READABLE ),
+                               array( array( $media, 'editPost' ),   self::EDITABLE ),
+                               array( array( $media, 'deletePost' ), self::DELETABLE ),
+                       ),
</ins><span class="cx">           );
</span><span class="cx"> 
</span><span class="cx">          $endpoints = apply_filters( 'json_endpoints', $endpoints );
</span><span class="lines">@@ -375,11 +388,15 @@
</span><span class="cx">                                  $data = json_decode( $this->get_raw_data(), true );
</span><span class="cx">                                  $args = array_merge( $args, array( 'data' => $data ) );
</span><span class="cx">                          }
</span><ins>+                               elseif ( $supported & self::ACCEPT_RAW ) {
+                                       $data = $this->get_raw_data();
+                               }
</ins><span class="cx"> 
</span><span class="cx">                          $args['_method']  = $method;
</span><span class="cx">                          $args['_route']   = $route;
</span><span class="cx">                          $args['_path']    = $path;
</span><span class="cx">                          $args['_headers'] = $this->get_headers( $_SERVER );
</span><ins>+                               $args['_files']   = $_FILES;
</ins><span class="cx"> 
</span><span class="cx">                          $args = apply_filters( 'json_dispatch_args', $args, $callback );
</span><span class="cx"> 
</span></span></pre></div>
<a id="2013rmccuetrunkpluginphp"></a>
<div class="modfile"><h4>Modified: 2013/rmccue/trunk/plugin.php (2267 => 2268)</h4>
<pre class="diff"><span>
<span class="info">--- 2013/rmccue/trunk/plugin.php     2013-09-10 18:32:06 UTC (rev 2267)
+++ 2013/rmccue/trunk/plugin.php        2013-09-10 18:32:12 UTC (rev 2268)
</span><span class="lines">@@ -32,6 +32,7 @@
</span><span class="cx">  include_once( dirname( __FILE__ ) . '/lib/class-wp-json-server.php' );
</span><span class="cx">  include_once( dirname( __FILE__ ) . '/lib/class-wp-json-posts.php' );
</span><span class="cx">  include_once( dirname( __FILE__ ) . '/lib/class-wp-json-pages.php' );
</span><ins>+       include_once( dirname( __FILE__ ) . '/lib/class-wp-json-media.php' );
</ins><span class="cx"> 
</span><span class="cx">  /**
</span><span class="cx">   * Whether this is a XMLRPC Request
</span></span></pre>
</div>
</div>

</body>
</html>