From 86c1e5f82bc77fe676062d542b3012331ae4e491 Mon Sep 17 00:00:00 2001 From: Dan Phiffer Date: Fri, 25 Mar 2011 12:22:44 -0400 Subject: [PATCH] Initial commit --- controllers/core.php | 334 ++++++++ controllers/posts.php | 34 + controllers/respond.php | 27 + json-api.php | 83 ++ library/JSON.php | 861 +++++++++++++++++++ models/attachment.php | 56 ++ models/author.php | 62 ++ models/category.php | 29 + models/comment.php | 80 ++ models/post.php | 283 +++++++ models/tag.php | 26 + readme.txt | 1117 +++++++++++++++++++++++++ screenshot-1.png | Bin 0 -> 23452 bytes singletons/api.php | 371 ++++++++ singletons/introspector.php | 299 +++++++ singletons/query.php | 194 +++++ singletons/response.php | 184 ++++ tests/core.get_author_index-01.phpt | 14 + tests/core.get_author_posts-01.phpt | 14 + tests/core.get_author_posts-02.phpt | 14 + tests/core.get_author_posts-03.phpt | 14 + tests/core.get_author_posts-04.phpt | 14 + tests/core.get_category_index-01.phpt | 14 + tests/core.get_category_posts-01.phpt | 14 + tests/core.get_date_index-01.phpt | 14 + tests/core.get_date_posts-01.phpt | 14 + tests/core.get_date_posts-02.phpt | 14 + tests/core.get_date_posts-03.phpt | 14 + tests/core.get_page-01.phpt | 14 + tests/core.get_page-02.phpt | 14 + tests/core.get_post-01.phpt | 14 + tests/core.get_recent_posts-01.phpt | 14 + tests/core.get_recent_posts-02.phpt | 14 + tests/core.get_recent_posts-03.phpt | 14 + tests/core.get_search_posts-01.phpt | 14 + tests/core.get_tag_index-01.phpt | 14 + tests/core.get_tag_posts-01.phpt | 14 + tests/core.info-01.phpt | 14 + tests/core.info-02.phpt | 14 + tests/query-01.phpt | 14 + 40 files changed, 4362 insertions(+) create mode 100644 controllers/core.php create mode 100644 controllers/posts.php create mode 100644 controllers/respond.php create mode 100644 json-api.php create mode 100644 library/JSON.php create mode 100644 models/attachment.php create mode 100644 models/author.php create mode 100644 models/category.php create mode 100644 models/comment.php create mode 100644 models/post.php create mode 100644 models/tag.php create mode 100644 readme.txt create mode 100644 screenshot-1.png create mode 100644 singletons/api.php create mode 100644 singletons/introspector.php create mode 100644 singletons/query.php create mode 100644 singletons/response.php create mode 100644 tests/core.get_author_index-01.phpt create mode 100644 tests/core.get_author_posts-01.phpt create mode 100644 tests/core.get_author_posts-02.phpt create mode 100644 tests/core.get_author_posts-03.phpt create mode 100644 tests/core.get_author_posts-04.phpt create mode 100644 tests/core.get_category_index-01.phpt create mode 100644 tests/core.get_category_posts-01.phpt create mode 100644 tests/core.get_date_index-01.phpt create mode 100644 tests/core.get_date_posts-01.phpt create mode 100644 tests/core.get_date_posts-02.phpt create mode 100644 tests/core.get_date_posts-03.phpt create mode 100644 tests/core.get_page-01.phpt create mode 100644 tests/core.get_page-02.phpt create mode 100644 tests/core.get_post-01.phpt create mode 100644 tests/core.get_recent_posts-01.phpt create mode 100644 tests/core.get_recent_posts-02.phpt create mode 100644 tests/core.get_recent_posts-03.phpt create mode 100644 tests/core.get_search_posts-01.phpt create mode 100644 tests/core.get_tag_index-01.phpt create mode 100644 tests/core.get_tag_posts-01.phpt create mode 100644 tests/core.info-01.phpt create mode 100644 tests/core.info-02.phpt create mode 100644 tests/query-01.phpt diff --git a/controllers/core.php b/controllers/core.php new file mode 100644 index 0000000..a3dda64 --- /dev/null +++ b/controllers/core.php @@ -0,0 +1,334 @@ +query->controller)) { + return $json_api->controller_info($json_api->query->controller); + } else { + $dir = json_api_dir(); + if (file_exists("$dir/json-api.php")) { + $php = file_get_contents("$dir/json-api.php"); + } else { + // Check one directory up, in case json-api.php was moved + $dir = dirname($dir); + if (file_exists("$dir/json-api.php")) { + $php = file_get_contents("$dir/json-api.php"); + } + } + if (preg_match('/^\s*Version:\s*(.+)$/m', $php, $matches)) { + $version = $matches[1]; + } else { + $version = '(Unknown)'; + } + $active_controllers = explode(',', get_option('json_api_controllers', 'core')); + $controllers = array_intersect($json_api->get_controllers(), $active_controllers); + return array( + 'json_api_version' => $version, + 'controllers' => array_values($controllers) + ); + } + } + + public function get_recent_posts() { + global $json_api; + $posts = $json_api->introspector->get_posts(); + return $this->posts_result($posts); + } + + public function get_post() { + global $json_api, $post; + extract($json_api->query->get(array('id', 'slug', 'post_id', 'post_slug'))); + if ($id || $post_id) { + if (!$id) { + $id = $post_id; + } + $posts = $json_api->introspector->get_posts(array( + 'p' => $id + ), true); + } else if ($slug || $post_slug) { + if (!$slug) { + $slug = $post_slug; + } + $posts = $json_api->introspector->get_posts(array( + 'name' => $slug + ), true); + } else { + $json_api->error("Include 'id' or 'slug' var in your request."); + } + if (count($posts) == 1) { + $post = $posts[0]; + $previous = get_adjacent_post(false, '', true); + $next = get_adjacent_post(false, '', false); + $post = new JSON_API_Post($post); + $response = array( + 'post' => $post + ); + if ($previous) { + $response['previous_url'] = get_permalink($previous->ID); + } + if ($next) { + $response['next_url'] = get_permalink($next->ID); + } + return $response; + } else { + $json_api->error("Not found."); + } + } + + public function get_page() { + global $json_api; + extract($json_api->query->get(array('id', 'slug', 'page_id', 'page_slug', 'children'))); + if ($id || $page_id) { + if (!$id) { + $id = $page_id; + } + $posts = $json_api->introspector->get_posts(array( + 'page_id' => $id + )); + } else if ($slug || $page_slug) { + if (!$slug) { + $slug = $page_slug; + } + $posts = $json_api->introspector->get_posts(array( + 'pagename' => $slug + )); + } else { + $json_api->error("Include 'id' or 'slug' var in your request."); + } + + // Workaround for https://core.trac.wordpress.org/ticket/12647 + if (empty($posts)) { + $url = $_SERVER['REQUEST_URI']; + $parsed_url = parse_url($url); + $path = $parsed_url['path']; + if (preg_match('#^http://[^/]+(/.+)$#', get_bloginfo('url'), $matches)) { + $blog_root = $matches[1]; + $path = preg_replace("#^$blog_root#", '', $path); + } + if (substr($path, 0, 1) == '/') { + $path = substr($path, 1); + } + $posts = $json_api->introspector->get_posts(array('pagename' => $path)); + } + + if (count($posts) == 1) { + if (!empty($children)) { + $json_api->introspector->attach_child_posts($posts[0]); + } + return array( + 'page' => $posts[0] + ); + } else { + $json_api->error("Not found."); + } + } + + public function get_date_posts() { + global $json_api; + if ($json_api->query->date) { + $date = preg_replace('/\D/', '', $json_api->query->date); + if (!preg_match('/^\d{4}(\d{2})?(\d{2})?$/', $date)) { + $json_api->error("Specify a date var in one of 'YYYY' or 'YYYY-MM' or 'YYYY-MM-DD' formats."); + } + $request = array('year' => substr($date, 0, 4)); + if (strlen($date) > 4) { + $request['monthnum'] = (int) substr($date, 4, 2); + } + if (strlen($date) > 6) { + $request['day'] = (int) substr($date, 6, 2); + } + $posts = $json_api->introspector->get_posts($request); + } else { + $json_api->error("Include 'date' var in your request."); + } + return $this->posts_result($posts); + } + + public function get_category_posts() { + global $json_api; + $category = $json_api->introspector->get_current_category(); + if (!$category) { + $json_api->error("Not found."); + } + $posts = $json_api->introspector->get_posts(array( + 'cat' => $category->id + )); + return $this->posts_object_result($posts, $category); + } + + public function get_tag_posts() { + global $json_api; + $tag = $json_api->introspector->get_current_tag(); + if (!$tag) { + $json_api->error("Not found."); + } + $posts = $json_api->introspector->get_posts(array( + 'tag' => $tag->slug + )); + return $this->posts_object_result($posts, $tag); + } + + public function get_author_posts() { + global $json_api; + $author = $json_api->introspector->get_current_author(); + if (!$author) { + $json_api->error("Not found."); + } + $posts = $json_api->introspector->get_posts(array( + 'author' => $author->id + )); + return $this->posts_object_result($posts, $author); + } + + public function get_search_results() { + global $json_api; + if ($json_api->query->search) { + $posts = $json_api->introspector->get_posts(array( + 's' => $json_api->query->search + )); + } else { + $json_api->error("Include 'search' var in your request."); + } + return $this->posts_result($posts); + } + + public function get_date_index() { + global $json_api; + $permalinks = $json_api->introspector->get_date_archive_permalinks(); + $tree = $json_api->introspector->get_date_archive_tree($permalinks); + return array( + 'permalinks' => $permalinks, + 'tree' => $tree + ); + } + + public function get_category_index() { + global $json_api; + $categories = $json_api->introspector->get_categories(); + return array( + 'count' => count($categories), + 'categories' => $categories + ); + } + + public function get_tag_index() { + global $json_api; + $tags = $json_api->introspector->get_tags(); + return array( + 'count' => count($tags), + 'tags' => $tags + ); + } + + public function get_author_index() { + global $json_api; + $authors = $json_api->introspector->get_authors(); + return array( + 'count' => count($authors), + 'authors' => array_values($authors) + ); + } + + public function get_page_index() { + global $json_api; + $pages = array(); + // Thanks to blinder for the fix! + $numberposts = empty($json_api->query->count) ? -1 : $json_api->query->count; + $wp_posts = get_posts(array( + 'post_type' => 'page', + 'post_parent' => 0, + 'order' => 'ASC', + 'orderby' => 'menu_order', + 'numberposts' => $numberposts + )); + foreach ($wp_posts as $wp_post) { + $pages[] = new JSON_API_Post($wp_post); + } + foreach ($pages as $page) { + $json_api->introspector->attach_child_posts($page); + } + return array( + 'pages' => $pages + ); + } + + public function get_nonce() { + global $json_api; + extract($json_api->query->get(array('controller', 'method'))); + if ($controller && $method) { + $controller = strtolower($controller); + if (!in_array($controller, $json_api->get_controllers())) { + $json_api->error("Unknown controller '$controller'."); + } + require_once $json_api->controller_path($controller); + if (!method_exists($json_api->controller_class($controller), $method)) { + $json_api->error("Unknown method '$method'."); + } + $nonce_id = $json_api->get_nonce_id($controller, $method); + return array( + 'controller' => $controller, + 'method' => $method, + 'nonce' => wp_create_nonce($nonce_id) + ); + } else { + $json_api->error("Include 'controller' and 'method' vars in your request."); + } + } + + protected function get_object_posts($object, $id_var, $slug_var) { + global $json_api; + $object_id = "{$type}_id"; + $object_slug = "{$type}_slug"; + extract($json_api->query->get(array('id', 'slug', $object_id, $object_slug))); + if ($id || $$object_id) { + if (!$id) { + $id = $$object_id; + } + $posts = $json_api->introspector->get_posts(array( + $id_var => $id + )); + } else if ($slug || $$object_slug) { + if (!$slug) { + $slug = $$object_slug; + } + $posts = $json_api->introspector->get_posts(array( + $slug_var => $slug + )); + } else { + $json_api->error("No $type specified. Include 'id' or 'slug' var in your request."); + } + return $posts; + } + + protected function posts_result($posts) { + global $wp_query; + return array( + 'count' => count($posts), + 'count_total' => (int) $wp_query->found_posts, + 'pages' => $wp_query->max_num_pages, + 'posts' => $posts + ); + } + + protected function posts_object_result($posts, $object) { + global $wp_query; + // Convert something like "JSON_API_Category" into "category" + $object_key = strtolower(substr(get_class($object), 9)); + return array( + 'count' => count($posts), + 'pages' => (int) $wp_query->max_num_pages, + $object_key => $object, + 'posts' => $posts + ); + } + +} + +?> diff --git a/controllers/posts.php b/controllers/posts.php new file mode 100644 index 0000000..db8f0ad --- /dev/null +++ b/controllers/posts.php @@ -0,0 +1,34 @@ +error("You need to login with a user capable of creating posts."); + } + if (!$json_api->query->nonce) { + $json_api->error("You must include a 'nonce' value to create posts. Use the `get_nonce` Core API method."); + } + $nonce_id = $json_api->get_nonce_id('posts', 'create_post'); + if (!wp_verify_nonce($json_api->query->nonce, $nonce_id)) { + $json_api->error("Your 'nonce' value was incorrect. Use the 'get_nonce' API method."); + } + nocache_headers(); + $post = new JSON_API_Post(); + $id = $post->create($_REQUEST); + if (empty($id)) { + $json_api->error("Could not create post."); + } + return array( + 'post' => $post + ); + } + +} + +?> diff --git a/controllers/respond.php b/controllers/respond.php new file mode 100644 index 0000000..20ac91e --- /dev/null +++ b/controllers/respond.php @@ -0,0 +1,27 @@ +error("No post specified. Include 'post_id' var in your request."); + } else if (empty($_REQUEST['name']) || + empty($_REQUEST['email']) || + empty($_REQUEST['content'])) { + $json_api->error("Please include all required arguments (name, email, content)."); + } else if (!is_email($_REQUEST['email'])) { + $json_api->error("Please enter a valid email address."); + } + $pending = new JSON_API_Comment(); + return $pending->handle_submission(); + } + +} + +?> diff --git a/json-api.php b/json-api.php new file mode 100644 index 0000000..5249ad4 --- /dev/null +++ b/json-api.php @@ -0,0 +1,83 @@ +

Sorry, JSON API requires PHP version 5.0 or greater.

"; +} + +function json_api_class_warning() { + echo "

Oops, JSON_API class not found. If you've defined a JSON_API_DIR constant, double check that the path is correct.

"; +} + +function json_api_activation() { + // Add the rewrite rule on activation + global $wp_rewrite; + add_filter('rewrite_rules_array', 'json_api_rewrites'); + $wp_rewrite->flush_rules(); +} + +function json_api_deactivation() { + // Remove the rewrite rule on deactivation + global $wp_rewrite; + $wp_rewrite->flush_rules(); +} + +function json_api_rewrites($wp_rules) { + $base = get_option('json_api_base', 'api'); + if (empty($base)) { + return $wp_rules; + } + $json_api_rules = array( + "$base\$" => 'index.php?json=info', + "$base/(.+)\$" => 'index.php?json=$matches[1]' + ); + return array_merge($json_api_rules, $wp_rules); +} + +function json_api_dir() { + if (defined('JSON_API_DIR') && file_exists(JSON_API_DIR)) { + return JSON_API_DIR; + } else { + return dirname(__FILE__); + } +} + +// Add initialization and activation hooks +add_action('init', 'json_api_init'); +register_activation_hook("$dir/json-api.php", 'json_api_activation'); +register_deactivation_hook("$dir/json-api.php", 'json_api_deactivation'); + +?> diff --git a/library/JSON.php b/library/JSON.php new file mode 100644 index 0000000..ac3c835 --- /dev/null +++ b/library/JSON.php @@ -0,0 +1,861 @@ + + * @author Matt Knapp + * @author Brett Stimmerman + * @copyright 2005 Michal Migurski + * @version CVS: $Id: JSON.php 288200 2009-09-09 15:41:29Z alan_k $ + * @license http://www.opensource.org/licenses/bsd-license.php + * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 + */ + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_SLICE', 1); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_STR', 2); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_ARR', 3); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_OBJ', 4); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_CMT', 5); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_LOOSE_TYPE', 16); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_SUPPRESS_ERRORS', 32); + +/** + * Converts to and from JSON format. + * + * Brief example of use: + * + * + * // create a new instance of Services_JSON + * $json = new Services_JSON(); + * + * // convert a complexe value to JSON notation, and send it to the browser + * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); + * $output = $json->encode($value); + * + * print($output); + * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] + * + * // accept incoming POST data, assumed to be in JSON notation + * $input = file_get_contents('php://input', 1000000); + * $value = $json->decode($input); + * + */ +class Services_JSON +{ + /** + * constructs a new JSON instance + * + * @param int $use object behavior flags; combine with boolean-OR + * + * possible values: + * - SERVICES_JSON_LOOSE_TYPE: loose typing. + * "{...}" syntax creates associative arrays + * instead of objects in decode(). + * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. + * Values which can't be encoded (e.g. resources) + * appear as NULL instead of throwing errors. + * By default, a deeply-nested resource will + * bubble up with an error, so all return values + * from encode() should be checked with isError() + */ + function Services_JSON($use = 0) + { + $this->use = $use; + } + + /** + * convert a string from one UTF-16 char to one UTF-8 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf16 UTF-16 character + * @return string UTF-8 character + * @access private + */ + function utf162utf8($utf16) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); + } + + $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); + + switch(true) { + case ((0x7F & $bytes) == $bytes): + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x7F & $bytes); + + case (0x07FF & $bytes) == $bytes: + // return a 2-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xC0 | (($bytes >> 6) & 0x1F)) + . chr(0x80 | ($bytes & 0x3F)); + + case (0xFFFF & $bytes) == $bytes: + // return a 3-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xE0 | (($bytes >> 12) & 0x0F)) + . chr(0x80 | (($bytes >> 6) & 0x3F)) + . chr(0x80 | ($bytes & 0x3F)); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * convert a string from one UTF-8 char to one UTF-16 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf8 UTF-8 character + * @return string UTF-16 character + * @access private + */ + function utf82utf16($utf8) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); + } + + switch(strlen($utf8)) { + case 1: + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return $utf8; + + case 2: + // return a UTF-16 character from a 2-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x07 & (ord($utf8{0}) >> 2)) + . chr((0xC0 & (ord($utf8{0}) << 6)) + | (0x3F & ord($utf8{1}))); + + case 3: + // return a UTF-16 character from a 3-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr((0xF0 & (ord($utf8{0}) << 4)) + | (0x0F & (ord($utf8{1}) >> 2))) + . chr((0xC0 & (ord($utf8{1}) << 6)) + | (0x7F & ord($utf8{2}))); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * encodes an arbitrary variable into JSON format (and sends JSON Header) + * + * @param mixed $var any number, boolean, string, array, or object to be encoded. + * see argument 1 to Services_JSON() above for array-parsing behavior. + * if var is a strng, note that encode() always expects it + * to be in ASCII or UTF-8 format! + * + * @return mixed JSON string representation of input var or an error if a problem occurs + * @access public + */ + function encode($var) + { + header('Content-type: application/json'); + return $this->_encode($var); + } + /** + * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow CSS!!!!) + * + * @param mixed $var any number, boolean, string, array, or object to be encoded. + * see argument 1 to Services_JSON() above for array-parsing behavior. + * if var is a strng, note that encode() always expects it + * to be in ASCII or UTF-8 format! + * + * @return mixed JSON string representation of input var or an error if a problem occurs + * @access public + */ + function encodeUnsafe($var) + { + return $this->_encode($var); + } + /** + * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format + * + * @param mixed $var any number, boolean, string, array, or object to be encoded. + * see argument 1 to Services_JSON() above for array-parsing behavior. + * if var is a strng, note that encode() always expects it + * to be in ASCII or UTF-8 format! + * + * @return mixed JSON string representation of input var or an error if a problem occurs + * @access public + */ + function _encode($var) + { + + switch (gettype($var)) { + case 'boolean': + return $var ? 'true' : 'false'; + + case 'NULL': + return 'null'; + + case 'integer': + return (int) $var; + + case 'double': + case 'float': + return (float) $var; + + case 'string': + // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT + $ascii = ''; + $strlen_var = strlen($var); + + /* + * Iterate over every character in the string, + * escaping with a slash or encoding to UTF-8 where necessary + */ + for ($c = 0; $c < $strlen_var; ++$c) { + + $ord_var_c = ord($var{$c}); + + switch (true) { + case $ord_var_c == 0x08: + $ascii .= '\b'; + break; + case $ord_var_c == 0x09: + $ascii .= '\t'; + break; + case $ord_var_c == 0x0A: + $ascii .= '\n'; + break; + case $ord_var_c == 0x0C: + $ascii .= '\f'; + break; + case $ord_var_c == 0x0D: + $ascii .= '\r'; + break; + + case $ord_var_c == 0x22: + case $ord_var_c == 0x2F: + case $ord_var_c == 0x5C: + // double quote, slash, slosh + $ascii .= '\\'.$var{$c}; + break; + + case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): + // characters U-00000000 - U-0000007F (same as ASCII) + $ascii .= $var{$c}; + break; + + case (($ord_var_c & 0xE0) == 0xC0): + // characters U-00000080 - U-000007FF, mask 110XXXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + if ($c+1 >= $strlen_var) { + $c += 1; + $ascii .= '?'; + break; + } + + $char = pack('C*', $ord_var_c, ord($var{$c + 1})); + $c += 1; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF0) == 0xE0): + if ($c+2 >= $strlen_var) { + $c += 2; + $ascii .= '?'; + break; + } + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + @ord($var{$c + 1}), + @ord($var{$c + 2})); + $c += 2; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF8) == 0xF0): + if ($c+3 >= $strlen_var) { + $c += 3; + $ascii .= '?'; + break; + } + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3})); + $c += 3; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFC) == 0xF8): + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + if ($c+4 >= $strlen_var) { + $c += 4; + $ascii .= '?'; + break; + } + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4})); + $c += 4; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFE) == 0xFC): + if ($c+5 >= $strlen_var) { + $c += 5; + $ascii .= '?'; + break; + } + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4}), + ord($var{$c + 5})); + $c += 5; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + } + } + return '"'.$ascii.'"'; + + case 'array': + /* + * As per JSON spec if any array key is not an integer + * we must treat the the whole array as an object. We + * also try to catch a sparsely populated associative + * array with numeric keys here because some JS engines + * will create an array with empty indexes up to + * max_index which can cause memory issues and because + * the keys, which may be relevant, will be remapped + * otherwise. + * + * As per the ECMA and JSON specification an object may + * have any string as a property. Unfortunately due to + * a hole in the ECMA specification if the key is a + * ECMA reserved word or starts with a digit the + * parameter is only accessible using ECMAScript's + * bracket notation. + */ + + // treat as a JSON object + if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { + $properties = array_map(array($this, 'name_value'), + array_keys($var), + array_values($var)); + + foreach($properties as $property) { + if(Services_JSON::isError($property)) { + return $property; + } + } + + return '{' . join(',', $properties) . '}'; + } + + // treat it like a regular array + $elements = array_map(array($this, '_encode'), $var); + + foreach($elements as $element) { + if(Services_JSON::isError($element)) { + return $element; + } + } + + return '[' . join(',', $elements) . ']'; + + case 'object': + $vars = get_object_vars($var); + + $properties = array_map(array($this, 'name_value'), + array_keys($vars), + array_values($vars)); + + foreach($properties as $property) { + if(Services_JSON::isError($property)) { + return $property; + } + } + + return '{' . join(',', $properties) . '}'; + + default: + return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) + ? 'null' + : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); + } + } + + /** + * array-walking function for use in generating JSON-formatted name-value pairs + * + * @param string $name name of key to use + * @param mixed $value reference to an array element to be encoded + * + * @return string JSON-formatted name-value pair, like '"name":value' + * @access private + */ + function name_value($name, $value) + { + $encoded_value = $this->_encode($value); + + if(Services_JSON::isError($encoded_value)) { + return $encoded_value; + } + + return $this->_encode(strval($name)) . ':' . $encoded_value; + } + + /** + * reduce a string by removing leading and trailing comments and whitespace + * + * @param $str string string value to strip of comments and whitespace + * + * @return string string value stripped of comments and whitespace + * @access private + */ + function reduce_string($str) + { + $str = preg_replace(array( + + // eliminate single line comments in '// ...' form + '#^\s*//(.+)$#m', + + // eliminate multi-line comments in '/* ... */' form, at start of string + '#^\s*/\*(.+)\*/#Us', + + // eliminate multi-line comments in '/* ... */' form, at end of string + '#/\*(.+)\*/\s*$#Us' + + ), '', $str); + + // eliminate extraneous space + return trim($str); + } + + /** + * decodes a JSON string into appropriate variable + * + * @param string $str JSON-formatted string + * + * @return mixed number, boolean, string, array, or object + * corresponding to given JSON input string. + * See argument 1 to Services_JSON() above for object-output behavior. + * Note that decode() always returns strings + * in ASCII or UTF-8 format! + * @access public + */ + function decode($str) + { + $str = $this->reduce_string($str); + + switch (strtolower($str)) { + case 'true': + return true; + + case 'false': + return false; + + case 'null': + return null; + + default: + $m = array(); + + if (is_numeric($str)) { + // Lookie-loo, it's a number + + // This would work on its own, but I'm trying to be + // good about returning integers where appropriate: + // return (float)$str; + + // Return float or int, as appropriate + return ((float)$str == (integer)$str) + ? (integer)$str + : (float)$str; + + } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { + // STRINGS RETURNED IN UTF-8 FORMAT + $delim = substr($str, 0, 1); + $chrs = substr($str, 1, -1); + $utf8 = ''; + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c < $strlen_chrs; ++$c) { + + $substr_chrs_c_2 = substr($chrs, $c, 2); + $ord_chrs_c = ord($chrs{$c}); + + switch (true) { + case $substr_chrs_c_2 == '\b': + $utf8 .= chr(0x08); + ++$c; + break; + case $substr_chrs_c_2 == '\t': + $utf8 .= chr(0x09); + ++$c; + break; + case $substr_chrs_c_2 == '\n': + $utf8 .= chr(0x0A); + ++$c; + break; + case $substr_chrs_c_2 == '\f': + $utf8 .= chr(0x0C); + ++$c; + break; + case $substr_chrs_c_2 == '\r': + $utf8 .= chr(0x0D); + ++$c; + break; + + case $substr_chrs_c_2 == '\\"': + case $substr_chrs_c_2 == '\\\'': + case $substr_chrs_c_2 == '\\\\': + case $substr_chrs_c_2 == '\\/': + if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || + ($delim == "'" && $substr_chrs_c_2 != '\\"')) { + $utf8 .= $chrs{++$c}; + } + break; + + case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): + // single, escaped unicode character + $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) + . chr(hexdec(substr($chrs, ($c + 4), 2))); + $utf8 .= $this->utf162utf8($utf16); + $c += 5; + break; + + case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): + $utf8 .= $chrs{$c}; + break; + + case ($ord_chrs_c & 0xE0) == 0xC0: + // characters U-00000080 - U-000007FF, mask 110XXXXX + //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 2); + ++$c; + break; + + case ($ord_chrs_c & 0xF0) == 0xE0: + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 3); + $c += 2; + break; + + case ($ord_chrs_c & 0xF8) == 0xF0: + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 4); + $c += 3; + break; + + case ($ord_chrs_c & 0xFC) == 0xF8: + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 5); + $c += 4; + break; + + case ($ord_chrs_c & 0xFE) == 0xFC: + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 6); + $c += 5; + break; + + } + + } + + return $utf8; + + } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { + // array, or object notation + + if ($str{0} == '[') { + $stk = array(SERVICES_JSON_IN_ARR); + $arr = array(); + } else { + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = array(); + } else { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = new stdClass(); + } + } + + array_push($stk, array('what' => SERVICES_JSON_SLICE, + 'where' => 0, + 'delim' => false)); + + $chrs = substr($str, 1, -1); + $chrs = $this->reduce_string($chrs); + + if ($chrs == '') { + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } else { + return $obj; + + } + } + + //print("\nparsing {$chrs}\n"); + + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c <= $strlen_chrs; ++$c) { + + $top = end($stk); + $substr_chrs_c_2 = substr($chrs, $c, 2); + + if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { + // found a comma that is not inside a string, array, etc., + // OR we've reached the end of the character list + $slice = substr($chrs, $top['where'], ($c - $top['where'])); + array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); + //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + // we are in an array, so just push an element onto the stack + array_push($arr, $this->decode($slice)); + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + // we are in an object, so figure + // out the property name and set an + // element in an associative array, + // for now + $parts = array(); + + if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // "name":value pair + $key = $this->decode($parts[1]); + $val = $this->decode($parts[2]); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // name:value pair, where name is unquoted + $key = $parts[1]; + $val = $this->decode($parts[2]); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } + + } + + } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { + // found a quote, and we are not inside a string + array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); + //print("Found start of string at {$c}\n"); + + } elseif (($chrs{$c} == $top['delim']) && + ($top['what'] == SERVICES_JSON_IN_STR) && + ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { + // found a quote, we're in a string, and it's not escaped + // we know that it's not escaped becase there is _not_ an + // odd number of backslashes at the end of the string so far + array_pop($stk); + //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '[') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-bracket, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); + //print("Found start of array at {$c}\n"); + + } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { + // found a right-bracket, and we're in an array + array_pop($stk); + //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '{') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-brace, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); + //print("Found start of object at {$c}\n"); + + } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { + // found a right-brace, and we're in an object + array_pop($stk); + //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($substr_chrs_c_2 == '/*') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a comment start, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); + $c++; + //print("Found start of comment at {$c}\n"); + + } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { + // found a comment end, and we're in one now + array_pop($stk); + $c++; + + for ($i = $top['where']; $i <= $c; ++$i) + $chrs = substr_replace($chrs, ' ', $i, 1); + + //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } + + } + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + return $obj; + + } + + } + } + } + + /** + * @todo Ultimately, this should just call PEAR::isError() + */ + function isError($data, $code = null) + { + if (class_exists('pear')) { + return PEAR::isError($data, $code); + } elseif (is_object($data) && (get_class($data) == 'services_json_error' || + is_subclass_of($data, 'services_json_error'))) { + return true; + } + + return false; + } +} + +if (class_exists('PEAR_Error')) { + + class Services_JSON_Error extends PEAR_Error + { + function Services_JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + parent::PEAR_Error($message, $code, $mode, $options, $userinfo); + } + } + +} else { + + /** + * @todo Ultimately, this class shall be descended from PEAR_Error + */ + class Services_JSON_Error + { + function Services_JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + + } + } + +} + diff --git a/models/attachment.php b/models/attachment.php new file mode 100644 index 0000000..490e030 --- /dev/null +++ b/models/attachment.php @@ -0,0 +1,56 @@ +import_wp_object($wp_attachment); + if ($this->is_image()) { + $this->query_images(); + } + } + } + + function import_wp_object($wp_attachment) { + $this->id = (int) $wp_attachment->ID; + $this->url = $wp_attachment->guid; + $this->slug = $wp_attachment->post_name; + $this->title = $wp_attachment->post_title; + $this->description = $wp_attachment->post_content; + $this->caption = $wp_attachment->post_excerpt; + $this->parent = (int) $wp_attachment->post_parent; + $this->mime_type = $wp_attachment->post_mime_type; + } + + function is_image() { + return (substr($this->mime_type, 0, 5) == 'image'); + } + + function query_images() { + $sizes = array('thumbnail', 'medium', 'large', 'full'); + if (function_exists('get_intermediate_image_sizes')) { + $sizes = array_merge(array('full'), get_intermediate_image_sizes()); + } + $this->images = array(); + foreach ($sizes as $size) { + list($url, $width, $height) = wp_get_attachment_image_src($this->id, $size); + $this->images[$size] = (object) array( + 'url' => $url, + 'width' => $width, + 'height' => $height + ); + } + } + +} + +?> diff --git a/models/author.php b/models/author.php new file mode 100644 index 0000000..ae399c1 --- /dev/null +++ b/models/author.php @@ -0,0 +1,62 @@ +id = (int) $id; + } else { + $this->id = (int) get_the_author_meta('ID'); + } + $this->set_value('slug', 'user_nicename'); + $this->set_value('name', 'display_name'); + $this->set_value('first_name', 'first_name'); + $this->set_value('last_name', 'last_name'); + $this->set_value('nickname', 'nickname'); + $this->set_value('url', 'user_url'); + $this->set_value('description', 'description'); + $this->set_author_meta(); + //$this->raw = get_userdata($this->id); + } + + function set_value($key, $wp_key = false) { + if (!$wp_key) { + $wp_key = $key; + } + $this->$key = get_the_author_meta($wp_key, $this->id); + } + + function set_author_meta() { + global $json_api; + if (!$json_api->query->author_meta) { + return; + } + $protected_vars = array( + 'user_login', + 'user_pass', + 'user_email', + 'user_activation_key' + ); + $vars = explode(',', $json_api->query->author_meta); + $vars = array_diff($vars, $protected_vars); + foreach ($vars as $var) { + $this->set_value($var); + } + } + +} + +?> diff --git a/models/category.php b/models/category.php new file mode 100644 index 0000000..499373e --- /dev/null +++ b/models/category.php @@ -0,0 +1,29 @@ +import_wp_object($wp_category); + } + } + + function import_wp_object($wp_category) { + $this->id = (int) $wp_category->term_id; + $this->slug = $wp_category->slug; + $this->title = $wp_category->name; + $this->description = $wp_category->description; + $this->parent = (int) $wp_category->parent; + $this->post_count = (int) $wp_category->count; + } + +} + +?> diff --git a/models/comment.php b/models/comment.php new file mode 100644 index 0000000..690dbba --- /dev/null +++ b/models/comment.php @@ -0,0 +1,80 @@ +import_wp_object($wp_comment); + } + } + + function import_wp_object($wp_comment) { + global $json_api; + + $date_format = $json_api->query->date_format; + $content = apply_filters('comment_text', $wp_comment->comment_content); + + $this->id = (int) $wp_comment->comment_ID; + $this->name = $wp_comment->comment_author; + $this->url = $wp_comment->comment_author_url; + $this->date = date($date_format, strtotime($wp_comment->comment_date)); + $this->content = $content; + $this->parent = (int) $wp_comment->comment_parent; + //$this->raw = $wp_comment; + + if (!empty($wp_comment->user_id)) { + $this->author = new JSON_API_Author($wp_comment->user_id); + } else { + unset($this->author); + } + } + + function handle_submission() { + global $comment, $wpdb; + add_action('comment_id_not_found', array(&$this, 'comment_id_not_found')); + add_action('comment_closed', array(&$this, 'comment_closed')); + add_action('comment_on_draft', array(&$this, 'comment_on_draft')); + add_filter('comment_post_redirect', array(&$this, 'comment_post_redirect')); + $_SERVER['REQUEST_METHOD'] = 'POST'; + $_POST['comment_post_ID'] = $_REQUEST['post_id']; + $_POST['author'] = $_REQUEST['name']; + $_POST['email'] = $_REQUEST['email']; + $_POST['url'] = empty($_REQUEST['url']) ? '' : $_REQUEST['url']; + $_POST['comment'] = $_REQUEST['content']; + $_POST['parent'] = $_REQUEST['parent']; + include ABSPATH . 'wp-comments-post.php'; + } + + function comment_id_not_found() { + global $json_api; + $json_api->error("Post ID '{$_REQUEST['post_id']}' not found."); + } + + function comment_closed() { + global $json_api; + $json_api->error("Post is closed for comments."); + } + + function comment_on_draft() { + global $json_api; + $json_api->error("You cannot comment on unpublished posts."); + } + + function comment_post_redirect() { + global $comment, $json_api; + $status = ($comment->comment_approved) ? 'ok' : 'pending'; + $new_comment = new JSON_API_Comment($comment); + $json_api->response->respond($new_comment, $status); + } + +} + +?> diff --git a/models/post.php b/models/post.php new file mode 100644 index 0000000..4a8c492 --- /dev/null +++ b/models/post.php @@ -0,0 +1,283 @@ +import_wp_object($wp_post); + } + } + + function create($values = null) { + unset($values['id']); + if (empty($values) || empty($values['title'])) { + $values = array( + 'title' => 'Untitled', + 'content' => '' + ); + } + return $this->save($values); + } + + function update($values) { + $values['id'] = $this->id; + return $this->save($values); + } + + function save($values = null) { + global $json_api, $user_ID; + + $wp_values = array(); + + if (!empty($values['id'])) { + $wp_values['ID'] = $values['id']; + } + + if (!empty($values['type'])) { + $wp_values['post_type'] = $values['type']; + } + + if (!empty($values['status'])) { + $wp_values['post_status'] = $values['status']; + } + + if (!empty($values['title'])) { + $wp_values['post_title'] = $values['title']; + } + + if (!empty($values['content'])) { + $wp_values['post_content'] = $values['content']; + } + + if (!empty($values['author'])) { + $author = $json_api->introspector->get_author_by_login($values['author']); + $wp_values['post_author'] = $author->id; + } + + if (isset($values['categories'])) { + $categories = explode(',', $values['categories']); + foreach ($categories as $category_slug) { + $category_slug = trim($category_slug); + $category = $json_api->introspector->get_category_by_slug($category_slug); + if (empty($wp_values['post_category'])) { + $wp_values['post_category'] = array($category->id); + } else { + array_push($wp_values['post_category'], $category->id); + } + } + } + + if (isset($values['tags'])) { + $tags = explode(',', $values['tags']); + foreach ($tags as $tag_slug) { + $tag_slug = trim($tag_slug); + if (empty($wp_values['tags_input'])) { + $wp_values['tags_input'] = array($tag_slug); + } else { + array_push($wp_values['tags_input'], $tag_slug); + } + } + } + + if (isset($wp_values['ID'])) { + $this->id = wp_update_post($wp_values); + } else { + $this->id = wp_insert_post($wp_values); + } + + if (!empty($_FILES['attachment'])) { + include_once ABSPATH . '/wp-admin/includes/file.php'; + include_once ABSPATH . '/wp-admin/includes/media.php'; + include_once ABSPATH . '/wp-admin/includes/image.php'; + $attachment_id = media_handle_upload('attachment', $this->id); + $this->attachments[] = new JSON_API_Attachment($attachment_id); + unset($_FILES['attachment']); + } + + $wp_post = get_post($this->id); + $this->import_wp_object($wp_post); + + return $this->id; + } + + function import_wp_object($wp_post) { + global $json_api, $post; + $date_format = $json_api->query->date_format; + $this->id = (int) $wp_post->ID; + setup_postdata($wp_post); + $this->set_value('type', $wp_post->post_type); + $this->set_value('slug', $wp_post->post_name); + $this->set_value('url', get_permalink($this->id)); + $this->set_value('status', $wp_post->post_status); + $this->set_value('title', get_the_title($this->id)); + $this->set_value('title_plain', strip_tags(@$this->title)); + $this->set_content_value(); + $this->set_value('excerpt', get_the_excerpt()); + $this->set_value('date', get_the_time($date_format)); + $this->set_value('modified', date($date_format, strtotime($wp_post->post_modified))); + $this->set_categories_value(); + $this->set_tags_value(); + $this->set_author_value($wp_post->post_author); + $this->set_comments_value(); + $this->set_attachments_value(); + $this->set_value('comment_count', (int) $wp_post->comment_count); + $this->set_value('comment_status', $wp_post->comment_status); + $this->set_thumbnail_value(); + $this->set_custom_fields_value(); + } + + function set_value($key, $value) { + global $json_api; + if ($json_api->include_value($key)) { + $this->$key = $value; + } else { + unset($this->$key); + } + } + + function set_content_value() { + global $json_api; + if ($json_api->include_value('content')) { + $content = get_the_content($json_api->query->read_more); + $content = apply_filters('the_content', $content); + $content = str_replace(']]>', ']]>', $content); + $this->content = $content; + } else { + unset($this->content); + } + } + + function set_categories_value() { + global $json_api; + if ($json_api->include_value('categories')) { + $this->categories = array(); + if ($wp_categories = get_the_category($this->id)) { + foreach ($wp_categories as $wp_category) { + $category = new JSON_API_Category($wp_category); + if ($category->id == 1 && $category->slug == 'uncategorized') { + // Skip the 'uncategorized' category + continue; + } + $this->categories[] = $category; + } + } + } else { + unset($this->categories); + } + } + + function set_tags_value() { + global $json_api; + if ($json_api->include_value('tags')) { + $this->tags = array(); + if ($wp_tags = get_the_tags($this->id)) { + foreach ($wp_tags as $wp_tag) { + $this->tags[] = new JSON_API_Tag($wp_tag); + } + } + } else { + unset($this->tags); + } + } + + function set_author_value($author_id) { + global $json_api; + if ($json_api->include_value('author')) { + $this->author = new JSON_API_Author($author_id); + } else { + unset($this->author); + } + } + + function set_comments_value() { + global $json_api; + if ($json_api->include_value('comments')) { + $this->comments = $json_api->introspector->get_comments($this->id); + } else { + unset($this->comments); + } + } + + function set_attachments_value() { + global $json_api; + if ($json_api->include_value('attachments')) { + $this->attachments = $json_api->introspector->get_attachments($this->id); + } else { + unset($this->attachments); + } + } + + function set_thumbnail_value() { + global $json_api; + if (!$json_api->include_value('thumbnail') || + !function_exists('get_post_thumbnail_id')) { + unset($this->thumbnail); + return; + } + $attachment_id = get_post_thumbnail_id($this->id); + if (!$attachment_id) { + unset($this->thumbnail); + return; + } + $thumbnail_size = $this->get_thumbnail_size(); + list($thumbnail) = wp_get_attachment_image_src($attachment_id, $thumbnail_size); + $this->thumbnail = $thumbnail; + } + + function set_custom_fields_value() { + global $json_api; + if ($json_api->include_value('custom_fields') && + $json_api->query->custom_fields) { + $keys = explode(',', $json_api->query->custom_fields); + $wp_custom_fields = get_post_custom($this->id); + $this->custom_fields = new stdClass(); + foreach ($keys as $key) { + if (isset($wp_custom_fields[$key])) { + $this->custom_fields->$key = $wp_custom_fields[$key]; + } + } + } else { + unset($this->custom_fields); + } + } + + function get_thumbnail_size() { + global $json_api; + if ($json_api->query->thumbnail_size) { + return $json_api->query->thumbnail_size; + } else if (function_exists('get_intermediate_image_sizes')) { + $sizes = get_intermediate_image_sizes(); + if (in_array('post-thumbnail', $sizes)) { + return 'post-thumbnail'; + } + } + return 'thumbnail'; + } + +} + +?> diff --git a/models/tag.php b/models/tag.php new file mode 100644 index 0000000..48c3592 --- /dev/null +++ b/models/tag.php @@ -0,0 +1,26 @@ +import_wp_object($wp_tag); + } + } + + function import_wp_object($wp_tag) { + $this->id = (int) $wp_tag->term_id; + $this->slug = $wp_tag->slug; + $this->title = $wp_tag->name; + $this->description = $wp_tag->description; + $this->post_count = (int) $wp_tag->count; + } + +} + +?> diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..4b1677f --- /dev/null +++ b/readme.txt @@ -0,0 +1,1117 @@ +=== JSON API === +Contributors: dphiffer +Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DH4MEG99JR2WE +Tags: json, api, ajax, cms, admin, integration, moma +Requires at least: 2.8 +Tested up to: 3.1 +Stable tag: 1.0.7 + +A RESTful API for WordPress + +== Description == + +JSON API allows you to retrieve and manipulate WordPress content using HTTP requests. There are three main goals: + +1. Provide a simple, consistent external interface +2. Create a stable, understandable internal implementation +3. Enable new types of extensions for WordPress + +This plugin was created at [The Museum of Modern Art](http://moma.org/) for the weblog [Inside/Out](http://moma.org/explore/inside_out), which is served from Ruby on Rails. Instead of reimplementing the site templates as a WordPress theme, we opted for a Rails front-end that displays content served from a WordPress back-end. JSON API provides the necessary interface for retrieving content and accepting comment submissions. + +See the [Other Notes](http://wordpress.org/extend/plugins/json-api/other_notes/) section for the complete documentation. + +== Installation == + +1. Upload the `json-api` folder to the `/wp-content/plugins/` directory or install directly through the plugin installer. +2. Activate the plugin through the 'Plugins' menu in WordPress or by using the link provided by the plugin installer. + +== Screenshots == + +1. Our old friend, in JSON format + +== Documentation == + +1. General concepts + 1.1. Requests + 1.2. Controllers + 1.3. Responses +2. Request methods + 2.1. Core controller methods + 2.2. Posts controller methods + 2.3. Respond controller methods +3. Request arguments + 3.1. Output-modifying arguments + 3.2. Content-modifying arguments + 3.3. Using include/exclude and redirects +4. Response objects + 4.1. Post response object + 4.2. Category response object + 4.3. Tag response object + 4.4. Author response object + 4.4. Comment response object + 4.5. Attachment response object +5. Extending JSON API + 5.1. Plugin hooks + 5.2. Developing JSON API controllers + 5.3. Configuration options +6. Unit tests + 6.1. Preparing a WordPress test site + 6.2. Running the tests + +== 1. General Concepts == + +== 1.1. Requests == + +Requests use a simple REST-style HTTP GET or POST. To invoke the API, include a non-empty query value for `json` in the URL. + +JSON API operates in two modes: + +1. *Implicit mode* is triggered by setting the `json` query var to a non-empty value on any WordPress page. The content that would normally appear on that page is returned in JSON format. +2. *Explicit mode* is triggered by setting `json` to a known method string. See *Section 2: Request methods* for a complete method listing. + += Implicit mode examples: = + + * `http://www.example.org/?json=1` + * `http://www.example.org/?p=47&json=1` + * `http://www.example.org/tag/banana/?json=1` + += Explicit mode examples: = + +* `http://www.example.org/?json=get_recent_posts` +* `http://www.example.org/?json=get_post&post_id=47` +* `http://www.example.org/?json=get_tag_posts&tag_slug=banana` + += With user-friendly permalinks configured: = + +* `http://www.example.org/api/get_recent_posts/` +* `http://www.example.org/api/get_post/?post_id=47` +* `http://www.example.org/api/get_tag_posts/?tag_slug=banana` + +__Further reading__ +See *Section 3: Request arguments* for more information about request arguments to modify the response. + +== 1.2. Controllers == + +The 1.0 release of JSON API introduced a modular controller system. This allows developers to flexibly add features to the API and give users more control over which methods they have enabled. + += The Core controller = + +Most of the methods available prior to version 1.0 have been moved to the Core controller. The two exceptions are `submit_comment` and `create_post` which are now available from the Respond and Posts controllers, respectively. The Core controller is the only one enabled by default. All other functionality must be enabled from the JSON API Settings page (under Settings in the WordPress admin menu). + += Specifying a controller = + +There are a few ways of specifying a controller, depending on how you are calling the API: + +* `http://www.example.org/?json=get_recent_posts` (`core` controller is implied, method is `get_recent_posts`) +* `http://www.example.org/api/info/` (`core` controller is implied) +* `http://www.example.org/api/core/get_category_posts/` (`core` controller can also be explicitly specified) +* `http://www.example.org/?json=respond.submit_comment` (`respond` controller, `submit_comment` method) + +__Legacy compatibility__ +JSON API retains support for its pre-1.0 methods. For example, if you invoke the method `create_post` without a controller specified, the Posts controller is chosen instead of Core. + += Available controllers = + +The current release includes three controllers: Core, Posts, and Respond. Developers are encouraged to suggest or submit additional controllers. + +__Further reading__ +See *Section 2: Request methods* for a complete reference of available controllers and methods. For documentation on extending JSON API with new controllers see *Section 5.2: Developing JSON API controllers*. + +== 1.3. Responses == + +The standard response format for JSON API is (as you may have guessed) [JSON](http://json.org/). + +Here is an example response from `http://localhost/wordpress/?json=1` called on a default WordPress installation (formatted for readability): + + { + "status": "ok", + "count": 1, + "count_total": 1, + "pages": 1, + "posts": [ + { + "id": 1, + "type": "post", + "slug": "hello-world", + "url": "http:\/\/localhost\/wordpress\/?p=1", + "title": "Hello world!", + "title_plain": "Hello world!", + "content": "

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!<\/p>\n", + "excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!\n", + "date": "2009-11-11 12:50:19", + "modified": "2009-11-11 12:50:19", + "categories": [], + "tags": [], + "author": { + "id": 1, + "slug": "admin", + "name": "admin", + "first_name": "", + "last_name": "", + "nickname": "", + "url": "", + "description": "" + }, + "comments": [ + { + "id": 1, + "name": "Mr WordPress", + "url": "http:\/\/wordpress.org\/", + "date": "2009-11-11 12:50:19", + "content": "

Hi, this is a comment.
To delete a comment, just log in and view the post's comments. There you will have the option to edit or delete them.<\/p>\n", + "parent": 0 + } + ], + "comment_count": 1, + "comment_status": "open" + } + ] + } + +== 2. Request methods == + +Request methods are available from the following controllers: + +* Core controller - basic introspection methods +* Posts controller - data manipulation methods for posts +* Respond controller - comment/trackback submission methods + +== 2.1. Core controller methods == + +The Core controller offers a mostly-complete set of introspection methods for retrieving content from WordPress. + + +== Method: info == + +Returns information about JSON API. + += Optional arguments = + +* `controller` - returns detailed information about a specific controller + += Response = + + { + "status": "ok", + "json_api_version": "1.0", + "controllers": [ + "core" + ] + } + + += Response = + + { + "status": "ok", + "name": "Core", + "description": "Basic introspection methods", + "methods": [ + ... + ] + } + + +== Method: get_recent_posts == + +Returns an array of recent posts. You can invoke this from the WordPress home page either by setting `json` to a non-empty value (i.e., `json=1`) or from any page by setting `json=get_recent_posts`. + += Optional arguments = + +* `count` - determines how many posts per page are returned (default value is 10) +* `page` - return a specific page number from the results +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "count": 10, + "count_total": 79, + "pages": 7, + "posts": [ + { ... }, + { ... }, + ... + ] + } + + +== Method: get_post == + +Returns a single post object. + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on a post URL +* `id` or `post_id` - set to the post's ID +* `slug` or `post_slug` - set to the post's URL slug + += Optional arguments = + +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "post": { ... } + } + + +== Method: get_page == + +Returns a single page object. + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on a page URL +* `id` or `page_id` - set to the page's ID +* `slug` or `page_slug` - set to the page's URL slug + += Optional arguments = + +* `children` - set to a non-empty value to include a recursive hierarchy of child pages +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "page": { ... } + } + +== Method: get_date_posts == + +Returns an array of posts/pages in a specific date archive (by day, month, or year). + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on a date archive page +* `date` - set to a date in the format `YYYY` or `YYYY-MM` or `YYYY-MM-DD` (non-numeric characters are stripped from the var, so `YYYYMMDD` or `YYYY/MM/DD` are also valid) + += Optional arguments = + +* `count` - determines how many posts per page are returned (default value is 10) +* `page` - return a specific page number from the results +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "count": 10, + "count_total": 79, + "pages": 7, + "posts": [ + { ... }, + { ... }, + ... + ] + } + +== Method: get_category_posts == + +Returns an array of posts/pages in a specific category. + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on a category archive page +* `id` or `category_id` - set to the category's ID +* `slug` or `category_slug` - set to the category's URL slug + += Optional arguments = + +* `count` - determines how many posts per page are returned (default value is 10) +* `page` - return a specific page number from the results +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "count": 10, + "count_total": 79, + "pages": 7, + "category": { ... } + "posts": [ + { ... }, + { ... }, + ... + ] + } + + +== Method: get_tag_posts == + +Returns an array of posts/pages with a specific tag. + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on a tag archive page +* `id` or `tag_id` - set to the tag's ID +* `slug` or `tag_slug` - set to the tag's URL slug + += Optional arguments = + +* `count` - determines how many posts per page are returned (default value is 10) +* `page` - return a specific page number from the results +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "count": 10, + "count_total": 79, + "pages": 7, + "tag": { ... } + "posts": [ + { ... }, + { ... }, + ... + ] + } + + +== Method: get_author_posts == + +Returns an array of posts/pages written by a specific author. + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on an author archive page +* `id` or `author_id` - set to the author's ID +* `slug` or `author_slug` - set to the author's URL slug + += Optional arguments = + +* `count` - determines how many posts per page are returned (default value is 10) +* `page` - return a specific page number from the results +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "count": 10, + "count_total": 79, + "pages": 7, + "author": { ... } + "posts": [ + { ... }, + { ... }, + ... + ] + } + + +== Method: get_search_results == + +Returns an array of posts/pages in response to a search query. + += One of the following is required = + +* Invoking the JSON API implicitly (i.e., `?json=1`) on a search results page +* `search` - set to the desired search query + += Optional arguments = + +* `count` - determines how many posts per page are returned (default value is 10) +* `page` - return a specific page number from the results +* `post_type` - used to retrieve custom post types + += Response = + + { + "status": "ok", + "count": 10, + "count_total": 79, + "pages": 7, + "posts": [ + { ... }, + { ... }, + ... + ] + } + + +== Method: get_date_index == + +Returns both an array of date page permalinks and a tree structure representation of the archive. + += Response = + + { + "status": "ok", + "permalinks": [ + "...", + "...", + "..." + ], + "tree": { + "2009": { + "09": 17, + "10": 20, + "11": 7 + } + } + +Note: the tree is arranged by `response.tree.[year].[month].[number of posts]`. + + +== Method: get_category_index == + +Returns an array of active categories. + += Response = + + { + "status": "ok", + "count": 3, + "categories": [ + { ... }, + { ... }, + { ... } + ] + } + + +== Method: get_tag_index == + +Returns an array of active tags. + += Response = + + { + "status": "ok", + "count": 3 + "tags": [ + { ... }, + { ... }, + { ... } + ] + } + + +== Method: get_author_index == + +Returns an array of active blog authors. + += Response = + + { + "status": "ok", + "count": 3, + "authors": [ + { ... }, + { ... }, + { ... } + ] + } + + +== Method: get_page_index == + +Returns a hierarchical tree of `page` posts. + += Response = + + { + "status": "ok", + "pages": [ + { ... }, + { ... }, + { ... } + ] + } + +== Method: get_nonce == + +Returns a WordPress nonce value, required to call some data manipulation methods. + += Required arguments = + +* `controller` - the JSON API controller for the method you will use the nonce for +* `method` - the method you wish to call (currently `create_post` is the only method that requires a nonce) + += Response = + + { + "status": "ok", + "controller": "posts", + "method": "create_post", + "nonce": "cefe01efd4" + } + +__Further reading__ +To learn more about how nonces are used in WordPress, see [Mark Jaquith's article on the subject](http://markjaquith.wordpress.com/2006/06/02/wordpress-203-nonces/). + +== 2.2. Pages controller methods == + +== Method: create_post == + +Creates a new post. + += Required argument = + +* `nonce` - available from the `get_nonce` method (call with vars `controller=posts` and `method=create_post`) + += Optional arguments = + +* `status` - sets the post status ("draft" or "publish"), default is "draft" +* `title` - the post title +* `content` - the post content +* `author` - the post's author (login name), default is the current logged in user +* `categories` - a comma-separated list of categories (URL slugs) +* `tags` - a comma-separated list of tags (URL slugs) + +Note: including a file upload field called `attachment` will cause an attachment to be stored with your new post. + + +== 2.3. Respond controller methods == + +== Method: submit_comment == + +Submits a comment to a WordPress post. + += Required arguments = + +* `post_id` - which post to comment on +* `name` - the commenter's name +* `email` - the commenter's email address +* `content` - the comment content + += Optional arguments = + +* `redirect` - redirect instead of returning a JSON object +* `redirect_ok` - redirect to a specific URL when the status value is `ok` +* `redirect_error` - redirect to a specific URL when the status value is `error` +* `redirect_pending` - redirect to a specific URL when the status value is `pending` + += Custom status values = + +* `pending` - assigned if the comment submission is pending moderation + + +== 3. Request arguments == + +API requests can be controlled by specifying one of the following arguments as URL query vars. + += Examples = + +* Debug the response: `http://www.example.org/api/get_page_index/?dev=1` +* Widget-style JSONP output: `http://www.example.org/api/get_recent_posts/?callback=show_posts_widget&read_more=More&count=3` +* Redirect on error: `http://www.example.org/api/posts/create_post/?callback_error=http%3A%2F%2Fwww.example.org%2Fhelp.html` + +== 3.1. Output-modifying arguments == + +The following arguments modify how you get results back from the API. The redirect response styles are intended for use with the data manipulation methods. + +* Setting `callback` to a JavaScript function name will trigger a JSONP-style callback. +* Setting `redirect` to a URL will cause the user's browser to redirect to the specified URL with a `status` value appended to the query vars (see the *Response objects* section below for an explanation of status values). +* Setting `redirect_[status]` allows you to control the resulting browser redirection depending on the `status` value. +* Setting `dev` to a non-empty value adds whitespace for readability and responds with `text/plain` +* Omitting all of the above arguments will result in a standard JSON response. + +== 3.2. Content-modifying arguments == + +These arguments are available to modify all introspection methods: + +* `date_format` - Changes the format of date values. Uses the same syntax as PHP's date() function. Default value is `Y-m-d H:i:s`. +* `read_more` - Changes the 'read more' link text in post content. +* `include` - Specifies which post data fields to include. Expects a comma-separated list of post fields. Leaving this empty includes *all* fields. +* `exclude` - Specifies which post data fields to exclude. Expects a comma-separated list of post fields. +* `custom_fields` - Includes values from posts' Custom Fields. Expects a comma-separated list of custom field keys. +* `author_meta` - Includes additional author metadata. Should be a comma-separated list of metadata fields. +* `count` - Controls the number of posts to include (defaults to the number specified by WordPress) +* `order` - Controls the order of post results ('DESC' or 'ASC'). Default value is 'DESC'. +* `order_by` - Controls which field to order results by. Expects one of the following values: + * `author` + * `date` (default value) + * `title` + * `modified` + * `menu_order` (only works with Pages) + * `parent` + * `ID` + * `rand` + * `meta_value` (`meta_key` must also be set) + * `none` + * `comment_count` +* `meta_key`, `meta_value`, `meta_compare` - Retrieve posts (or Pages) based on a custom field key or value. + +== 3.3. Using include/exclude and redirects == + +__About `include`/`exclude` arguments__ +By default you get all values included with each post object. Specify a list of `include` values will cause the post object to filter out the values absent from the list. Specifying `exclude` causes post objects to include all values except the fields you list. For example, the query `exclude=comments` includes everything *except* the comments. + +__About the `redirect` argument__ +The `redirect` response style is useful for when you need the user's browser to make a request directly rather than making proxy requests using a tool like cURL. Setting a `redirect` argument causes the user's browser to redirect back to the specified URL instead of returning a JSON object. The resulting `status` value is included as an extra query variable. + +For example calling an API method with `redirect` set to `http://www.example.com/foo` will result in a redirection to one of the following: + +* `http://www.example.com/foo?status=ok` +* `http://www.example.com/foo?status=error` + +You can also set separate URLs to handle status values differently. You could set `redirect_ok` to `http://www.example.com/handle_ok` and `redirect_error` to `http://www.example.com/handle_error` in order to have more fine-tuned control over the method result. + + +== 4. Response objects == + +This section describes data objects you can retrieve from WordPress and the optional URL redirects. + +__Status values__ +All JSON API requests result in a status value. The two basic status values are `ok` and `error`. Additional status values are available for certain methods (such as `pending` in the case of the `submit_comment` method). API methods that result in custom status values include a *custom status values* section in their documentation. + +__Naming compatibility__ +Developers familiar with WordPress may notice that many names for properties and arguments have been changed. This was a stylistic choice that intends to provide more clarity and consistency in the interface. + +== 4.1. Post response object == + +* `id` - Integer +* `type` - String (e.g., `post` or `page`) +* `slug` - String +* `url` - String +* `title` - String +* `title_plain` - String +* `content` - String (modified by the `read_more` argument) +* `excerpt` - String +* `date` - String (modified by the `date_format` argument) +* `modified` - String (modified by the `date_format` argument) +* `categories` - Array of category objects +* `tags` - Array of tag objects +* `author` Author object +* `comments` - Array of comment objects +* `attachments` - Array of attachment objects +* `comment_count` - Integer +* `comment_status` - String (`"open"` or `"closed"`) +* `thumbnail` - String (only included if a post thumbnail has been specified) +* `custom_fields` - Object (included by setting the `custom_fields` argument to a comma-separated list of custom field names) + +__Note__ +The `thumbnail` attribute returns a URL to the image size specified by the optional `thumbnail_size` request argument. By default this will use the `thumbnail` or `post-thumbnail` sizes, depending on your version of WordPress. See [Mark Jaquith's post on the topic](http://markjaquith.wordpress.com/2009/12/23/new-in-wordpress-2-9-post-thumbnail-images/) for more information. + +== 4.2. Category response object == + +* `id` - Integer +* `slug` - String +* `title` - String +* `description` - String +* `parent` - Integer +* `post_count` - Integer + +== 4.3. Tag response object == + +* `id` - Integer +* `slug` - String +* `title` - String +* `description` - String +* `post_count` - Integer + +== 4.4. Author response object == + +* `id` - Integer +* `slug` - String +* `name` - String +* `first_name` - String +* `last_name` - String +* `nickname` - String +* `url` - String +* `description` - String + +Note: You can include additional values by setting the `author_meta` argument to a comma-separated list of metadata fields. + +== 4.5. Comment response object == + +* `id` - Integer +* `name` - String +* `url` - String +* `date` - String +* `content` - String +* `parent` - Integer +* `author` - Object (only set if the comment author was registered & logged in) + +== 4.6. Attachment response object == + +* `id` - Integer +* `url` - String +* `slug` - String +* `title` - String +* `description` - String +* `caption` - String +* `parent` - Integer +* `mime_type` - String +* `images` - Object with values including `thumbnail`, `medium`, `large`, `full`, each of which are objects with values `url`, `width` and `height` (only set if the attachment is an image) + + +== 5. Extending JSON API == + +JSON API exposes several WordPress action and filter hooks as well as a modular controller system for adding new API methods. + +== 5.1. Plugin hooks == + +JSON API exposes several [action and filter hooks](http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters) to augment its behavior. + +== Filter: json_api_controllers == + +This filter controls the array of controllers available to JSON API. The callback function is passed a single argument, an array of strings. + += Example = + + // Add a custom controller + add_filter('json_api_controllers', 'add_my_controller'); + + function add_my_controller($controllers) { + // Corresponds to the class JSON_API_MyController_Controller + $controllers[] = 'MyController'; + return $controllers; + } + + +== Filter: json_api_[controller]_controller_path == + +Specifies the PHP source file for a given controller, overriding the default location `wp-content/plugins/json_api/controllers`. + +__Note__ +If you your controller file in the `json-api/controllers` folder JSON API will find it automatically. + += Example = + + // Register the source file for JSON_API_Widgets_Controller + add_filter('json_api_widgets_controller_path', 'widgets_controller_path'); + + function widgets_controller_path($default_path) { + return '/path/to/widgets.php'; + } + +__Capitalization__ +Your filter hook must be all-lowercase to work correctly. The above example would fail with the filter `json_api_Widgets_Controller_path`, even if that's how the class is capitalized in the PHP source. + +== Filter: json_api_encode == + +This is called just before the output is encoded into JSON format. The value passed will always be an associative array, according to the format described in each method's documentation. Those items described in the *Response objects* section are passed as PHP objects, not associative arrays. + += Example = + + add_filter('json_api_encode', 'my_encode_kittens'); + + function my_encode_kittens($response) { + if (isset($response['posts'])) { + foreach ($response['posts'] as $post) { + my_add_kittens($post); // Add kittens to each post + } + } else if (isset($response['post'])) { + my_add_kittens($response['post']); // Add a kittens property + } + return $response; + } + + function my_add_kittens(&$post) { + $post->kittens = 'Kittens!'; + } + +== Action: json_api-[controller]-[method] == + +Each JSON API method invokes an action when called. + += Example = + + // Disable get_author_index method (e.g., for security reasons) + add_action('json_api-core-get_author_index', 'my_disable_author_index'); + + function my_disable_author_index() { + // Stop execution + exit; + } + +== 5.2. Developing JSON API controllers == + += Creating a controller = + +To start a new JSON API controller, create a file called `hello.php` inside `wp-content/plugins/json-api/controllers`. Add the following class definition: + + "Hello, world" + ); + } + + } + + ?> + +Your controller is now available as `hello`, and exposes one `hello_world` method. + +Next, activate your controller from the WordPress admin interface, available from the menu under Settings > JSON API. You can either click on the link to your `hello_world` method from the admin interface or enter it manually. It should have the form: `http://www.example.org/api/hello/hello_world/?dev=1` or `http://www.example.org/?json=hello.hello_world&dev=1` (note the use of the `dev` argument to enable human-readable output). You should get the following output: + + { + "status": "ok", + "message": "Hello, world" + } + += Using query vars = + +To customize the behavior of your controller, you will want to make use of the global `$json_api->query` object. Add the following method to your controller: + + public function hello_person() { + global $json_api; + $name = $json_api->query->name; + return array( + "message" => "Hello, $name." + ); + } + +Now append the `name` query var to the method call: `http://www.example.org/api/hello/hello_world/?dev=1&name=Alice` or `http://www.example.org/?json=hello.hello_world&dev=1&name=Alice`. + + { + "status": "ok", + "message": "Hello, Alice" + } + += Introspector and data models = + +Your controller can use any of the [existing WordPress functions](http://codex.wordpress.org/Function_Reference) to collect data, but JSON API also includes an introspector that wraps data in objects defined in the `json-api/models` directory. These are the same data models described in *Section 4: Response objects*. + +Here is an example of how you might use the introspector: + + // Retrieve posts based on custom field key/value pair + public function get_custom_posts() { + global $json_api; + + // Make sure we have key/value query vars + if (!$json_api->query->key || !$json_api->query->value) { + $json_api->error("Include a 'key' and 'value' query var."); + } + + // See also: http://codex.wordpress.org/Template_Tags/query_posts + $posts = $json_api->introspector->get_posts(array( + 'meta_key' => $json_api->query->key, + 'meta_value' => $json_api->query->value + )); + + return array( + 'key' => $key, + 'value' => $value, + 'posts' => $posts + ); + } + += External controllers = + +It is recommended that custom controllers are kept outside of `json-api/controllers` in order to avoid accidental deletion during upgrades or site migrations. To make your controller visible from an external plugin or theme directory you will need to use two filters: `json_api_controllers` and `json_api_[controller]_controller_path`. Move the `hello.php` file from the steps above into your theme's directory. Then add the following to your theme's `functions.php` file (if your theme doesn't have a file called `functions.php` you can create one). + + function add_hello_controller($controllers) { + $controllers[] = 'hello'; + return $controllers; + } + add_filter('json_api_controllers', 'add_hello_controller'); + + function set_hello_controller_path() { + return "/path/to/theme/hello.php"; + } + add_filter('json_api_hello_controller_path', 'set_hello_controller_path'); + +== 5.3. Configuration options == + +The following are constants you can define in your `wp-config.php` folder: + +* `JSON_API_DIR` - set to the directory where JSON API plugin lives (in some cases this can be useful for `mu-plugins` with WordPress MU) +* `JSON_API_CONTROLLERS` - a comma-separated list of default controllers to enable (this is overridden by the JSON API settings page) + +== 6. Unit tests == + +JSON API comes with a set of tests that should make it easier to maintain and reveal incompatibilities when they might occur. This is an ongoing process, I hope to improve the test coverage going forward. + +== 6.1. Preparing a WordPress test site == + +There are a few necessary steps that need to be carried out before the test suite will run properly. + +1. WordPress should generate a new set of tables before you start, so if you're testing with a `wp_` table prefix make sure the database has no existing tables of this kind +2. Configure and install a new copy of WordPress +3. Delete the Hello World post and Sample Page (titled "About" in some versions of WordPress) +4. Enable user-friendly URLs from Settings > Permalinks, use the "Day and name" format +5. Install the JSON API plugin and enable all bundled controllers from Settings > JSON API +6. Import the [Theme Unit Test](http://codex.wordpress.org/Theme_Unit_Test) test data XML file from Settings > Import > WordPress (you will need to install the WordPress Importer plugin) + +== 6.2. Running the tests == + +From the command line, make sure you have the HTTP_Client PEAR package installed: + +`pear install HTTP_Client` + +Change directory to `tests` and run the following: + +`pear run-tests` + +You should see the test results print out culminating in a summary: + + TOTAL TIME: 00:04 + 23 PASSED TESTS + 0 SKIPPED TESTS + +== Changelog == + += 1.0.7 (2011-01-27): = +* Created some basic unit tests +* Fixed a bug where `get_author_posts` was unable to find users by `slug` +* Added missing `post_type` argument to documentation for `get_post` and `get_page` (props Koshirosan) +* Added `previous_url` and `next_url` properties to the `get_post` response object (props mlcy44) + += 1.0.6 (2011-01-13): = +* Fixed a bug in `exclude` query parameter (big props to ikesyo and archon810) +* Fix for `get_page_index` that where it only returned 5 pages -- it now responds to `count` query param (props to npavkovic and blinder) +* Removed `Content-Disposition` header from response (props mimecine, kjwierenga) +* Fixed an incompatibility issue with Disqus plugin (props joshcanhelp) +* Fixed a bug where `submit_comment` was resulting in a HTTP 404 status (props @tdweston) +* Fixed an error in the documentation, external controller example (props jli) + += 1.0.5 (2010-07-08): = +* Added an check so that `json-api.php` can be moved one level above the `json-api` directory +* Added more documentation about using nonces + += 1.0.4 (2010-07-07): = +* Fixed a bug where the order of attachments didn't match the gallery +* Added a section to the developer documentation for externalizing custom controllers +* Moved JSON_API class to its own file: `singletons/api.php` +* Created a new top-level function: `json_api_dir()` +* Improvements for WordPress MU: `JSON_API_DIR` and `JSON_API_CONTROLLERS` constants (props Jim McQuillan) + += 1.0.3 (2010-07-07): = +* Added request argument `thumbnail_size` to support different sizes of featured images (see also: `add_image_size` WordPress function) +* Added request argument `post_type` to support custom post types (props Mark Harris) + += 1.0.2 (2010-07-02): = +* Removed an inaccurate section from readme.txt about supporting `query_posts` arguments +* Changed controller info block format to use "Controller name" and "Controller description" +* Made admin page more robust about handling errors loading controllers +* Changed `JSON_API::get_controllers` method to lowercase all entries +* Added introspector section to developer documentation +* Fixed incorrect example for `json_api_[controller]_controller_path` +* Thanks to Tim Nash for early feedback on writing external controllers + += 1.0.1 (2010-07-01): = +* Fixed some typos in readme.txt +* Switched `get_tag_posts` to query on tag instead of tag_id (maybe a WordPress issue?) + += 1.0 (2010-06-29): = +* JSON API officially drops support for PHP 4 (it was already broken) +* Added JSON API Settings page to WP admin +* Broke apart `JSON_API_Controller` into a modular controller system +* Refactored `JSON_API_Query` to depend less on WordPress's `get_query_var` mechanism +* Developer mode now shows response in JSON format +* The `create_post` method now requires a nonce +* Improved support for complex post queries (props zibitt) +* Fixed a bug with `get_author_by_login` (props Krzysztof Sobolewski) +* Made image attachments more robust with `get_intermediate_image_sizes` (props mimecine) +* Improved post thumbnail support (props nyamsprod) + += 0.9.6 (2010-05-27): = +* Fixed a bug introduced in 0.9.5 + += 0.9.5 (2010-05-27): = +* Added a `thumbnail` property to Post response objects + += 0.9.4 (2010-04-28): = +* Fixed a bug where any non-authenticated user could create a draft blog post through `create_post`. Thanks to user futtta for posting about this. + += 0.9.3 (2010-03-19): = +* Fixed a bug where child pages were being ignored by the API. See also: https://core.trac.wordpress.org/ticket/12647 + += 0.9.2 (2010-03-18): = +* Fixed a bug where the /api/ rewrite rules would be lost + += 0.9 (2010-02-04): = +* Added a `create_post` method + += 0.8.3 (2010-01-27): = +* Fixed the stable tag version + += 0.8.2 (2010-01-27): = +* Fixed a typo in the changelog + += 0.8.1 (2010-01-27): = +* Fixed a bug that was making JSONP support non-functional + += 0.8 (2010-01-18): = +* Added an attachment model and instance variable for post objects + += 0.7.3 (2010-01-15): = +* Added a `count` request parameter to control the number of posts returned + += 0.7.2 (2010-01-14): = +* Removed the version number from the description text + += 0.7.1 (2010-01-14): = +* Fixed another subtle bug with `get_author_index` + += 0.7 (2010-01-08): = +* Added a `post_count` response to tag objects +* Fixed a bug with `get_author_index` + += 0.6 (2009-11-30): = +* Added `count_total` response +* Added `json_api_encode` filter +* Fixed bugs in the introspector's `get_current_category` and `get_current_tag` + += 0.5 (2009-11-17): = +* Initial Public Release + +== Upgrade Notice == + += 1.0.7 = +Minor bugfix/improvement release + += 1.0.6 = +Minor bugfix/improvement release + += 1.0.5 = +Minor improvement release + += 1.0.4 = +Minor bugfix/refactor release + += 1.0.3 = +Two new request arguments added: `thumbnail_size` and `post_type` + += 1.0.2 = +Minor bugfix release + += 1.0.1 = +Bugfix release, possibly stemming from a bug in WordPress 3.0 + += 1.0 = +Major release, see changelog for details. + += 0.9.6 = +Bugfix release for something added in 0.9.5. + += 0.9.5 = +Feature addition: post thumbnails now included in response objects. + += 0.9.4 = +Security fix: all users are strongly encouraged to upgrade. (See Changelog.) + += 0.9.3 = +Fixed a bug where child pages could not be introspected by the API. + += 0.9.2 = +Fixed a bug where the /api/ path would stop working upon publishing new pages. + += 0.9 = +Added a new data manipulation method: `create_post`. + += 0.8.3 = +Oh dear, I didn't tag 0.8.2 in the stable tags thing. + += 0.8.2 = +Just fixing a mislabeled 0.8.1 release in the changelog. + += 0.8.1 = +This is a bug fix release for JSONP support. Thanks to Ben Wilson for reporting it! + += 0.8 = +Added what may be the last introspection feature: post attachments. You can now see images and other media that have been added to posts. diff --git a/screenshot-1.png b/screenshot-1.png new file mode 100644 index 0000000000000000000000000000000000000000..b5bba9d5d2d806e8567e5aff9190fa5e2ea86c42 GIT binary patch literal 23452 zcmb@ubyQH@+Aj*yNVhbCNJ)2!bR&%*Dc#*5-6h>A-Q6wSUD74p4c^Iq_degf-yP$O zbIv$_IFxj)x#oPHUp*^WURDel5g!o(0s>h=Tv!1D;uRJI1SAUlEASbu);E*jFK8n{ z89@k$1*lK6a#`SG1Z#11I|zu^m@j`IA(B(^z$Yo}MbzvStqkp*bZreFK0BD`n<<%C z7?5(%v(vMXQpxD*lgcTQs!>C<<{mbK?}xLOkP(4fc#Vb)LoC!tZ4UuK3LzmZsN|e_ z)aoLyY?OTKC8H@XkM$XA`R40pd_xM}4fY03g6x?6Ps-mhb*abuN)F2TO?e7aY-yD& zN#6#OA}l5)mN)6q1eZIApq1o5LP82c3!|YKM6c!_KaAX^HQuCm^CgJLq>qu*k9wTA zt=za|T(phZj(XRNSX!1H<@aO>1riH*9?H)*+U;_zx?d#qlf(O*zMb62-{FN8MDq){ zn5@S6hz2d_e1^752Jb_vCYl;Z3h$%y#)jAj{B6+V0zL^JkN&^##XN~rF-OPi9I?nS z&(fkI*ZWHop~ZavfK+<$D_GI$Q~NgiBHQoxi#Im(N-4<6^}7R*&(6-!(a{NG@zWU1X=-XR82YPNt=|`+ zrKJT43Hjkm&6*;u*X^mUvoj}Lwb9t|a$|KHFAYsmOG}HvNTHCr$)cy zJ0!TTaYR~L+MDCwJT@CWR|j)3C4^kI!ViU3t8G(xGMhTXiA>~T5!3Zv=UWoYVcFSl zQAOXqtTFW!Pb9dI`T6{qEDm=E}bEI31gxUn{j@;o`!$;HLx?(Pn(YXXDz@m%?;9|ET9^dADxdzl|@8gj<^0y;@_29*6znYb zdOGMOiU9xB8bdi$%Vkks-LSj2WO^IBWhE!RM5`S7M(H6z=-SMV|{)@d8>5 zhT=8qEep%zS*gL=eGeS%9vdsKsi{%Smj(Mel0?7~>=~CQP*MW?{4Vz_!ESSR zci(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f5b6A16&5)KfEJ_z8bva<3#4LN3LXeir&8Kqf?$J)H$F4iNZDbkM~(sDd>V4Oi} zR0JYHnq$#)qRVmt!*29M|Aa{2U803Zj|<~DN=d!T$jCqx89mNb_mHlMuDRcReOo@m ziDb2yUefC}F2<0Roh@N+>nlxgn8gj=n< zVos?R;Zg7-3z5x0=|~9)GjQ`SLlr_}LA-M4YUxu*1rA&L)g}8)o;#~~T6MAp_TWo_ z%%{1ttep8fhPag4;NRcW!%A=VrI8g`Z8mE_(Znp~E zi*-E`04SxHLD5%>xvR7jv)3{(FCASA7rshJrA`_U~D@qhMv`y$=joH`oR>pILG zLdwd@LiAie-|l0S!MXSJ`)Tu$upv7h=spByq6yYCD6In491>cCXysL4GR5EJirp4O zQv5~m%-o<{Ap$A`xeLweUXe(w|Y+Ic3jzoDr>?C zrIOnjlU(wnMs#YvOQ=B+K`46%yih!OG;H7HSa6qZ5@hu*U-t5y`S}wUQ?8C5XQ@#C zVNyN1$gp({Vt}H{OeqEC0JMln_0Aa}PI(J3WR8(1JgJoNaUx1_x`2ubH6chDqs37F zU>Y?y-QVVVE;tU7k{74ttrpFP!~-1uV&J)2S-n|Y&uI5si7q!=t@SFy13s;$Ho7Ya zysrLA`n8zX#|;c{&!$y4;#{}>7HYyXbr}Fac6MFha9LOeh9-q+g7D=W>2LHP|BrrZ ll^;IzM8f}{W;;jSxXAXgB%4{l0c7kA8fq6#Wt=d2{6ANiE(QPq literal 0 HcmV?d00001 diff --git a/singletons/api.php b/singletons/api.php new file mode 100644 index 0000000..baeb506 --- /dev/null +++ b/singletons/api.php @@ -0,0 +1,371 @@ +query = new JSON_API_Query(); + $this->introspector = new JSON_API_Introspector(); + $this->response = new JSON_API_Response(); + add_action('template_redirect', array(&$this, 'template_redirect')); + add_action('admin_menu', array(&$this, 'admin_menu')); + add_action('update_option_json_api_base', array(&$this, 'flush_rewrite_rules')); + add_action('pre_update_option_json_api_controllers', array(&$this, 'update_controllers')); + } + + function template_redirect() { + // Check to see if there's an appropriate API controller + method + $controller = strtolower($this->query->get_controller()); + $available_controllers = $this->get_controllers(); + $enabled_controllers = explode(',', get_option('json_api_controllers', 'core')); + $active_controllers = array_intersect($available_controllers, $enabled_controllers); + + if ($controller) { + + if (!in_array($controller, $active_controllers)) { + $this->error("Unknown controller '$controller'."); + } + + $controller_path = $this->controller_path($controller); + if (file_exists($controller_path)) { + require_once $controller_path; + } + $controller_class = $this->controller_class($controller); + + if (!class_exists($controller_class)) { + $this->error("Unknown controller '$controller_class'."); + } + + $this->controller = new $controller_class(); + $method = $this->query->get_method($controller); + + if ($method) { + + $this->response->setup(); + + // Run action hooks for method + do_action("json_api-{$controller}-$method"); + + // Error out if nothing is found + if ($method == '404') { + $this->error('Not found'); + } + + // Run the method + $result = $this->controller->$method(); + + // Handle the result + $this->response->respond($result); + + // Done! + exit; + } + } + } + + function admin_menu() { + add_options_page('JSON API Settings', 'JSON API', 'manage_options', 'json-api', array(&$this, 'admin_options')); + } + + function admin_options() { + if (!current_user_can('manage_options')) { + wp_die( __('You do not have sufficient permissions to access this page.') ); + } + + $available_controllers = $this->get_controllers(); + $active_controllers = explode(',', get_option('json_api_controllers', 'core')); + + if (count($active_controllers) == 1 && empty($active_controllers[0])) { + $active_controllers = array(); + } + + if (!empty($_REQUEST['_wpnonce']) && wp_verify_nonce($_REQUEST['_wpnonce'], "update-options")) { + if ((!empty($_REQUEST['action']) || !empty($_REQUEST['action2'])) && + (!empty($_REQUEST['controller']) || !empty($_REQUEST['controllers']))) { + if (!empty($_REQUEST['action'])) { + $action = $_REQUEST['action']; + } else { + $action = $_REQUEST['action2']; + } + + if (!empty($_REQUEST['controllers'])) { + $controllers = $_REQUEST['controllers']; + } else { + $controllers = array($_REQUEST['controller']); + } + + foreach ($controllers as $controller) { + if (in_array($controller, $available_controllers)) { + if ($action == 'activate' && !in_array($controller, $active_controllers)) { + $active_controllers[] = $controller; + } else if ($action == 'deactivate') { + $index = array_search($controller, $active_controllers); + if ($index !== false) { + unset($active_controllers[$index]); + } + } + } + } + $this->save_option('json_api_controllers', implode(',', $active_controllers)); + } + if (isset($_REQUEST['json_api_base'])) { + $this->save_option('json_api_base', $_REQUEST['json_api_base']); + } + } + + ?> +

+

+

JSON API Settings

+
+ +

Controllers

+ print_controller_actions(); ?> + + + + + + + + + + + + + + + + + controller_info($controller); + + if (is_string($info)) { + $active = false; + $error = true; + $info = array( + 'name' => $controller, + 'description' => "

Error: $info

", + 'methods' => array(), + 'url' => null + ); + } + + ?> + + + + + + + +
ControllerDescription
ControllerDescription
+ + + +
+ ' . __('Deactivate') . ''; + } else if (!$error) { + echo '' . __('Activate') . ''; + } + + if ($info['url']) { + echo ' | '; + echo 'Docs
'; + } + + ?> +
+

+

+ get_method_url($controller, $method, array('dev' => 1)); + if ($active) { + echo "$method "; + } else { + echo "$method "; + } + } + + ?> +

+
+ print_controller_actions('action2'); ?> +

Address

+

Specify a base URL for JSON API. For example, using api as your API base URL would enable the following /api/get_recent_posts/. If you assign a blank value the API will only be available by setting a json query variable.

+ + + + + +
API base/
+ +
+

Note: User-friendly permalinks are not currently enabled. Change Permalinks + +

+ +

+
+
+ +
+
+ + +
+
+
+
+ $value) { + $args[] = urlencode($key) . '=' . urlencode($value); + } + $args = implode('&', $args); + } else { + $args = $options; + } + if ($controller != 'core') { + $method = "$controller/$method"; + } + if (!empty($base) && !empty($permalink_structure)) { + if (!empty($args)) { + $args = "?$args"; + } + return "$url/$base/$method/$args"; + } else { + return "$url?json=$method&$args"; + } + } + + function save_option($id, $value) { + $option_exists = (get_option($id, null) !== null); + if ($option_exists) { + update_option($id, $value); + } else { + add_option($id, $value); + } + } + + function get_controllers() { + $controllers = array(); + $dir = json_api_dir(); + $dh = opendir("$dir/controllers"); + while ($file = readdir($dh)) { + if (preg_match('/(.+)\.php$/', $file, $matches)) { + $controllers[] = $matches[1]; + } + } + $controllers = apply_filters('json_api_controllers', $controllers); + return array_map('strtolower', $controllers); + } + + function controller_is_active($controller) { + if (defined('JSON_API_CONTROLLERS')) { + $default = JSON_API_CONTROLLERS; + } else { + $default = 'core'; + } + $active_controllers = explode(',', get_option('json_api_controllers', $default)); + return (in_array($controller, $active_controllers)); + } + + function update_controllers($controllers) { + if (is_array($controllers)) { + return implode(',', $controllers); + } else { + return $controllers; + } + } + + function controller_info($controller) { + $path = $this->controller_path($controller); + $class = $this->controller_class($controller); + $response = array( + 'name' => $controller, + 'description' => '(No description available)', + 'methods' => array() + ); + if (file_exists($path)) { + $source = file_get_contents($path); + if (preg_match('/^\s*Controller name:(.+)$/im', $source, $matches)) { + $response['name'] = trim($matches[1]); + } + if (preg_match('/^\s*Controller description:(.+)$/im', $source, $matches)) { + $response['description'] = trim($matches[1]); + } + if (preg_match('/^\s*Controller URI:(.+)$/im', $source, $matches)) { + $response['docs'] = trim($matches[1]); + } + if (!class_exists($class)) { + require_once($path); + } + $response['methods'] = get_class_methods($class); + return $response; + } else if (is_admin()) { + return "Cannot find controller class '$class' (filtered path: $path)."; + } else { + $this->error("Unknown controller '$controller'."); + } + return $response; + } + + function controller_class($controller) { + return "json_api_{$controller}_controller"; + } + + function controller_path($controller) { + $dir = json_api_dir(); + $controller_class = $this->controller_class($controller); + return apply_filters("{$controller_class}_path", "$dir/controllers/$controller.php"); + } + + function get_nonce_id($controller, $method) { + $controller = strtolower($controller); + $method = strtolower($method); + return "json_api-$controller-$method"; + } + + function flush_rewrite_rules() { + global $wp_rewrite; + $wp_rewrite->flush_rules(); + } + + function error($message = 'Unknown error', $status = 'error') { + $this->response->respond(array( + 'error' => $message + ), $status); + } + + function include_value($key) { + return $this->response->is_value_included($key); + } + +} + +?> diff --git a/singletons/introspector.php b/singletons/introspector.php new file mode 100644 index 0000000..35fc63a --- /dev/null +++ b/singletons/introspector.php @@ -0,0 +1,299 @@ +set_posts_query($query); + $output = array(); + while (have_posts()) { + the_post(); + if ($wp_posts) { + $output[] = $post; + } else { + $output[] = new JSON_API_Post($post); + } + } + return $output; + } + + public function get_date_archive_permalinks() { + $archives = wp_get_archives('echo=0'); + preg_match_all("/href='([^']+)'/", $archives, $matches); + return $matches[1]; + } + + public function get_date_archive_tree($permalinks) { + $tree = array(); + foreach ($permalinks as $url) { + if (preg_match('#(\d{4})/(\d{2})#', $url, $date)) { + $year = $date[1]; + $month = $date[2]; + } else if (preg_match('/(\d{4})(\d{2})/', $url, $date)) { + $year = $date[1]; + $month = $date[2]; + } else { + continue; + } + $count = $this->get_date_archive_count($year, $month); + if (empty($tree[$year])) { + $tree[$year] = array( + $month => $count + ); + } else { + $tree[$year][$month] = $count; + } + } + return $tree; + } + + public function get_date_archive_count($year, $month) { + if (!isset($this->month_archives)) { + global $wpdb; + $post_counts = $wpdb->get_results(" + SELECT DATE_FORMAT(post_date, '%Y%m') AS month, + COUNT(ID) AS post_count + FROM $wpdb->posts + WHERE post_status = 'publish' + AND post_type = 'post' + GROUP BY month + "); + $this->month_archives = array(); + foreach ($post_counts as $post_count) { + $this->month_archives[$post_count->month] = $post_count->post_count; + } + } + return $this->month_archives["$year$month"]; + } + + public function get_categories() { + $wp_categories = get_categories(); + $categories = array(); + foreach ($wp_categories as $wp_category) { + if ($wp_category->term_id == 1 && $wp_category->slug == 'uncategorized') { + continue; + } + $categories[] = $this->get_category_object($wp_category); + } + return $categories; + } + + public function get_current_category() { + global $json_api; + extract($json_api->query->get(array('id', 'slug', 'category_id', 'category_slug'))); + if ($id || $category_id) { + if (!$id) { + $id = $category_id; + } + return $this->get_category_by_id($id); + } else if ($slug || $category_slug) { + if (!$slug) { + $slug = $category_slug; + } + return $this->get_category_by_slug($slug); + } else { + $json_api->error("Include 'id' or 'slug' var in your request."); + } + return null; + } + + public function get_category_by_id($category_id) { + $wp_category = get_term_by('id', $category_id, 'category'); + return $this->get_category_object($wp_category); + } + + public function get_category_by_slug($category_slug) { + $wp_category = get_term_by('slug', $category_slug, 'category'); + return $this->get_category_object($wp_category); + } + + public function get_tags() { + $wp_tags = get_tags(); + return array_map(array(&$this, 'get_tag_object'), $wp_tags); + } + + public function get_current_tag() { + global $json_api; + extract($json_api->query->get(array('id', 'slug', 'tag_id', 'tag_slug'))); + if ($id || $tag_id) { + if (!$id) { + $id = $tag_id; + } + return $this->get_tag_by_id($id); + } else if ($slug || $tag_slug) { + if (!$slug) { + $slug = $tag_slug; + } + return $this->get_tag_by_slug($slug); + } else { + $json_api->error("Include 'id' or 'slug' var in your request."); + } + return null; + } + + public function get_tag_by_id($tag_id) { + $wp_tag = get_term_by('id', $tag_id, 'post_tag'); + return $this->get_tag_object($wp_tag); + } + + public function get_tag_by_slug($tag_slug) { + $wp_tag = get_term_by('slug', $tag_slug, 'post_tag'); + return $this->get_tag_object($wp_tag); + } + + public function get_authors() { + global $wpdb; + $author_ids = $wpdb->get_col($wpdb->prepare(" + SELECT u.ID, m.meta_value AS last_name + FROM $wpdb->users AS u, + $wpdb->usermeta AS m + WHERE m.user_id = u.ID + AND m.meta_key = 'last_name' + ORDER BY last_name + ")); + $all_authors = array_map(array(&$this, 'get_author_by_id'), $author_ids); + $active_authors = array_filter($all_authors, array(&$this, 'is_active_author')); + return $active_authors; + } + + public function get_current_author() { + global $json_api; + extract($json_api->query->get(array('id', 'slug', 'author_id', 'author_slug'))); + if ($id || $author_id) { + if (!$id) { + $id = $author_id; + } + return $this->get_author_by_id($id); + } else if ($slug || $author_slug) { + if (!$slug) { + $slug = $author_slug; + } + return $this->get_author_by_login($slug); + } else { + $json_api->error("Include 'id' or 'slug' var in your request."); + } + return null; + } + + public function get_author_by_id($id) { + $id = get_the_author_meta('ID', $id); + if (!$id) { + return null; + } + return new JSON_API_Author($id); + } + + public function get_author_by_login($login) { + global $wpdb; + $id = $wpdb->get_var($wpdb->prepare(" + SELECT ID + FROM $wpdb->users + WHERE user_nicename = %s + ", $login)); + return $this->get_author_by_id($id); + } + + public function get_comments($post_id) { + global $wpdb; + $wp_comments = $wpdb->get_results($wpdb->prepare(" + SELECT * + FROM $wpdb->comments + WHERE comment_post_ID = %d + AND comment_approved = 1 + AND comment_type = '' + ORDER BY comment_date + ", $post_id)); + $comments = array(); + foreach ($wp_comments as $wp_comment) { + $comments[] = new JSON_API_Comment($wp_comment); + } + return $comments; + } + + public function get_attachments($post_id) { + $wp_attachments = get_children(array( + 'post_type' => 'attachment', + 'post_parent' => $post_id, + 'orderby' => 'menu_order', + 'order' => 'ASC' + )); + $attachments = array(); + if (!empty($wp_attachments)) { + foreach ($wp_attachments as $wp_attachment) { + $attachments[] = new JSON_API_Attachment($wp_attachment); + } + } + return $attachments; + } + + public function attach_child_posts(&$post) { + $post->children = array(); + $wp_children = get_posts(array( + 'post_type' => $post->type, + 'post_parent' => $post->id, + 'order' => 'ASC', + 'orderby' => 'menu_order' + )); + foreach ($wp_children as $wp_post) { + $post->children[] = new JSON_API_Post($wp_post); + } + foreach ($post->children as $child) { + $this->attach_child_posts($child); + } + } + + protected function get_category_object($wp_category) { + if (!$wp_category) { + return null; + } + return new JSON_API_Category($wp_category); + } + + protected function get_tag_object($wp_tag) { + if (!$wp_tag) { + return null; + } + return new JSON_API_Tag($wp_tag); + } + + protected function is_active_author($author) { + if (!isset($this->active_authors)) { + $this->active_authors = explode(',', wp_list_authors(array( + 'html' => false, + 'echo' => false, + 'exclude_admin' => false + ))); + $this->active_authors = array_map('trim', $this->active_authors); + } + return in_array($author->name, $this->active_authors); + } + + protected function set_posts_query($query = false) { + global $json_api, $wp_query; + + if (!$query) { + $query = array(); + } + + $query = array_merge($query, $wp_query->query); + + if ($json_api->query->page) { + $query['paged'] = $json_api->query->page; + } + + if ($json_api->query->count) { + $query['posts_per_page'] = $json_api->query->count; + } + + if ($json_api->query->post_type) { + $query['post_type'] = $json_api->query->post_type; + } + + if (!empty($query)) { + query_posts($query); + } + } + +} + +?> diff --git a/singletons/query.php b/singletons/query.php new file mode 100644 index 0000000..f01e906 --- /dev/null +++ b/singletons/query.php @@ -0,0 +1,194 @@ + 'Y-m-d H:i:s', + 'read_more' => 'Read more' + ); + + function __construct() { + // Register JSON API query vars + add_filter('query_vars', array(&$this, 'query_vars')); + } + + function get($key) { + if (is_array($key)) { + $result = array(); + foreach ($key as $k) { + $result[$k] = $this->get($k); + } + return $result; + } + $query_var = (isset($_REQUEST[$key])) ? $_REQUEST[$key] : null; + $wp_query_var = $this->wp_query_var($key); + if ($wp_query_var) { + return $wp_query_var; + } else if ($query_var) { + return $this->strip_magic_quotes($query_var); + } else if (isset($this->defaults[$key])) { + return $this->defaults[$key]; + } else { + return null; + } + } + + function __get($key) { + return $this->get($key); + } + + function __isset($key) { + return ($this->get($key) !== null); + } + + function wp_query_var($key) { + $wp_translation = array( + 'json' => 'json', + 'post_id' => 'p', + 'post_slug' => 'name', + 'page_id' => 'page_id', + 'page_slug' => 'name', + 'category_id' => 'cat', + 'category_slug' => 'category_name', + 'tag_id' => 'tag_id', + 'tag_slug' => 'tag', + 'author_id' => 'author', + 'author_slug' => 'author_name', + 'search' => 's', + 'order' => 'order', + 'order_by' => 'orderby' + ); + if ($key == 'date') { + $date = null; + if (get_query_var('year')) { + $date = get_query_var('year'); + } + if (get_query_var('monthnum')) { + $month = get_query_var('monthnum'); + if ($month < 10) { + $month = "0$month"; + } + $date .= $month; + } + if (get_query_var('day')) { + $day = get_query_var('day'); + if ($day < 10) { + $day = "0$day"; + } + $date .= $day; + } + return $date; + } else if (isset($wp_translation[$key])) { + return get_query_var($wp_translation[$key]); + } else { + return null; + } + } + + function strip_magic_quotes($value) { + if (get_magic_quotes_gpc()) { + return stripslashes($value); + } else { + return $value; + } + } + + function query_vars($wp_vars) { + $wp_vars[] = 'json'; + return $wp_vars; + } + + function get_controller() { + $json = $this->get('json'); + if (empty($json)) { + return false; + } + if (preg_match('/^[a-zA-Z_]+$/', $json)) { + return $this->get_legacy_controller($json); + } else if (preg_match('/^([a-zA-Z_]+)(\/|\.)[a-zA-Z_]+$/', $json, $matches)) { + return $matches[1]; + } else { + return 'core'; + } + } + + function get_legacy_controller($json) { + global $json_api; + if ($json == 'submit_comment') { + if ($json_api->controller_is_active('respond')) { + return 'respond'; + } else { + $json_api->error("The 'submit_comment' method has been removed from the Core controller. To use this method you must enable the Respond controller from WP Admin > Settings > JSON API."); + } + } else if ($json == 'create_post') { + if ($json_api->controller_is_active('posts')) { + return 'posts'; + } else { + $json_api->error("The 'create_post' method has been removed from the Core controller. To use this method you must enable the Posts controller from WP Admin > Settings > JSON API."); + } + } else { + return 'core'; + } + } + + function get_method($controller) { + + global $json_api; + + // Returns an appropriate API method name or false. Four possible outcomes: + // 1. API isn't being invoked at all (return false) + // 2. A specific API method was requested (return method name) + // 3. A method is chosen implicitly on a given WordPress page + // 4. API invoked incorrectly (return "error" method) + // + // Note: + // The implicit outcome (3) is invoked by setting the json query var to a + // non-empty value on any WordPress page: + // * http://example.org/2009/11/10/hello-world/?json=1 (get_post) + // * http://example.org/2009/11/?json=1 (get_date_posts) + // * http://example.org/category/foo?json=1 (get_category_posts) + + $method = $this->get('json'); + if (strpos($method, '/') !== false) { + $method = substr($method, strpos($method, '/') + 1); + } else if (strpos($method, '.') !== false) { + $method = substr($method, strpos($method, '.') + 1); + } + + if (empty($method)) { + // Case 1: we're not being invoked (done!) + return false; + } else if (method_exists("JSON_API_{$controller}_Controller", $method)) { + // Case 2: an explicit method was specified + return $method; + } else if ($controller == 'core') { + // Case 3: choose the method implicitly based on which page we're on... + if (is_search()) { + return 'get_search_results'; + } else if (is_home()) { + if (empty($_GET['json'])) { + $json_api->error("Uknown method '$method'."); + } + return 'get_recent_posts'; + } else if (is_page()) { + return 'get_page'; + } else if (is_single()) { + return 'get_post'; + } else if (is_category()) { + return 'get_category_posts'; + } else if (is_tag()) { + return 'get_tag_posts'; + } else if (is_author()) { + return 'get_author_posts'; + } else if (is_date()) { + return 'get_date_posts'; + } else if (is_404()) { + return '404'; + } + } + // Case 4: either the method doesn't exist or we don't support the page implicitly + return 'error'; + } + +} diff --git a/singletons/response.php b/singletons/response.php new file mode 100644 index 0000000..2479709 --- /dev/null +++ b/singletons/response.php @@ -0,0 +1,184 @@ +include_values = array(); + $this->exclude_values = array(); + if ($json_api->query->include) { + $this->include_values = explode(',', $json_api->query->include); + } + // Props to ikesyo for submitting a fix! + if ($json_api->query->exclude) { + $this->exclude_values = explode(',', $json_api->query->exclude); + $this->include_values = array_diff($this->include_values, $this->exclude_values); + } + + // Compatibility with Disqus plugin + remove_action('loop_end', 'dsq_loop_end'); + } + + function get_json($data, $status = 'ok') { + // Include a status value with the response + if (is_array($data)) { + $data = array_merge(array('status' => $status), $data); + } else if (is_object($data)) { + $data = get_object_vars($data); + $data = array_merge(array('status' => $status), $data); + } + + $data = apply_filters('json_api_encode', $data); + + if (function_exists('json_encode')) { + // Use the built-in json_encode function if it's available + return json_encode($data); + } else { + // Use PEAR's Services_JSON encoder otherwise + if (!class_exists('Services_JSON')) { + $dir = json_api_dir(); + require_once "$dir/library/JSON.php"; + } + $json = new Services_JSON(); + return $json->encode($data); + } + } + + function is_value_included($key) { + // Props to ikesyo for submitting a fix! + if (empty($this->include_values) && empty($this->exclude_values)) { + return true; + } else { + if (empty($this->exclude_values)) { + return in_array($key, $this->include_values); + } else { + return !in_array($key, $this->exclude_values); + } + } + } + + function respond($result, $status = 'ok') { + global $json_api; + $json = $this->get_json($result, $status); + $status_redirect = "redirect_$status"; + if ($json_api->query->dev || !empty($_REQUEST['dev'])) { + // Output the result in a human-redable format + if (!headers_sent()) { + header('HTTP/1.1 200 OK'); + header('Content-Type: text/plain; charset: UTF-8', true); + } else { + echo '
';
+      }
+      echo $this->prettify($json);
+    } else if (!empty($_REQUEST[$status_redirect])) {
+      wp_redirect($_REQUEST[$status_redirect]);
+    } else if ($json_api->query->redirect) {
+      $url = $this->add_status_query_var($json_api->query->redirect, $status);
+      wp_redirect($url);
+    } else if ($json_api->query->callback) {
+      // Run a JSONP-style callback with the result
+      $this->callback($json_api->query->callback, $json);
+    } else {
+      // Output the result
+      $this->output($json);
+    }
+    exit;
+  }
+  
+  function output($result) {
+    $charset = get_option('blog_charset');
+    if (!headers_sent()) {
+      header('HTTP/1.1 200 OK', true);
+      header("Content-Type: application/json; charset=$charset", true);
+    }
+    echo $result;
+  }
+  
+  function callback($callback, $result) {
+    $charset = get_option('blog_charset');
+    if (!headers_sent()) {
+      header('HTTP/1.1 200 OK', true);
+      header("Content-Type: application/javascript; charset=$charset", true);
+    }
+    echo "$callback($result)";
+  }
+  
+  function add_status_query_var($url, $status) {
+    if (strpos($url, '#')) {
+      // Remove the anchor hash for now
+      $pos = strpos($url, '#');
+      $anchor = substr($url, $pos);
+      $url = substr($url, 0, $pos);
+    }
+    if (strpos($url, '?')) {
+      $url .= "&status=$status";
+    } else {
+      $url .= "?status=$status";
+    }
+    if (!empty($anchor)) {
+      // Add the anchor hash back in
+      $url .= $anchor;
+    }
+    return $url;
+  }
+  
+  function prettify($ugly) {
+    $pretty = "";
+    $indent = "";
+    $last = '';
+    $pos = 0;
+    $level = 0;
+    $string = false;
+    while ($pos < strlen($ugly)) {
+      $char = substr($ugly, $pos++, 1);
+      if (!$string) {
+        if ($char == '{' || $char == '[') {
+          if ($char == '[' && substr($ugly, $pos, 1) == ']') {
+            $pretty .= "[]";
+            $pos++;
+          } else if ($char == '{' && substr($ugly, $pos, 1) == '}') {
+            $pretty .= "{}";
+            $pos++;
+          } else {
+            $pretty .= "$char\n";
+            $indent = str_repeat('  ', ++$level);
+            $pretty .= "$indent";
+          }
+        } else if ($char == '}' || $char == ']') {
+          $indent = str_repeat('  ', --$level);
+          if ($last != '}' && $last != ']') {
+            $pretty .= "\n$indent";
+          } else if (substr($pretty, -2, 2) == '  ') {
+            $pretty = substr($pretty, 0, -2);
+          }
+          $pretty .= $char;
+          if (substr($ugly, $pos, 1) == ',') {
+            $pretty .= ",";
+            $last = ',';
+            $pos++;
+          }
+          $pretty .= "\n$indent";
+        } else if ($char == ':') {
+          $pretty .= ": ";
+        } else if ($char == ',') {
+          $pretty .= ",\n$indent";
+        } else if ($char == '"') {
+          $pretty .= '"';
+          $string = true;
+        } else {
+          $pretty .= $char;
+        }
+      } else {
+        if ($last != '\\' && $char == '"') {
+          $string = false;
+        }
+        $pretty .= $char;
+      }
+      $last = $char;
+    }
+    return $pretty;
+  }
+  
+}
+
+?>
diff --git a/tests/core.get_author_index-01.phpt b/tests/core.get_author_index-01.phpt
new file mode 100644
index 0000000..5db2dfd
--- /dev/null
+++ b/tests/core.get_author_index-01.phpt
@@ -0,0 +1,14 @@
+--TEST--
+core.get_author_index
+--FILE--
+get('http://wordpress.test/?json=core.get_author_index');
+$response = $http->currentResponse();
+echo $response['body'];
+
+?>
+--EXPECT--
+{"status":"ok","count":2,"authors":[{"id":3,"slug":"chip-bennett","name":"Chip Bennett","first_name":"","last_name":"","nickname":"Chip Bennett","url":"","description":""},{"id":4,"slug":"ian-stewart","name":"Ian Stewart","first_name":"","last_name":"","nickname":"Ian Stewart","url":"","description":""}]}
diff --git a/tests/core.get_author_posts-01.phpt b/tests/core.get_author_posts-01.phpt
new file mode 100644
index 0000000..cfed798
--- /dev/null
+++ b/tests/core.get_author_posts-01.phpt
@@ -0,0 +1,14 @@
+--TEST--
+core.get_author_posts by slug
+--FILE--
+get('http://wordpress.test/?json=core.get_author_posts&slug=chip-bennett');
+$response = $http->currentResponse();
+echo $response['body'];
+
+?>
+--EXPECT--
+{"status":"ok","count":10,"pages":3,"author":{"id":3,"slug":"chip-bennett","name":"Chip Bennett","first_name":"","last_name":"","nickname":"Chip Bennett","url":"","description":""},"posts":[{"id":358,"type":"post","slug":"readability-test","url":"http:\/\/wordpress.test\/2008\/09\/05\/readability-test\/","status":"publish","title":"Readability Test","title_plain":"Readability Test","content":"

All children, except one, grow up. They soon know that they will grow up, and the way Wendy knew was this. One day when she was two years old she was playing in a garden, and she plucked another flower and ran with it to her mother. I suppose she must have looked rather delightful, for Mrs. Darling put her hand to her heart and cried, “Oh, why can’t you remain like this for ever!” This was all that passed between them on the subject, but henceforth Wendy knew that she must grow up. You always know after you are two. Two is the beginning of the end.<\/p>\n

Read more<\/a><\/p>\n","excerpt":"All children, except one, grow up. They soon know that they will grow up, and the way Wendy knew was this. One day when she was two years old she was playing in a garden, and she plucked another flower … Continue reading →<\/span><\/a>","date":"2008-09-05 00:27:25","modified":"2008-09-05 00:27:25","categories":[{"id":9,"slug":"cat-a","title":"Cat A","description":"","parent":0,"post_count":2}],"tags":[{"id":53,"slug":"chattels","title":"chattels","description":"","post_count":2},{"id":82,"slug":"privation","title":"privation","description":"","post_count":2}],"author":{"id":3,"slug":"chip-bennett","name":"Chip Bennett","first_name":"","last_name":"","nickname":"Chip Bennett","url":"","description":""},"comments":[],"attachments":[],"comment_count":0,"comment_status":"closed"},{"id":188,"type":"post","slug":"layout-test","url":"http:\/\/wordpress.test\/2008\/09\/04\/layout-test\/","status":"publish","title":"Layout Test","title_plain":"Layout Test","content":"

This is a sticky post!!! Make sure it sticks!<\/p>\n

This should then split into other pages with layout, images, HTML tags, and other things.<\/p>\n","excerpt":"This is a sticky post!!! Make sure it sticks! This should then split into other pages with layout, images, HTML tags, and other things.","date":"2008-09-04 23:02:20","modified":"2008-09-04 23:02:20","categories":[{"id":3,"slug":"aciform","title":"aciform","description":"","parent":0,"post_count":2},{"id":9,"slug":"cat-a","title":"Cat A","description":"","parent":0,"post_count":2},{"id":10,"slug":"cat-b","title":"Cat B","description":"","parent":0,"post_count":1},{"id":11,"slug":"cat-c","title":"Cat C","description":"","parent":0,"post_count":1},{"id":41,"slug":"sub","title":"sub","description":"","parent":3,"post_count":1}],"tags":[{"id":93,"slug":"tag1","title":"tag1","description":"","post_count":1},{"id":94,"slug":"tag2","title":"tag2","description":"","post_count":1},{"id":95,"slug":"tag3","title":"tag3","description":"","post_count":1}],"author":{"id":3,"slug":"chip-bennett","name":"Chip Bennett","first_name":"","last_name":"","nickname":"Chip Bennett","url":"","description":""},"comments":[],"attachments":[],"comment_count":0,"comment_status":"closed"},{"id":128,"type":"post","slug":"images-test","url":"http:\/\/wordpress.test\/2008\/09\/03\/images-test\/","status":"publish","title":"Images Test","title_plain":"Images Test","content":"

Image Alignment Tests: Un-Captioned Images<\/h2>\n

Center-align, no caption<\/h3>\n

Center-aligned image with no caption, and text before and after. \"\" ALorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl. Quisque quis urna in velit dictum pellentesque. Vivamus a quam. Curabitur eu tortor id turpis tristique adipiscing. Morbi blandit. Maecenas vel est. Nunc aliquam, orci at accumsan commodo, libero nibh euismod augue, a ullamcorper velit dui et purus. Aenean volutpat, ipsum ac imperdiet fermentum, dui dui suscipit arcu, vitae dictum purus diam ac ligula.<\/p>\n

Left-align, no caption<\/h3>\n

Left-aligned image with no caption, and text before and after. \"\" Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl. Quisque quis urna in velit dictum pellentesque. Vivamus a quam. Curabitur eu tortor id turpis tristique adipiscing. Morbi blandit. Maecenas vel est. Nunc aliquam, orci at accumsan commodo, libero nibh euismod augue, a ullamcorper velit dui et purus. Aenean volutpat, ipsum ac imperdiet fermentum, dui dui suscipit arcu, vitae dictum purus diam ac ligula.<\/p>\n

Right-align, no caption<\/h3>\n

Right-aligned image with no caption, and text before and after. \"\" Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl. Quisque quis urna in velit dictum pellentesque. Vivamus a quam. Curabitur eu tortor id turpis tristique adipiscing. Morbi blandit. Maecenas vel est. Nunc aliquam, orci at accumsan commodo, libero nibh euismod augue, a ullamcorper velit dui et purus. Aenean volutpat, ipsum ac imperdiet fermentum, dui dui suscipit arcu, vitae dictum purus diam ac ligula.<\/p>\n

No alignment, no caption<\/h3>\n

None-aligned image with no caption, and text before and after. \"\" Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae nisl. Quisque quis urna in velit dictum pellentesque. Vivamus a quam. Curabitur eu tortor id turpis tristique adipiscing. Morbi blandit. Maecenas vel est. Nunc aliquam, orci at accumsan commodo, libero nibh euismod augue, a ullamcorper velit dui et purus. Aenean volutpat, ipsum ac imperdiet fermentum, dui dui suscipit arcu, vitae dictum purus diam ac ligula.<\/p>\n","excerpt":"Image Alignment Tests: Un-Captioned Images Center-align, no caption Center-aligned image with no caption, and text before and after. ALorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed odio nibh, tincidunt adipiscing, pretium nec, tincidunt id, enim. Fusce scelerisque nunc vitae … Continue reading →<\/span><\/a>","date":"2008-09-03 09:35:23","modified":"2008-09-03 09:35:23","categories":[],"tags":[],"author":{"id":3,"slug":"chip-bennett","name":"Chip Bennett","first_name":"","last_name":"","nickname":"Chip Bennett","url":"","description":""},"comments":[],"attachments":[{"id":534,"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape-9001.jpg","slug":"test-image-landscape-900","title":"test-image-landscape-900","description":"","caption":"","parent":128,"mime_type":"image\/jpeg","images":{"full":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape-9001.jpg","width":900,"height":598},"thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape-9001.jpg","width":150,"height":99},"medium":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape-9001.jpg","width":300,"height":199},"large":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape-9001.jpg","width":640,"height":425},"post-thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape-9001.jpg","width":297,"height":198}}},{"id":535,"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape1.jpg","slug":"test-image-landscape","title":"test-image-landscape","description":"","caption":"","parent":128,"mime_type":"image\/jpeg","images":{"full":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape1.jpg","width":300,"height":199},"thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape1.jpg","width":150,"height":99},"medium":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape1.jpg","width":300,"height":199},"large":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape1.jpg","width":300,"height":199},"post-thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-landscape1.jpg","width":298,"height":198}}},{"id":536,"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-portrait1.jpg","slug":"test-image-portrait","title":"test-image-portrait","description":"","caption":"","parent":128,"mime_type":"image\/jpeg","images":{"full":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-portrait1.jpg","width":199,"height":300},"thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-portrait1.jpg","width":99,"height":150},"medium":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-portrait1.jpg","width":199,"height":300},"large":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-portrait1.jpg","width":199,"height":300},"post-thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/test-image-portrait1.jpg","width":131,"height":198}}},{"id":543,"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/spectacles1.gif","slug":"spectacles","title":"spectacles","description":"","caption":"","parent":128,"mime_type":"image\/gif","images":{"full":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/spectacles1.gif","width":165,"height":210},"thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/spectacles1.gif","width":117,"height":150},"medium":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/spectacles1.gif","width":165,"height":210},"large":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/spectacles1.gif","width":165,"height":210},"post-thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/spectacles1.gif","width":155,"height":198}}},{"id":544,"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/boat1.jpg","slug":"boat","title":"boat","description":"","caption":"A picture is worth a thousand words","parent":128,"mime_type":"image\/jpeg","images":{"full":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/boat1.jpg","width":435,"height":288},"thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/boat1.jpg","width":150,"height":99},"medium":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/boat1.jpg","width":300,"height":198},"large":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/boat1.jpg","width":435,"height":288},"post-thumbnail":{"url":"http:\/\/wordpress.test\/wp-content\/uploads\/2010\/08\/boat1.jpg","width":299,"height":198}}}],"comment_count":0,"comment_status":"closed"},{"id":555,"type":"post","slug":"post-format-test-gallery","url":"http:\/\/wordpress.test\/2008\/06\/10\/post-format-test-gallery\/","status":"publish","title":"Post Format Test: Gallery","title_plain":"Post Format Test: Gallery","content":"\n\t\t