3 * Atom Publishing Protocol support for WordPress
9 * WordPress is handling an Atom Publishing Protocol request.
13 define('APP_REQUEST', true);
15 /** Set up WordPress environment */
16 require_once('./wp-load.php');
18 /** Atom Publishing Protocol Class */
19 require_once(ABSPATH . WPINC . '/atomlib.php');
21 /** Admin Image API for metadata updating */
22 require_once(ABSPATH . '/wp-admin/includes/image.php');
24 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
27 * Whether to enable Atom Publishing Protocol Logging.
35 * Whether to always authenticate user. Permanently set to true.
37 * @name always_authenticate
39 * @todo Should be an option somewhere
41 $always_authenticate = 1;
44 * Writes logging info to a file.
51 * @param string $label Type of logging
52 * @param string $msg Information describing logging reason.
54 function log_app($label,$msg) {
57 $fp = fopen( 'wp-app.log', 'a+');
58 $date = gmdate( 'Y-m-d H:i:s' );
59 fwrite($fp, "\n\n$date - $label\n$msg\n");
65 * Filter to add more post statuses.
69 * @param string $where SQL statement to filter.
70 * @return string Filtered SQL statement with added post_status for where clause.
72 function wa_posts_where_include_drafts_filter($where) {
73 $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where);
77 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
80 * WordPress AtomPub API implementation.
83 * @subpackage Publishing
94 var $ATOM_CONTENT_TYPE = 'application/atom+xml';
97 * Categories ATOM content type.
102 var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
105 * Service ATOM content type.
110 var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
113 * ATOM XML namespace.
118 var $ATOM_NS = 'http://www.w3.org/2005/Atom';
121 * ATOMPUB XML namespace.
126 var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
134 var $ENTRIES_PATH = "posts";
142 var $CATEGORIES_PATH = "categories";
150 var $MEDIA_PATH = "attachments";
158 var $ENTRY_PATH = "post";
166 var $SERVICE_PATH = "service";
174 var $MEDIA_SINGLE_PATH = "attachment";
177 * ATOMPUB parameters.
182 var $params = array();
185 * Supported ATOMPUB media types.
190 var $media_content_types = array('image/*','audio/*','video/*');
193 * ATOMPUB content type(s).
198 var $atom_content_types = array('application/atom+xml');
206 var $selectors = array();
209 * Whether to do output.
216 var $do_output = true;
219 * Constructor - Sets up object properties.
224 function __construct() {
226 $var_by_ref = explode( '/', $_SERVER['SCRIPT_NAME'] );
227 $this->script_name = array_pop( $var_by_ref );
228 $this->app_base = site_url( $this->script_name . '/' );
230 $this->selectors = array(
232 array('GET' => 'get_service'),
234 array('GET' => 'get_categories_xml'),
236 array('GET' => 'get_post',
238 'DELETE' => 'delete_post'),
239 '@/posts/?(\d+)?$@' =>
240 array('GET' => 'get_posts',
241 'POST' => 'create_post'),
242 '@/attachments/?(\d+)?$@' =>
243 array('GET' => 'get_attachment',
244 'POST' => 'create_attachment'),
245 '@/attachment/file/(\d+)$@' =>
246 array('GET' => 'get_file',
248 'DELETE' => 'delete_file'),
249 '@/attachment/(\d+)$@' =>
250 array('GET' => 'get_attachment',
251 'PUT' => 'put_attachment',
252 'DELETE' => 'delete_attachment'),
257 * Handle ATOMPUB request.
261 function handle_request() {
262 global $always_authenticate;
264 if ( !empty( $_SERVER['ORIG_PATH_INFO'] ) )
265 $path = $_SERVER['ORIG_PATH_INFO'];
267 $path = $_SERVER['PATH_INFO'];
269 $method = $_SERVER['REQUEST_METHOD'];
271 log_app('REQUEST',"$method $path\n================");
273 $this->process_conditionals();
274 //$this->process_conditionals();
276 // exception case for HEAD (treat exactly as GET, but don't output)
277 if ($method == 'HEAD') {
278 $this->do_output = false;
282 // redirect to /service in case no path is found.
283 if (strlen($path) == 0 || $path == '/')
284 $this->redirect($this->get_service_url());
286 // check to see if AtomPub is enabled
287 if ( !get_option( 'enable_app' ) )
288 $this->forbidden( sprintf( __( 'AtomPub services are disabled on this site. An admin user can enable them at %s' ), admin_url('options-writing.php') ) );
291 foreach ( $this->selectors as $regex => $funcs ) {
292 if ( preg_match($regex, $path, $matches) ) {
293 if ( isset($funcs[$method]) ) {
295 // authenticate regardless of the operation and set the current
296 // user. each handler will decide if auth is required or not.
297 if ( !$this->authenticate() ) {
298 if ( $always_authenticate )
299 $this->auth_required('Credentials required.');
302 array_shift($matches);
303 call_user_func_array(array(&$this,$funcs[$method]), $matches);
306 // only allow what we have handlers for...
307 $this->not_allowed(array_keys($funcs));
312 // oops, nothing found
317 * Retrieve XML for ATOMPUB service.
321 function get_service() {
322 log_app('function','get_service()');
324 if ( !current_user_can( 'edit_posts' ) )
325 $this->auth_required( __( 'Sorry, you do not have the right to access this site.' ) );
327 $entries_url = esc_attr($this->get_entries_url());
328 $categories_url = esc_attr($this->get_categories_url());
329 $media_url = esc_attr($this->get_attachments_url());
330 $accepted_media_types = '';
331 foreach ($this->media_content_types as $med) {
332 $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
335 $atom_blogname = get_bloginfo('name');
336 $service_doc = <<<EOD
337 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
339 <$atom_prefix:title>$atom_blogname Workspace</$atom_prefix:title>
340 <collection href="$entries_url">
341 <$atom_prefix:title>$atom_blogname Posts</$atom_prefix:title>
342 <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
343 <categories href="$categories_url" />
345 <collection href="$media_url">
346 <$atom_prefix:title>$atom_blogname Media</$atom_prefix:title>
347 $accepted_media_types
354 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
358 * Retrieve categories list in XML format.
362 function get_categories_xml() {
363 log_app('function','get_categories_xml()');
365 if ( !current_user_can( 'edit_posts' ) )
366 $this->auth_required( __( 'Sorry, you do not have the right to access this site.' ) );
368 $home = esc_attr(get_bloginfo_rss('url'));
371 $cats = get_categories(array('hierarchical' => 0, 'hide_empty' => 0));
372 foreach ( (array) $cats as $cat ) {
373 $categories .= " <category term=\"" . esc_attr($cat->name) . "\" />\n";
376 <app:categories xmlns:app="$this->ATOMPUB_NS"
377 xmlns="$this->ATOM_NS"
378 fixed="yes" scheme="$home">
382 $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
390 function create_post() {
392 $this->get_accepted_content_type($this->atom_content_types);
394 $parser = new AtomParser();
395 if ( !$parser->parse() )
396 $this->client_error();
398 $entry = array_pop($parser->feed->entries);
400 log_app('Received entry:', print_r($entry,true));
403 foreach ( $entry->categories as $cat ) {
404 array_push($catnames, $cat["term"]);
407 $wp_cats = get_categories(array('hide_empty' => false));
409 $post_category = array();
411 foreach ( $wp_cats as $cat ) {
412 if ( in_array($cat->name, $catnames) )
413 array_push($post_category, $cat->term_id);
416 $publish = ! ( isset( $entry->draft ) && 'yes' == trim( $entry->draft ) );
418 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
420 if ( !current_user_can($cap) )
421 $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
423 $blog_ID = get_current_blog_id();
424 $post_status = ($publish) ? 'publish' : 'draft';
425 $post_author = (int) $user_ID;
426 $post_title = $entry->title[1];
427 $post_content = $entry->content[1];
428 $post_excerpt = $entry->summary[1];
429 $pubtimes = $this->get_publish_time($entry->published);
430 $post_date = $pubtimes[0];
431 $post_date_gmt = $pubtimes[1];
433 if ( isset( $_SERVER['HTTP_SLUG'] ) )
434 $post_name = $_SERVER['HTTP_SLUG'];
436 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
438 $this->escape($post_data);
439 log_app('Inserting Post. Data:', print_r($post_data,true));
441 $postID = wp_insert_post($post_data);
442 if ( is_wp_error( $postID ) )
443 $this->internal_error($postID->get_error_message());
446 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
448 // getting warning here about unable to set headers
449 // because something in the cache is printing to the buffer
450 // could we clean up wp_set_post_categories or cache to not print
451 // this could affect our ability to send back the right headers
452 @wp_set_post_categories($postID, $post_category);
454 do_action( 'atompub_create_post', $postID, $entry );
456 $output = $this->get_entry($postID);
458 log_app('function',"create_post($postID)");
459 $this->created($postID, $output);
467 * @param int $postID Post ID.
469 function get_post($postID) {
472 if ( !current_user_can( 'edit_post', $postID ) )
473 $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
475 $this->set_current_entry($postID);
476 $output = $this->get_entry($postID);
477 log_app('function',"get_post($postID)");
478 $this->output($output);
487 * @param int $postID Post ID.
489 function put_post($postID) {
490 // checked for valid content-types (atom+xml)
491 // quick check and exit
492 $this->get_accepted_content_type($this->atom_content_types);
494 $parser = new AtomParser();
495 if ( !$parser->parse() )
496 $this->bad_request();
498 $parsed = array_pop($parser->feed->entries);
500 log_app('Received UPDATED entry:', print_r($parsed,true));
502 // check for not found
504 $this->set_current_entry($postID);
506 if ( !current_user_can('edit_post', $entry['ID']) )
507 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
509 $publish = ! ( isset($parsed->draft) && 'yes' == trim($parsed->draft) );
510 $post_status = ($publish) ? 'publish' : 'draft';
514 $post_title = $parsed->title[1];
515 $post_content = $parsed->content[1];
516 $post_excerpt = $parsed->summary[1];
517 $pubtimes = $this->get_publish_time($entry->published);
518 $post_date = $pubtimes[0];
519 $post_date_gmt = $pubtimes[1];
520 $pubtimes = $this->get_publish_time($parsed->updated);
521 $post_modified = $pubtimes[0];
522 $post_modified_gmt = $pubtimes[1];
524 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
525 $this->escape($postdata);
527 $result = wp_update_post($postdata);
530 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
532 do_action( 'atompub_put_post', $ID, $parsed );
534 log_app('function',"put_post($postID)");
543 * @param int $postID Post ID.
545 function delete_post($postID) {
547 // check for not found
549 $this->set_current_entry($postID);
551 if ( !current_user_can('edit_post', $postID) )
552 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
554 if ( $entry['post_type'] == 'attachment' ) {
555 $this->delete_attachment($postID);
557 $result = wp_delete_post($postID);
560 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
563 log_app('function',"delete_post($postID)");
570 * Retrieve attachment.
574 * @param int $postID Optional. Post ID.
576 function get_attachment($postID = null) {
577 if ( !current_user_can( 'upload_files' ) )
578 $this->auth_required( __( 'Sorry, you do not have permission to upload files.' ) );
580 if ( !isset($postID) ) {
581 $this->get_attachments();
583 $this->set_current_entry($postID);
584 $output = $this->get_entry($postID, 'attachment');
585 log_app('function',"get_attachment($postID)");
586 $this->output($output);
591 * Create new attachment.
595 function create_attachment() {
597 $type = $this->get_accepted_content_type();
599 if ( !current_user_can('upload_files') )
600 $this->auth_required(__('You do not have permission to upload files.'));
602 $fp = fopen("php://input", "rb");
604 while ( !feof($fp) ) {
605 $bits .= fread($fp, 4096);
610 if ( isset( $_SERVER['HTTP_SLUG'] ) )
611 $slug = $_SERVER['HTTP_SLUG'];
612 elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
613 $slug = $_SERVER['HTTP_TITLE'];
614 elseif ( empty( $slug ) ) // just make a random name
615 $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
616 $ext = preg_replace( '|.*/([a-z0-9]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
617 $slug = sanitize_file_name( "$slug.$ext" );
618 $file = wp_upload_bits( $slug, NULL, $bits);
620 log_app('wp_upload_bits returns:',print_r($file,true));
623 $file = $file['file'];
625 do_action('wp_create_file_in_uploads', $file); // replicate
627 // Construct the attachment array
629 'post_title' => $slug,
630 'post_content' => $slug,
631 'post_status' => 'attachment',
633 'post_mime_type' => $type,
638 $postID = wp_insert_attachment($attachment, $file);
641 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
643 $output = $this->get_entry($postID, 'attachment');
645 $this->created($postID, $output, 'attachment');
646 log_app('function',"create_attachment($postID)");
654 * @param int $postID Post ID.
656 function put_attachment($postID) {
657 // checked for valid content-types (atom+xml)
658 // quick check and exit
659 $this->get_accepted_content_type($this->atom_content_types);
661 $parser = new AtomParser();
662 if (!$parser->parse()) {
663 $this->bad_request();
666 $parsed = array_pop($parser->feed->entries);
668 // check for not found
670 $this->set_current_entry($postID);
672 if ( !current_user_can('edit_post', $entry['ID']) )
673 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
677 $post_title = $parsed->title[1];
678 $post_content = $parsed->summary[1];
679 $pubtimes = $this->get_publish_time($parsed->updated);
680 $post_modified = $pubtimes[0];
681 $post_modified_gmt = $pubtimes[1];
683 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt');
684 $this->escape($postdata);
686 $result = wp_update_post($postdata);
689 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
691 log_app('function',"put_attachment($postID)");
700 * @param int $postID Post ID.
702 function delete_attachment($postID) {
703 log_app('function',"delete_attachment($postID). File '$location' deleted.");
705 // check for not found
707 $this->set_current_entry($postID);
709 if ( !current_user_can('edit_post', $postID) )
710 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
712 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
713 $filetype = wp_check_filetype($location);
715 if ( !isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']) )
716 $this->internal_error(__('Error occurred while accessing post metadata for file location.'));
722 $result = wp_delete_post($postID);
725 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
727 log_app('function',"delete_attachment($postID). File '$location' deleted.");
732 * Retrieve attachment from post.
736 * @param int $postID Post ID.
738 function get_file($postID) {
740 // check for not found
742 $this->set_current_entry($postID);
744 // then whether user can edit the specific post
745 if ( !current_user_can('edit_post', $postID) )
746 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
748 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
749 $location = get_option ('upload_path') . '/' . $location;
750 $filetype = wp_check_filetype($location);
752 if ( !isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']) )
753 $this->internal_error(__('Error occurred while accessing post metadata for file location.'));
755 status_header('200');
756 header('Content-Type: ' . $entry['post_mime_type']);
757 header('Connection: close');
759 if ( $fp = fopen($location, "rb") ) {
760 status_header('200');
761 header('Content-Type: ' . $entry['post_mime_type']);
762 header('Connection: close');
764 while ( !feof($fp) ) {
765 echo fread($fp, 4096);
770 status_header ('404');
773 log_app('function',"get_file($postID)");
778 * Upload file to blog and add attachment to post.
782 * @param int $postID Post ID.
784 function put_file($postID) {
786 // first check if user can upload
787 if ( !current_user_can('upload_files') )
788 $this->auth_required(__('You do not have permission to upload files.'));
790 // check for not found
792 $this->set_current_entry($postID);
794 // then whether user can edit the specific post
795 if ( !current_user_can('edit_post', $postID) )
796 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
798 $upload_dir = wp_upload_dir( );
799 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
800 $filetype = wp_check_filetype($location);
802 $location = "{$upload_dir['basedir']}/{$location}";
804 if (!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
805 $this->internal_error(__('Error occurred while accessing post metadata for file location.'));
807 $fp = fopen("php://input", "rb");
808 $localfp = fopen($location, "w+");
809 while ( !feof($fp) ) {
810 fwrite($localfp,fread($fp, 4096));
816 $pubtimes = $this->get_publish_time($entry->published);
817 $post_date = $pubtimes[0];
818 $post_date_gmt = $pubtimes[1];
819 $pubtimes = $this->get_publish_time($parsed->updated);
820 $post_modified = $pubtimes[0];
821 $post_modified_gmt = $pubtimes[1];
823 $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
824 $result = wp_update_post($post_data);
827 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
829 wp_update_attachment_metadata( $postID, wp_generate_attachment_metadata( $postID, $location ) );
831 log_app('function',"put_file($postID)");
836 * Retrieve entries URL.
840 * @param int $page Page ID.
843 function get_entries_url($page = null) {
844 if ( isset($GLOBALS['post_type']) && ( $GLOBALS['post_type'] == 'attachment' ) )
845 $path = $this->MEDIA_PATH;
847 $path = $this->ENTRIES_PATH;
848 $url = $this->app_base . $path;
849 if ( isset($page) && is_int($page) )
855 * Display entries URL.
859 * @param int $page Page ID.
861 function the_entries_url($page = null) {
862 echo $this->get_entries_url($page);
866 * Retrieve categories URL.
870 * @param mixed $deprecated Not used.
873 function get_categories_url($deprecated = '') {
874 if ( !empty( $deprecated ) )
875 _deprecated_argument( __FUNCTION__, '2.5' );
876 return $this->app_base . $this->CATEGORIES_PATH;
880 * Display category URL.
884 function the_categories_url() {
885 echo $this->get_categories_url();
889 * Retrieve attachment URL.
893 * @param int $page Page ID.
896 function get_attachments_url($page = null) {
897 $url = $this->app_base . $this->MEDIA_PATH;
898 if (isset($page) && is_int($page)) {
905 * Display attachment URL.
909 * @param int $page Page ID.
911 function the_attachments_url($page = null) {
912 echo $this->get_attachments_url($page);
916 * Retrieve service URL.
922 function get_service_url() {
923 return $this->app_base . $this->SERVICE_PATH;
927 * Retrieve entry URL.
931 * @param int $postID Post ID.
934 function get_entry_url($postID = null) {
935 if (!isset($postID)) {
937 $postID = (int) $post->ID;
940 $url = $this->app_base . $this->ENTRY_PATH . "/$postID";
942 log_app('function',"get_entry_url() = $url");
951 * @param int $postID Post ID.
953 function the_entry_url($postID = null) {
954 echo $this->get_entry_url($postID);
958 * Retrieve media URL.
962 * @param int $postID Post ID.
965 function get_media_url($postID = null) {
966 if (!isset($postID)) {
968 $postID = (int) $post->ID;
971 $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID";
973 log_app('function',"get_media_url() = $url");
978 * Display the media URL.
982 * @param int $postID Post ID.
984 function the_media_url($postID = null) {
985 echo $this->get_media_url($postID);
989 * Set the current entry to post ID.
993 * @param int $postID Post ID.
995 function set_current_entry($postID) {
997 log_app('function',"set_current_entry($postID)");
999 if (!isset($postID)) {
1000 // $this->bad_request();
1004 $entry = wp_get_single_post($postID,ARRAY_A);
1006 if (!isset($entry) || !isset($entry['ID']))
1013 * Display posts XML.
1017 * @param int $page Optional. Page ID.
1018 * @param string $post_type Optional, default is 'post'. Post Type.
1020 function get_posts($page = 1, $post_type = 'post') {
1021 log_app('function',"get_posts($page, '$post_type')");
1022 $feed = $this->get_feed($page, $post_type);
1023 $this->output($feed);
1027 * Display attachment XML.
1031 * @param int $page Page ID.
1032 * @param string $post_type Optional, default is 'attachment'. Post type.
1034 function get_attachments($page = 1, $post_type = 'attachment') {
1035 log_app('function',"get_attachments($page, '$post_type')");
1036 $GLOBALS['post_type'] = $post_type;
1037 $feed = $this->get_feed($page, $post_type);
1038 $this->output($feed);
1042 * Retrieve feed XML.
1046 * @param int $page Page ID.
1047 * @param string $post_type Optional, default is post. Post type.
1050 function get_feed($page = 1, $post_type = 'post') {
1051 global $post, $wp, $wp_query, $posts, $wpdb, $blog_id;
1052 log_app('function',"get_feed($page, '$post_type')");
1055 $this->ENTRY_PATH = $post_type;
1057 if (!isset($page)) {
1060 $page = (int) $page;
1062 $count = get_option('posts_per_rss');
1064 wp('posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified'));
1066 $post = $GLOBALS['post'];
1067 $posts = $GLOBALS['posts'];
1068 $wp = $GLOBALS['wp'];
1069 $wp_query = $GLOBALS['wp_query'];
1070 $wpdb = $GLOBALS['wpdb'];
1071 $blog_id = (int) $GLOBALS['blog_id'];
1072 log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)");
1074 log_app('function',"total_count(# $wp_query->max_num_pages #)");
1075 $last_page = $wp_query->max_num_pages;
1076 $next_page = (($page + 1) > $last_page) ? NULL : $page + 1;
1077 $prev_page = ($page - 1) < 1 ? NULL : $page - 1;
1078 $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page;
1079 $self_page = $page > 1 ? $page : NULL;
1080 ?><feed xmlns="<?php echo $this->ATOM_NS ?>" xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>" <?php do_action('app_ns'); ?> >
1081 <id><?php $this->the_entries_url() ?></id>
1082 <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT'), false); ?></updated>
1083 <title type="text"><?php bloginfo_rss('name') ?></title>
1084 <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle>
1085 <link rel="first" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url() ?>" />
1086 <?php if (isset($prev_page)): ?>
1087 <link rel="previous" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($prev_page) ?>" />
1089 <?php if (isset($next_page)): ?>
1090 <link rel="next" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($next_page) ?>" />
1092 <link rel="last" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($last_page) ?>" />
1093 <link rel="self" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($self_page) ?>" />
1094 <rights type="text">Copyright <?php echo date('Y'); ?></rights>
1095 <?php do_action('app_head'); ?>
1096 <?php if ( have_posts() ) {
1097 while ( have_posts() ) {
1099 $this->echo_entry();
1104 $feed = ob_get_contents();
1110 * Display entry XML.
1114 * @param int $postID Post ID.
1115 * @param string $post_type Optional, default is post. Post type.
1118 function get_entry($postID, $post_type = 'post') {
1119 log_app('function',"get_entry($postID, '$post_type')");
1121 switch($post_type) {
1126 $this->ENTRY_PATH = 'attachment';
1127 $varname = 'attachment_id';
1130 query_posts($varname . '=' . $postID);
1131 if ( have_posts() ) {
1132 while ( have_posts() ) {
1134 $this->echo_entry();
1135 log_app('$post',print_r($GLOBALS['post'],true));
1136 $entry = ob_get_contents();
1142 log_app('get_entry returning:',$entry);
1147 * Display post content XML.
1151 function echo_entry() { ?>
1152 <entry xmlns="<?php echo $this->ATOM_NS ?>"
1153 xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
1154 <id><?php the_guid( $GLOBALS['post']->ID ); ?></id>
1155 <?php list($content_type, $content) = prep_atom_text_construct(get_the_title()); ?>
1156 <title type="<?php echo $content_type ?>"><?php echo $content ?></title>
1157 <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
1158 <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
1159 <app:edited><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></app:edited>
1161 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
1164 <name><?php the_author()?></name>
1165 <?php if ( get_the_author_meta('url') && get_the_author_meta('url') != 'http://' ) { ?>
1166 <uri><?php the_author_meta('url') ?></uri>
1169 <?php if ($GLOBALS['post']->post_type == 'attachment') { ?>
1170 <link rel="edit-media" href="<?php $this->the_media_url() ?>" />
1171 <content type="<?php echo $GLOBALS['post']->post_mime_type ?>" src="<?php the_guid() ; ?>"/>
1173 <link href="<?php the_permalink_rss() ?>" />
1174 <?php if ( strlen( $GLOBALS['post']->post_content ) ) :
1175 list($content_type, $content) = prep_atom_text_construct(get_the_content()); ?>
1176 <content type="<?php echo $content_type ?>"><?php echo $content ?></content>
1179 <link rel="edit" href="<?php $this->the_entry_url() ?>" />
1180 <?php the_category_rss( 'atom' ); ?>
1181 <?php list($content_type, $content) = prep_atom_text_construct(get_the_excerpt()); ?>
1182 <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
1183 <?php do_action('app_entry'); ?>
1188 * Set 'OK' (200) status header.
1193 log_app('Status','200: OK');
1194 header('Content-Type: text/plain');
1195 status_header('200');
1200 * Set 'No Content' (204) status header.
1204 function no_content() {
1205 log_app('Status','204: No Content');
1206 header('Content-Type: text/plain');
1207 status_header('204');
1208 echo "Moved to Trash.";
1213 * Display 'Internal Server Error' (500) status header.
1217 * @param string $msg Optional. Status string.
1219 function internal_error($msg = 'Internal Server Error') {
1220 log_app('Status','500: Server Error');
1221 header('Content-Type: text/plain');
1222 status_header('500');
1228 * Set 'Bad Request' (400) status header.
1232 function bad_request() {
1233 log_app('Status','400: Bad Request');
1234 header('Content-Type: text/plain');
1235 status_header('400');
1240 * Set 'Length Required' (411) status header.
1244 function length_required() {
1245 log_app('Status','411: Length Required');
1246 header("HTTP/1.1 411 Length Required");
1247 header('Content-Type: text/plain');
1248 status_header('411');
1253 * Set 'Unsupported Media Type' (415) status header.
1257 function invalid_media() {
1258 log_app('Status','415: Unsupported Media Type');
1259 header("HTTP/1.1 415 Unsupported Media Type");
1260 header('Content-Type: text/plain');
1265 * Set 'Forbidden' (403) status header.
1269 function forbidden($reason='') {
1270 log_app('Status','403: Forbidden');
1271 header('Content-Type: text/plain');
1272 status_header('403');
1278 * Set 'Not Found' (404) status header.
1282 function not_found() {
1283 log_app('Status','404: Not Found');
1284 header('Content-Type: text/plain');
1285 status_header('404');
1290 * Set 'Not Allowed' (405) status header.
1294 function not_allowed($allow) {
1295 log_app('Status','405: Not Allowed');
1296 header('Allow: ' . join(',', $allow));
1297 status_header('405');
1302 * Display Redirect (302) content and set status headers.
1306 function redirect($url) {
1308 log_app('Status','302: Redirect');
1309 $escaped_url = esc_attr($url);
1311 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1314 <title>302 Found</title>
1318 <p>The document has moved <a href="$escaped_url">here</a>.</p>
1323 header('HTTP/1.1 302 Moved');
1324 header('Content-Type: text/html');
1325 header('Location: ' . $url);
1332 * Set 'Client Error' (400) status header.
1336 function client_error($msg = 'Client Error') {
1337 log_app('Status','400: Client Error');
1338 header('Content-Type: text/plain');
1339 status_header('400');
1344 * Set created status headers (201).
1346 * Sets the 'content-type', 'content-location', and 'location'.
1350 function created($post_ID, $content, $post_type = 'post') {
1351 log_app('created()::$post_ID',"$post_ID, $post_type");
1352 $edit = $this->get_entry_url($post_ID);
1353 switch($post_type) {
1355 $ctloc = $this->get_entry_url($post_ID);
1358 $edit = $this->app_base . "attachments/$post_ID";
1361 header("Content-Type: $this->ATOM_CONTENT_TYPE");
1363 header('Content-Location: ' . $ctloc);
1364 header('Location: ' . $edit);
1365 status_header('201');
1371 * Set 'Auth Required' (401) headers.
1375 * @param string $msg Status header content and HTML content.
1377 function auth_required($msg) {
1378 log_app('Status','401: Auth Required');
1380 header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"');
1381 header("HTTP/1.1 401 $msg");
1382 header('Status: 401 ' . $msg);
1383 header('Content-Type: text/html');
1385 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1388 <title>401 Unauthorized</title>
1391 <h1>401 Unauthorized</h1>
1402 * Display XML and set headers with content type.
1406 * @param string $xml Display feed content.
1407 * @param string $ctype Optional, default is 'atom+xml'. Feed content type.
1409 function output($xml, $ctype = 'application/atom+xml') {
1410 status_header('200');
1411 $xml = '<?xml version="1.0" encoding="' . strtolower(get_option('blog_charset')) . '"?>'."\n".$xml;
1412 header('Connection: close');
1413 header('Content-Length: '. strlen($xml));
1414 header('Content-Type: ' . $ctype);
1415 header('Content-Disposition: attachment; filename=atom.xml');
1416 header('Date: '. date('r'));
1417 if ($this->do_output)
1419 log_app('function', "output:\n$xml");
1424 * Sanitize content for database usage.
1428 * @param array $array Sanitize array and multi-dimension array.
1430 function escape(&$array) {
1433 foreach ($array as $k => $v) {
1435 $this->escape($array[$k]);
1436 } else if (is_object($v)) {
1439 $array[$k] = $wpdb->escape($v);
1445 * Access credential through various methods and perform login.
1451 function authenticate() {
1452 log_app("authenticate()",print_r($_ENV, true));
1454 // if using mod_rewrite/ENV hack
1455 // http://www.besthostratings.com/articles/http-auth-php-cgi.html
1456 if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
1457 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1458 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
1459 } else if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
1460 // Workaround for setups that do not forward HTTP_AUTHORIZATION
1461 // See http://trac.wordpress.org/ticket/7361
1462 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1463 explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
1466 // If Basic Auth is working...
1467 if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
1468 log_app("Basic Auth",$_SERVER['PHP_AUTH_USER']);
1470 $user = wp_authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1471 if ( $user && !is_wp_error($user) ) {
1472 wp_set_current_user($user->ID);
1473 log_app("authenticate()", $user->user_login);
1482 * Retrieve accepted content types.
1486 * @param array $types Optional. Content Types.
1489 function get_accepted_content_type($types = null) {
1491 if (!isset($types)) {
1492 $types = $this->media_content_types;
1495 if (!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1496 $this->length_required();
1499 $type = $_SERVER['CONTENT_TYPE'];
1500 list($type,$subtype) = explode('/',$type);
1501 list($subtype) = explode(";",$subtype); // strip MIME parameters
1502 log_app("get_accepted_content_type", "type=$type, subtype=$subtype");
1504 foreach($types as $t) {
1505 list($acceptedType,$acceptedSubtype) = explode('/',$t);
1506 if ($acceptedType == '*' || $acceptedType == $type) {
1507 if ($acceptedSubtype == '*' || $acceptedSubtype == $subtype)
1508 return $type . "/" . $subtype;
1512 $this->invalid_media();
1516 * Process conditionals for posts.
1520 function process_conditionals() {
1522 if (empty($this->params)) return;
1523 if ($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1525 switch($this->params[0]) {
1526 case $this->ENTRY_PATH:
1528 $post = wp_get_single_post($this->params[1]);
1529 $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true);
1532 case $this->ENTRIES_PATH:
1533 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1538 $wp_etag = md5($wp_last_modified);
1539 @header("Last-Modified: $wp_last_modified");
1540 @header("ETag: $wp_etag");
1542 // Support for Conditional GET
1543 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1544 $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1546 $client_etag = false;
1548 $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1549 // If string is empty, return 0. If not, attempt to parse into a timestamp
1550 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
1552 // Make a timestamp for our most recent modification...
1553 $wp_modified_timestamp = strtotime($wp_last_modified);
1555 if ( ($client_last_modified && $client_etag) ?
1556 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
1557 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
1558 status_header( 304 );
1564 * Convert RFC3339 time string to timestamp.
1568 * @param string $str String to time.
1569 * @return bool|int false if format is incorrect.
1571 function rfc3339_str2time($str) {
1574 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))
1577 if ($match[3] == 'Z')
1578 $match[3] = '+0000';
1580 return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1584 * Retrieve published time to display in XML.
1588 * @param string $published Time string.
1591 function get_publish_time($published) {
1593 $pubtime = $this->rfc3339_str2time($published);
1596 return array(current_time('mysql'),current_time('mysql',1));
1598 return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1607 * @global object $server
1609 $server = new AtomServer();
1610 $server->handle_request();