3 * Atom Publishing Protocol support for WordPress
5 * @author Original by Elias Torres <http://torrez.us/archives/2006/08/31/491/>
6 * @author Modified by Dougal Campbell <http://dougal.gunters.org/>
11 * WordPress is handling an Atom Publishing Protocol request.
15 define('APP_REQUEST', true);
17 /** Set up WordPress environment */
18 require_once('./wp-load.php');
20 /** Post Template API */
21 require_once(ABSPATH . WPINC . '/post-template.php');
23 /** Atom Publishing Protocol Class */
24 require_once(ABSPATH . WPINC . '/atomlib.php');
26 /** Feed Handling API */
27 require_once(ABSPATH . WPINC . '/feed.php');
29 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
32 * Whether to enable Atom Publishing Protocol Logging.
40 * Whether to always authenticate user. Permanently set to true.
42 * @name always_authenticate
44 * @todo Should be an option somewhere
46 $always_authenticate = 1;
49 * Writes logging info to a file.
56 * @param string $label Type of logging
57 * @param string $msg Information describing logging reason.
59 function log_app($label,$msg) {
62 $fp = fopen( 'wp-app.log', 'a+');
63 $date = gmdate( 'Y-m-d H:i:s' );
64 fwrite($fp, "\n\n$date - $label\n$msg\n");
69 if ( !function_exists('wp_set_current_user') ) :
73 function wp_set_current_user($id, $name = '') {
76 if ( isset($current_user) && ($id == $current_user->ID) )
79 $current_user = new WP_User($id, $name);
86 * Filter to add more post statuses.
90 * @param string $where SQL statement to filter.
91 * @return string Filtered SQL statement with added post_status for where clause.
93 function wa_posts_where_include_drafts_filter($where) {
94 $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where);
98 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
101 * WordPress AtomPub API implementation.
104 * @subpackage Publishing
115 var $ATOM_CONTENT_TYPE = 'application/atom+xml';
118 * Categories ATOM content type.
123 var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
126 * Service ATOM content type.
131 var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
134 * ATOM XML namespace.
139 var $ATOM_NS = 'http://www.w3.org/2005/Atom';
142 * ATOMPUB XML namespace.
147 var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
155 var $ENTRIES_PATH = "posts";
163 var $CATEGORIES_PATH = "categories";
171 var $MEDIA_PATH = "attachments";
179 var $ENTRY_PATH = "post";
187 var $SERVICE_PATH = "service";
195 var $MEDIA_SINGLE_PATH = "attachment";
198 * ATOMPUB parameters.
203 var $params = array();
206 * Supported ATOMPUB media types.
211 var $media_content_types = array('image/*','audio/*','video/*');
214 * ATOMPUB content type(s).
219 var $atom_content_types = array('application/atom+xml');
227 var $selectors = array();
230 * Whether to do output.
237 var $do_output = true;
240 * PHP4 constructor - Sets up object properties.
245 function AtomServer() {
247 $this->script_name = array_pop(explode('/',$_SERVER['SCRIPT_NAME']));
248 $this->app_base = get_bloginfo('url') . '/' . $this->script_name . '/';
249 if ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) {
250 $this->app_base = preg_replace( '/^http:\/\//', 'https://', $this->app_base );
253 $this->selectors = array(
255 array('GET' => 'get_service'),
257 array('GET' => 'get_categories_xml'),
259 array('GET' => 'get_post',
261 'DELETE' => 'delete_post'),
262 '@/posts/?(\d+)?$@' =>
263 array('GET' => 'get_posts',
264 'POST' => 'create_post'),
265 '@/attachments/?(\d+)?$@' =>
266 array('GET' => 'get_attachment',
267 'POST' => 'create_attachment'),
268 '@/attachment/file/(\d+)$@' =>
269 array('GET' => 'get_file',
271 'DELETE' => 'delete_file'),
272 '@/attachment/(\d+)$@' =>
273 array('GET' => 'get_attachment',
274 'PUT' => 'put_attachment',
275 'DELETE' => 'delete_attachment'),
280 * Handle ATOMPUB request.
284 function handle_request() {
285 global $always_authenticate;
287 if( !empty( $_SERVER['ORIG_PATH_INFO'] ) )
288 $path = $_SERVER['ORIG_PATH_INFO'];
290 $path = $_SERVER['PATH_INFO'];
292 $method = $_SERVER['REQUEST_METHOD'];
294 log_app('REQUEST',"$method $path\n================");
296 $this->process_conditionals();
297 //$this->process_conditionals();
299 // exception case for HEAD (treat exactly as GET, but don't output)
300 if($method == 'HEAD') {
301 $this->do_output = false;
305 // redirect to /service in case no path is found.
306 if(strlen($path) == 0 || $path == '/') {
307 $this->redirect($this->get_service_url());
310 // check to see if AtomPub is enabled
311 if( !get_option( 'enable_app' ) )
312 $this->forbidden( sprintf( __( 'AtomPub services are disabled on this blog. An admin user can enable them at %s' ), admin_url('options-writing.php') ) );
315 foreach($this->selectors as $regex => $funcs) {
316 if(preg_match($regex, $path, $matches)) {
317 if(isset($funcs[$method])) {
319 // authenticate regardless of the operation and set the current
320 // user. each handler will decide if auth is required or not.
321 if(!$this->authenticate()) {
322 if ($always_authenticate) {
323 $this->auth_required('Credentials required.');
327 array_shift($matches);
328 call_user_func_array(array(&$this,$funcs[$method]), $matches);
331 // only allow what we have handlers for...
332 $this->not_allowed(array_keys($funcs));
337 // oops, nothing found
342 * Retrieve XML for ATOMPUB service.
346 function get_service() {
347 log_app('function','get_service()');
349 if( !current_user_can( 'edit_posts' ) )
350 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
352 $entries_url = attribute_escape($this->get_entries_url());
353 $categories_url = attribute_escape($this->get_categories_url());
354 $media_url = attribute_escape($this->get_attachments_url());
355 foreach ($this->media_content_types as $med) {
356 $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
359 $atom_blogname=get_bloginfo('name');
360 $service_doc = <<<EOD
361 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
363 <$atom_prefix:title>$atom_blogname Workspace</$atom_prefix:title>
364 <collection href="$entries_url">
365 <$atom_prefix:title>$atom_blogname Posts</$atom_prefix:title>
366 <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
367 <categories href="$categories_url" />
369 <collection href="$media_url">
370 <$atom_prefix:title>$atom_blogname Media</$atom_prefix:title>
371 $accepted_media_types
378 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
382 * Retrieve categories list in XML format.
386 function get_categories_xml() {
387 log_app('function','get_categories_xml()');
389 if( !current_user_can( 'edit_posts' ) )
390 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
392 $home = attribute_escape(get_bloginfo_rss('home'));
395 $cats = get_categories("hierarchical=0&hide_empty=0");
396 foreach ((array) $cats as $cat) {
397 $categories .= " <category term=\"" . attribute_escape($cat->name) . "\" />\n";
400 <app:categories xmlns:app="$this->ATOMPUB_NS"
401 xmlns="$this->ATOM_NS"
402 fixed="yes" scheme="$home">
406 $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
414 function create_post() {
415 global $blog_id, $user_ID;
416 $this->get_accepted_content_type($this->atom_content_types);
418 $parser = new AtomParser();
419 if(!$parser->parse()) {
420 $this->client_error();
423 $entry = array_pop($parser->feed->entries);
425 log_app('Received entry:', print_r($entry,true));
428 foreach($entry->categories as $cat)
429 array_push($catnames, $cat["term"]);
431 $wp_cats = get_categories(array('hide_empty' => false));
433 $post_category = array();
435 foreach($wp_cats as $cat) {
436 if(in_array($cat->name, $catnames))
437 array_push($post_category, $cat->term_id);
440 $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
442 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
444 if(!current_user_can($cap))
445 $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
447 $blog_ID = (int ) $blog_id;
448 $post_status = ($publish) ? 'publish' : 'draft';
449 $post_author = (int) $user_ID;
450 $post_title = $entry->title[1];
451 $post_content = $entry->content[1];
452 $post_excerpt = $entry->summary[1];
453 $pubtimes = $this->get_publish_time($entry->published);
454 $post_date = $pubtimes[0];
455 $post_date_gmt = $pubtimes[1];
457 if ( isset( $_SERVER['HTTP_SLUG'] ) )
458 $post_name = $_SERVER['HTTP_SLUG'];
460 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
462 $this->escape($post_data);
463 log_app('Inserting Post. Data:', print_r($post_data,true));
465 $postID = wp_insert_post($post_data);
466 if ( is_wp_error( $postID ) )
467 $this->internal_error($postID->get_error_message());
470 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
472 // getting warning here about unable to set headers
473 // because something in the cache is printing to the buffer
474 // could we clean up wp_set_post_categories or cache to not print
475 // this could affect our ability to send back the right headers
476 @wp_set_post_categories($postID, $post_category);
478 $output = $this->get_entry($postID);
480 log_app('function',"create_post($postID)");
481 $this->created($postID, $output);
489 * @param int $postID Post ID.
491 function get_post($postID) {
494 if( !current_user_can( 'edit_post', $postID ) )
495 $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
497 $this->set_current_entry($postID);
498 $output = $this->get_entry($postID);
499 log_app('function',"get_post($postID)");
500 $this->output($output);
509 * @param int $postID Post ID.
511 function put_post($postID) {
512 // checked for valid content-types (atom+xml)
513 // quick check and exit
514 $this->get_accepted_content_type($this->atom_content_types);
516 $parser = new AtomParser();
517 if(!$parser->parse()) {
518 $this->bad_request();
521 $parsed = array_pop($parser->feed->entries);
523 log_app('Received UPDATED entry:', print_r($parsed,true));
525 // check for not found
527 $this->set_current_entry($postID);
529 if(!current_user_can('edit_post', $entry['ID']))
530 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
532 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
533 $post_status = ($publish) ? 'publish' : 'draft';
537 $post_title = $parsed->title[1];
538 $post_content = $parsed->content[1];
539 $post_excerpt = $parsed->summary[1];
540 $pubtimes = $this->get_publish_time($entry->published);
541 $post_date = $pubtimes[0];
542 $post_date_gmt = $pubtimes[1];
543 $pubtimes = $this->get_publish_time($parsed->updated);
544 $post_modified = $pubtimes[0];
545 $post_modified_gmt = $pubtimes[1];
547 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
548 $this->escape($postdata);
550 $result = wp_update_post($postdata);
553 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
556 log_app('function',"put_post($postID)");
565 * @param int $postID Post ID.
567 function delete_post($postID) {
569 // check for not found
571 $this->set_current_entry($postID);
573 if(!current_user_can('edit_post', $postID)) {
574 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
577 if ($entry['post_type'] == 'attachment') {
578 $this->delete_attachment($postID);
580 $result = wp_delete_post($postID);
583 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
586 log_app('function',"delete_post($postID)");
593 * Retrieve attachment.
597 * @param int $postID Optional. Post ID.
599 function get_attachment($postID = null) {
600 if( !current_user_can( 'upload_files' ) )
601 $this->auth_required( __( 'Sorry, you do not have permission to upload files.' ) );
603 if (!isset($postID)) {
604 $this->get_attachments();
606 $this->set_current_entry($postID);
607 $output = $this->get_entry($postID, 'attachment');
608 log_app('function',"get_attachment($postID)");
609 $this->output($output);
614 * Create new attachment.
618 function create_attachment() {
620 $type = $this->get_accepted_content_type();
622 if(!current_user_can('upload_files'))
623 $this->auth_required(__('You do not have permission to upload files.'));
625 $fp = fopen("php://input", "rb");
628 $bits .= fread($fp, 4096);
633 if ( isset( $_SERVER['HTTP_SLUG'] ) )
634 $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] );
635 elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
636 $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] );
637 elseif ( empty( $slug ) ) // just make a random name
638 $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
639 $ext = preg_replace( '|.*/([a-z0-9]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
640 $slug = "$slug.$ext";
641 $file = wp_upload_bits( $slug, NULL, $bits);
643 log_app('wp_upload_bits returns:',print_r($file,true));
646 $file = $file['file'];
648 do_action('wp_create_file_in_uploads', $file); // replicate
650 // Construct the attachment array
652 'post_title' => $slug,
653 'post_content' => $slug,
654 'post_status' => 'attachment',
656 'post_mime_type' => $type,
661 $postID = wp_insert_attachment($attachment, $file);
664 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
666 $output = $this->get_entry($postID, 'attachment');
668 $this->created($postID, $output, 'attachment');
669 log_app('function',"create_attachment($postID)");
677 * @param int $postID Post ID.
679 function put_attachment($postID) {
680 // checked for valid content-types (atom+xml)
681 // quick check and exit
682 $this->get_accepted_content_type($this->atom_content_types);
684 $parser = new AtomParser();
685 if(!$parser->parse()) {
686 $this->bad_request();
689 $parsed = array_pop($parser->feed->entries);
691 // check for not found
693 $this->set_current_entry($postID);
695 if(!current_user_can('edit_post', $entry['ID']))
696 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
700 $post_title = $parsed->title[1];
701 $post_content = $parsed->content[1];
702 $pubtimes = $this->get_publish_time($parsed->updated);
703 $post_modified = $pubtimes[0];
704 $post_modified_gmt = $pubtimes[1];
706 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt');
707 $this->escape($postdata);
709 $result = wp_update_post($postdata);
712 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
715 log_app('function',"put_attachment($postID)");
724 * @param int $postID Post ID.
726 function delete_attachment($postID) {
727 log_app('function',"delete_attachment($postID). File '$location' deleted.");
729 // check for not found
731 $this->set_current_entry($postID);
733 if(!current_user_can('edit_post', $postID)) {
734 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
737 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
738 $filetype = wp_check_filetype($location);
740 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
741 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
747 $result = wp_delete_post($postID);
750 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
753 log_app('function',"delete_attachment($postID). File '$location' deleted.");
758 * Retrieve attachment from post.
762 * @param int $postID Post ID.
764 function get_file($postID) {
766 // check for not found
768 $this->set_current_entry($postID);
770 // then whether user can edit the specific post
771 if(!current_user_can('edit_post', $postID)) {
772 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
775 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
776 $filetype = wp_check_filetype($location);
778 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
779 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
781 status_header('200');
782 header('Content-Type: ' . $entry['post_mime_type']);
783 header('Connection: close');
785 $fp = fopen($location, "rb");
787 echo fread($fp, 4096);
791 log_app('function',"get_file($postID)");
796 * Upload file to blog and add attachment to post.
800 * @param int $postID Post ID.
802 function put_file($postID) {
804 // first check if user can upload
805 if(!current_user_can('upload_files'))
806 $this->auth_required(__('You do not have permission to upload files.'));
808 // check for not found
810 $this->set_current_entry($postID);
812 // then whether user can edit the specific post
813 if(!current_user_can('edit_post', $postID)) {
814 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
817 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
818 $filetype = wp_check_filetype($location);
820 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
821 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
823 $fp = fopen("php://input", "rb");
824 $localfp = fopen($location, "w+");
826 fwrite($localfp,fread($fp, 4096));
832 $pubtimes = $this->get_publish_time($entry->published);
833 $post_date = $pubtimes[0];
834 $post_date_gmt = $pubtimes[1];
835 $pubtimes = $this->get_publish_time($parsed->updated);
836 $post_modified = $pubtimes[0];
837 $post_modified_gmt = $pubtimes[1];
839 $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
840 $result = wp_update_post($post_data);
843 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
846 log_app('function',"put_file($postID)");
851 * Retrieve entries URL.
855 * @param int $page Page ID.
858 function get_entries_url($page = null) {
859 if($GLOBALS['post_type'] == 'attachment') {
860 $path = $this->MEDIA_PATH;
862 $path = $this->ENTRIES_PATH;
864 $url = $this->app_base . $path;
865 if(isset($page) && is_int($page)) {
872 * Display entries URL.
876 * @param int $page Page ID.
878 function the_entries_url($page = null) {
879 echo $this->get_entries_url($page);
883 * Retrieve categories URL.
887 * @param mixed $deprecated Optional, not used.
890 function get_categories_url($deprecated = '') {
891 return $this->app_base . $this->CATEGORIES_PATH;
895 * Display category URL.
899 function the_categories_url() {
900 echo $this->get_categories_url();
904 * Retrieve attachment URL.
908 * @param int $page Page ID.
911 function get_attachments_url($page = null) {
912 $url = $this->app_base . $this->MEDIA_PATH;
913 if(isset($page) && is_int($page)) {
920 * Display attachment URL.
924 * @param int $page Page ID.
926 function the_attachments_url($page = null) {
927 echo $this->get_attachments_url($page);
931 * Retrieve service URL.
937 function get_service_url() {
938 return $this->app_base . $this->SERVICE_PATH;
942 * Retrieve entry URL.
946 * @param int $postID Post ID.
949 function get_entry_url($postID = null) {
950 if(!isset($postID)) {
952 $postID = (int) $post->ID;
955 $url = $this->app_base . $this->ENTRY_PATH . "/$postID";
957 log_app('function',"get_entry_url() = $url");
966 * @param int $postID Post ID.
968 function the_entry_url($postID = null) {
969 echo $this->get_entry_url($postID);
973 * Retrieve media URL.
977 * @param int $postID Post ID.
980 function get_media_url($postID = null) {
981 if(!isset($postID)) {
983 $postID = (int) $post->ID;
986 $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID";
988 log_app('function',"get_media_url() = $url");
993 * Display the media URL.
997 * @param int $postID Post ID.
999 function the_media_url($postID = null) {
1000 echo $this->get_media_url($postID);
1004 * Set the current entry to post ID.
1008 * @param int $postID Post ID.
1010 function set_current_entry($postID) {
1012 log_app('function',"set_current_entry($postID)");
1014 if(!isset($postID)) {
1015 // $this->bad_request();
1019 $entry = wp_get_single_post($postID,ARRAY_A);
1021 if(!isset($entry) || !isset($entry['ID']))
1028 * Display posts XML.
1032 * @param int $page Optional. Page ID.
1033 * @param string $post_type Optional, default is 'post'. Post Type.
1035 function get_posts($page = 1, $post_type = 'post') {
1036 log_app('function',"get_posts($page, '$post_type')");
1037 $feed = $this->get_feed($page, $post_type);
1038 $this->output($feed);
1042 * Display attachment XML.
1046 * @param int $page Page ID.
1047 * @param string $post_type Optional, default is 'attachment'. Post type.
1049 function get_attachments($page = 1, $post_type = 'attachment') {
1050 log_app('function',"get_attachments($page, '$post_type')");
1051 $GLOBALS['post_type'] = $post_type;
1052 $feed = $this->get_feed($page, $post_type);
1053 $this->output($feed);
1057 * Retrieve feed XML.
1061 * @param int $page Page ID.
1062 * @param string $post_type Optional, default is post. Post type.
1065 function get_feed($page = 1, $post_type = 'post') {
1066 global $post, $wp, $wp_query, $posts, $wpdb, $blog_id;
1067 log_app('function',"get_feed($page, '$post_type')");
1073 $page = (int) $page;
1075 $count = get_option('posts_per_rss');
1077 wp('what_to_show=posts&posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified'));
1079 $post = $GLOBALS['post'];
1080 $posts = $GLOBALS['posts'];
1081 $wp = $GLOBALS['wp'];
1082 $wp_query = $GLOBALS['wp_query'];
1083 $wpdb = $GLOBALS['wpdb'];
1084 $blog_id = (int) $GLOBALS['blog_id'];
1085 log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)");
1087 log_app('function',"total_count(# $wp_query->max_num_pages #)");
1088 $last_page = $wp_query->max_num_pages;
1089 $next_page = (($page + 1) > $last_page) ? NULL : $page + 1;
1090 $prev_page = ($page - 1) < 1 ? NULL : $page - 1;
1091 $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page;
1092 $self_page = $page > 1 ? $page : NULL;
1093 ?><feed xmlns="<?php echo $this->ATOM_NS ?>" xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
1094 <id><?php $this->the_entries_url() ?></id>
1095 <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT')); ?></updated>
1096 <title type="text"><?php bloginfo_rss('name') ?></title>
1097 <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle>
1098 <link rel="first" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url() ?>" />
1099 <?php if(isset($prev_page)): ?>
1100 <link rel="previous" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($prev_page) ?>" />
1102 <?php if(isset($next_page)): ?>
1103 <link rel="next" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($next_page) ?>" />
1105 <link rel="last" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($last_page) ?>" />
1106 <link rel="self" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($self_page) ?>" />
1107 <rights type="text">Copyright <?php echo mysql2date('Y', get_lastpostdate('blog')); ?></rights>
1108 <?php the_generator( 'atom' ); ?>
1109 <?php if ( have_posts() ) {
1110 while ( have_posts() ) {
1112 $this->echo_entry();
1117 $feed = ob_get_contents();
1123 * Display entry XML.
1127 * @param int $postID Post ID.
1128 * @param string $post_type Optional, default is post. Post type.
1131 function get_entry($postID, $post_type = 'post') {
1132 log_app('function',"get_entry($postID, '$post_type')");
1134 switch($post_type) {
1139 $varname = 'attachment_id';
1142 query_posts($varname . '=' . $postID);
1143 if ( have_posts() ) {
1144 while ( have_posts() ) {
1146 $this->echo_entry();
1147 log_app('$post',print_r($GLOBALS['post'],true));
1148 $entry = ob_get_contents();
1154 log_app('get_entry returning:',$entry);
1159 * Display post content XML.
1163 function echo_entry() { ?>
1164 <entry xmlns="<?php echo $this->ATOM_NS ?>"
1165 xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
1166 <id><?php the_guid($GLOBALS['post']->ID); ?></id>
1167 <?php list($content_type, $content) = prep_atom_text_construct(get_the_title()); ?>
1168 <title type="<?php echo $content_type ?>"><?php echo $content ?></title>
1169 <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
1170 <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
1171 <app:edited><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></app:edited>
1173 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
1176 <name><?php the_author()?></name>
1177 <?php if (get_the_author_url() && get_the_author_url() != 'http://') { ?>
1178 <uri><?php the_author_url()?></uri>
1181 <?php if($GLOBALS['post']->post_type == 'attachment') { ?>
1182 <link rel="edit-media" href="<?php $this->the_media_url() ?>" />
1183 <content type="<?php echo $GLOBALS['post']->post_mime_type ?>" src="<?php the_guid(); ?>"/>
1185 <link href="<?php the_permalink_rss() ?>" />
1186 <?php if ( strlen( $GLOBALS['post']->post_content ) ) :
1187 list($content_type, $content) = prep_atom_text_construct(get_the_content()); ?>
1188 <content type="<?php echo $content_type ?>"><?php echo $content ?></content>
1191 <link rel="edit" href="<?php $this->the_entry_url() ?>" />
1192 <?php foreach(get_the_category() as $category) { ?>
1193 <category scheme="<?php bloginfo_rss('home') ?>" term="<?php echo $category->name?>" />
1195 <?php list($content_type, $content) = prep_atom_text_construct(get_the_excerpt()); ?>
1196 <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
1201 * Set 'OK' (200) status header.
1206 log_app('Status','200: OK');
1207 header('Content-Type: text/plain');
1208 status_header('200');
1213 * Set 'No Content' (204) status header.
1217 function no_content() {
1218 log_app('Status','204: No Content');
1219 header('Content-Type: text/plain');
1220 status_header('204');
1226 * Display 'Internal Server Error' (500) status header.
1230 * @param string $msg Optional. Status string.
1232 function internal_error($msg = 'Internal Server Error') {
1233 log_app('Status','500: Server Error');
1234 header('Content-Type: text/plain');
1235 status_header('500');
1241 * Set 'Bad Request' (400) status header.
1245 function bad_request() {
1246 log_app('Status','400: Bad Request');
1247 header('Content-Type: text/plain');
1248 status_header('400');
1253 * Set 'Length Required' (411) status header.
1257 function length_required() {
1258 log_app('Status','411: Length Required');
1259 header("HTTP/1.1 411 Length Required");
1260 header('Content-Type: text/plain');
1261 status_header('411');
1266 * Set 'Unsupported Media Type' (415) status header.
1270 function invalid_media() {
1271 log_app('Status','415: Unsupported Media Type');
1272 header("HTTP/1.1 415 Unsupported Media Type");
1273 header('Content-Type: text/plain');
1278 * Set 'Forbidden' (403) status header.
1282 function forbidden($reason='') {
1283 log_app('Status','403: Forbidden');
1284 header('Content-Type: text/plain');
1285 status_header('403');
1291 * Set 'Not Found' (404) status header.
1295 function not_found() {
1296 log_app('Status','404: Not Found');
1297 header('Content-Type: text/plain');
1298 status_header('404');
1303 * Set 'Not Allowed' (405) status header.
1307 function not_allowed($allow) {
1308 log_app('Status','405: Not Allowed');
1309 header('Allow: ' . join(',', $allow));
1310 status_header('405');
1315 * Display Redirect (302) content and set status headers.
1319 function redirect($url) {
1321 log_app('Status','302: Redirect');
1322 $escaped_url = attribute_escape($url);
1324 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1327 <title>302 Found</title>
1331 <p>The document has moved <a href="$escaped_url">here</a>.</p>
1336 header('HTTP/1.1 302 Moved');
1337 header('Content-Type: text/html');
1338 header('Location: ' . $url);
1345 * Set 'Client Error' (400) status header.
1349 function client_error($msg = 'Client Error') {
1350 log_app('Status','400: Client Error');
1351 header('Content-Type: text/plain');
1352 status_header('400');
1357 * Set created status headers (201).
1359 * Sets the 'content-type', 'content-location', and 'location'.
1363 function created($post_ID, $content, $post_type = 'post') {
1364 log_app('created()::$post_ID',"$post_ID, $post_type");
1365 $edit = $this->get_entry_url($post_ID);
1366 switch($post_type) {
1368 $ctloc = $this->get_entry_url($post_ID);
1371 $edit = $this->app_base . "attachments/$post_ID";
1374 header("Content-Type: $this->ATOM_CONTENT_TYPE");
1376 header('Content-Location: ' . $ctloc);
1377 header('Location: ' . $edit);
1378 status_header('201');
1384 * Set 'Auth Required' (401) headers.
1388 * @param string $msg Status header content and HTML content.
1390 function auth_required($msg) {
1391 log_app('Status','401: Auth Required');
1393 header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"');
1394 header("HTTP/1.1 401 $msg");
1395 header('Status: 401 ' . $msg);
1396 header('Content-Type: text/html');
1398 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1401 <title>401 Unauthorized</title>
1404 <h1>401 Unauthorized</h1>
1415 * Display XML and set headers with content type.
1419 * @param string $xml Display feed content.
1420 * @param string $ctype Optional, default is 'atom+xml'. Feed content type.
1422 function output($xml, $ctype = 'application/atom+xml') {
1423 status_header('200');
1424 $xml = '<?xml version="1.0" encoding="' . strtolower(get_option('blog_charset')) . '"?>'."\n".$xml;
1425 header('Connection: close');
1426 header('Content-Length: '. strlen($xml));
1427 header('Content-Type: ' . $ctype);
1428 header('Content-Disposition: attachment; filename=atom.xml');
1429 header('Date: '. date('r'));
1430 if($this->do_output)
1432 log_app('function', "output:\n$xml");
1437 * Sanitize content for database usage.
1441 * @param array $array Sanitize array and multi-dimension array.
1443 function escape(&$array) {
1446 foreach ($array as $k => $v) {
1448 $this->escape($array[$k]);
1449 } else if (is_object($v)) {
1452 $array[$k] = $wpdb->escape($v);
1458 * Access credential through various methods and perform login.
1464 function authenticate() {
1465 log_app("authenticate()",print_r($_ENV, true));
1467 // if using mod_rewrite/ENV hack
1468 // http://www.besthostratings.com/articles/http-auth-php-cgi.html
1469 if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
1470 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1471 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
1472 } else if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
1473 // Workaround for setups that do not forward HTTP_AUTHORIZATION
1474 // See http://trac.wordpress.org/ticket/7361
1475 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1476 explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
1479 // If Basic Auth is working...
1480 if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
1481 log_app("Basic Auth",$_SERVER['PHP_AUTH_USER']);
1482 $user = wp_authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1483 if ( $user && !is_wp_error($user) ) {
1484 wp_set_current_user($user->ID);
1485 log_app("authenticate()", $_SERVER['PHP_AUTH_USER']);
1494 * Retrieve accepted content types.
1498 * @param array $types Optional. Content Types.
1501 function get_accepted_content_type($types = null) {
1503 if(!isset($types)) {
1504 $types = $this->media_content_types;
1507 if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1508 $this->length_required();
1511 $type = $_SERVER['CONTENT_TYPE'];
1512 list($type,$subtype) = explode('/',$type);
1513 list($subtype) = explode(";",$subtype); // strip MIME parameters
1514 log_app("get_accepted_content_type", "type=$type, subtype=$subtype");
1516 foreach($types as $t) {
1517 list($acceptedType,$acceptedSubtype) = explode('/',$t);
1518 if($acceptedType == '*' || $acceptedType == $type) {
1519 if($acceptedSubtype == '*' || $acceptedSubtype == $subtype)
1520 return $type . "/" . $subtype;
1524 $this->invalid_media();
1528 * Process conditionals for posts.
1532 function process_conditionals() {
1534 if(empty($this->params)) return;
1535 if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1537 switch($this->params[0]) {
1538 case $this->ENTRY_PATH:
1540 $post = wp_get_single_post($this->params[1]);
1541 $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true);
1544 case $this->ENTRIES_PATH:
1545 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1550 $wp_etag = md5($wp_last_modified);
1551 @header("Last-Modified: $wp_last_modified");
1552 @header("ETag: $wp_etag");
1554 // Support for Conditional GET
1555 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1556 $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1558 $client_etag = false;
1560 $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1561 // If string is empty, return 0. If not, attempt to parse into a timestamp
1562 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
1564 // Make a timestamp for our most recent modification...
1565 $wp_modified_timestamp = strtotime($wp_last_modified);
1567 if ( ($client_last_modified && $client_etag) ?
1568 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
1569 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
1570 status_header( 304 );
1576 * Convert RFC3339 time string to timestamp.
1580 * @param string $str String to time.
1581 * @return bool|int false if format is incorrect.
1583 function rfc3339_str2time($str) {
1586 if(!preg_match("/(\d{4}-\d{2}-\d{2})T(\d{2}\:\d{2}\:\d{2})\.?\d{0,3}(Z|[+-]+\d{2}\:\d{2})/", $str, $match))
1589 if($match[3] == 'Z')
1590 $match[3] == '+0000';
1592 return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1596 * Retrieve published time to display in XML.
1600 * @param string $published Time string.
1603 function get_publish_time($published) {
1605 $pubtime = $this->rfc3339_str2time($published);
1608 return array(current_time('mysql'),current_time('mysql',1));
1610 return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1619 * @global object $server
1621 $server = new AtomServer();
1622 $server->handle_request();