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 /** Admin Image API for metadata updating */
30 require_once(ABSPATH . '/wp-admin/includes/image.php');
32 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
35 * Whether to enable Atom Publishing Protocol Logging.
43 * Whether to always authenticate user. Permanently set to true.
45 * @name always_authenticate
47 * @todo Should be an option somewhere
49 $always_authenticate = 1;
52 * Writes logging info to a file.
59 * @param string $label Type of logging
60 * @param string $msg Information describing logging reason.
62 function log_app($label,$msg) {
65 $fp = fopen( 'wp-app.log', 'a+');
66 $date = gmdate( 'Y-m-d H:i:s' );
67 fwrite($fp, "\n\n$date - $label\n$msg\n");
72 if ( !function_exists('wp_set_current_user') ) :
76 function wp_set_current_user($id, $name = '') {
79 if ( isset($current_user) && ($id == $current_user->ID) )
82 $current_user = new WP_User($id, $name);
89 * Filter to add more post statuses.
93 * @param string $where SQL statement to filter.
94 * @return string Filtered SQL statement with added post_status for where clause.
96 function wa_posts_where_include_drafts_filter($where) {
97 $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where);
101 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
104 * WordPress AtomPub API implementation.
107 * @subpackage Publishing
118 var $ATOM_CONTENT_TYPE = 'application/atom+xml';
121 * Categories ATOM content type.
126 var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
129 * Service ATOM content type.
134 var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
137 * ATOM XML namespace.
142 var $ATOM_NS = 'http://www.w3.org/2005/Atom';
145 * ATOMPUB XML namespace.
150 var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
158 var $ENTRIES_PATH = "posts";
166 var $CATEGORIES_PATH = "categories";
174 var $MEDIA_PATH = "attachments";
182 var $ENTRY_PATH = "post";
190 var $SERVICE_PATH = "service";
198 var $MEDIA_SINGLE_PATH = "attachment";
201 * ATOMPUB parameters.
206 var $params = array();
209 * Supported ATOMPUB media types.
214 var $media_content_types = array('image/*','audio/*','video/*');
217 * ATOMPUB content type(s).
222 var $atom_content_types = array('application/atom+xml');
230 var $selectors = array();
233 * Whether to do output.
240 var $do_output = true;
243 * PHP4 constructor - Sets up object properties.
248 function AtomServer() {
250 $this->script_name = array_pop(explode('/',$_SERVER['SCRIPT_NAME']));
251 $this->app_base = get_bloginfo('url') . '/' . $this->script_name . '/';
252 if ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) {
253 $this->app_base = preg_replace( '/^http:\/\//', 'https://', $this->app_base );
256 $this->selectors = array(
258 array('GET' => 'get_service'),
260 array('GET' => 'get_categories_xml'),
262 array('GET' => 'get_post',
264 'DELETE' => 'delete_post'),
265 '@/posts/?(\d+)?$@' =>
266 array('GET' => 'get_posts',
267 'POST' => 'create_post'),
268 '@/attachments/?(\d+)?$@' =>
269 array('GET' => 'get_attachment',
270 'POST' => 'create_attachment'),
271 '@/attachment/file/(\d+)$@' =>
272 array('GET' => 'get_file',
274 'DELETE' => 'delete_file'),
275 '@/attachment/(\d+)$@' =>
276 array('GET' => 'get_attachment',
277 'PUT' => 'put_attachment',
278 'DELETE' => 'delete_attachment'),
283 * Handle ATOMPUB request.
287 function handle_request() {
288 global $always_authenticate;
290 if( !empty( $_SERVER['ORIG_PATH_INFO'] ) )
291 $path = $_SERVER['ORIG_PATH_INFO'];
293 $path = $_SERVER['PATH_INFO'];
295 $method = $_SERVER['REQUEST_METHOD'];
297 log_app('REQUEST',"$method $path\n================");
299 $this->process_conditionals();
300 //$this->process_conditionals();
302 // exception case for HEAD (treat exactly as GET, but don't output)
303 if($method == 'HEAD') {
304 $this->do_output = false;
308 // redirect to /service in case no path is found.
309 if(strlen($path) == 0 || $path == '/') {
310 $this->redirect($this->get_service_url());
313 // check to see if AtomPub is enabled
314 if( !get_option( 'enable_app' ) )
315 $this->forbidden( sprintf( __( 'AtomPub services are disabled on this blog. An admin user can enable them at %s' ), admin_url('options-writing.php') ) );
318 foreach($this->selectors as $regex => $funcs) {
319 if(preg_match($regex, $path, $matches)) {
320 if(isset($funcs[$method])) {
322 // authenticate regardless of the operation and set the current
323 // user. each handler will decide if auth is required or not.
324 if(!$this->authenticate()) {
325 if ($always_authenticate) {
326 $this->auth_required('Credentials required.');
330 array_shift($matches);
331 call_user_func_array(array(&$this,$funcs[$method]), $matches);
334 // only allow what we have handlers for...
335 $this->not_allowed(array_keys($funcs));
340 // oops, nothing found
345 * Retrieve XML for ATOMPUB service.
349 function get_service() {
350 log_app('function','get_service()');
352 if( !current_user_can( 'edit_posts' ) )
353 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
355 $entries_url = esc_attr($this->get_entries_url());
356 $categories_url = esc_attr($this->get_categories_url());
357 $media_url = esc_attr($this->get_attachments_url());
358 foreach ($this->media_content_types as $med) {
359 $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
362 $atom_blogname=get_bloginfo('name');
363 $service_doc = <<<EOD
364 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
366 <$atom_prefix:title>$atom_blogname Workspace</$atom_prefix:title>
367 <collection href="$entries_url">
368 <$atom_prefix:title>$atom_blogname Posts</$atom_prefix:title>
369 <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
370 <categories href="$categories_url" />
372 <collection href="$media_url">
373 <$atom_prefix:title>$atom_blogname Media</$atom_prefix:title>
374 $accepted_media_types
381 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
385 * Retrieve categories list in XML format.
389 function get_categories_xml() {
390 log_app('function','get_categories_xml()');
392 if( !current_user_can( 'edit_posts' ) )
393 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
395 $home = esc_attr(get_bloginfo_rss('home'));
398 $cats = get_categories("hierarchical=0&hide_empty=0");
399 foreach ((array) $cats as $cat) {
400 $categories .= " <category term=\"" . esc_attr($cat->name) . "\" />\n";
403 <app:categories xmlns:app="$this->ATOMPUB_NS"
404 xmlns="$this->ATOM_NS"
405 fixed="yes" scheme="$home">
409 $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
417 function create_post() {
418 global $blog_id, $user_ID;
419 $this->get_accepted_content_type($this->atom_content_types);
421 $parser = new AtomParser();
422 if(!$parser->parse()) {
423 $this->client_error();
426 $entry = array_pop($parser->feed->entries);
428 log_app('Received entry:', print_r($entry,true));
431 foreach($entry->categories as $cat)
432 array_push($catnames, $cat["term"]);
434 $wp_cats = get_categories(array('hide_empty' => false));
436 $post_category = array();
438 foreach($wp_cats as $cat) {
439 if(in_array($cat->name, $catnames))
440 array_push($post_category, $cat->term_id);
443 $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
445 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
447 if(!current_user_can($cap))
448 $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
450 $blog_ID = (int ) $blog_id;
451 $post_status = ($publish) ? 'publish' : 'draft';
452 $post_author = (int) $user_ID;
453 $post_title = $entry->title[1];
454 $post_content = $entry->content[1];
455 $post_excerpt = $entry->summary[1];
456 $pubtimes = $this->get_publish_time($entry->published);
457 $post_date = $pubtimes[0];
458 $post_date_gmt = $pubtimes[1];
460 if ( isset( $_SERVER['HTTP_SLUG'] ) )
461 $post_name = $_SERVER['HTTP_SLUG'];
463 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
465 $this->escape($post_data);
466 log_app('Inserting Post. Data:', print_r($post_data,true));
468 $postID = wp_insert_post($post_data);
469 if ( is_wp_error( $postID ) )
470 $this->internal_error($postID->get_error_message());
473 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
475 // getting warning here about unable to set headers
476 // because something in the cache is printing to the buffer
477 // could we clean up wp_set_post_categories or cache to not print
478 // this could affect our ability to send back the right headers
479 @wp_set_post_categories($postID, $post_category);
481 do_action( 'atompub_create_post', $postID, $entry );
483 $output = $this->get_entry($postID);
485 log_app('function',"create_post($postID)");
486 $this->created($postID, $output);
494 * @param int $postID Post ID.
496 function get_post($postID) {
499 if( !current_user_can( 'edit_post', $postID ) )
500 $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
502 $this->set_current_entry($postID);
503 $output = $this->get_entry($postID);
504 log_app('function',"get_post($postID)");
505 $this->output($output);
514 * @param int $postID Post ID.
516 function put_post($postID) {
517 // checked for valid content-types (atom+xml)
518 // quick check and exit
519 $this->get_accepted_content_type($this->atom_content_types);
521 $parser = new AtomParser();
522 if(!$parser->parse()) {
523 $this->bad_request();
526 $parsed = array_pop($parser->feed->entries);
528 log_app('Received UPDATED entry:', print_r($parsed,true));
530 // check for not found
532 $this->set_current_entry($postID);
534 if(!current_user_can('edit_post', $entry['ID']))
535 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
537 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
538 $post_status = ($publish) ? 'publish' : 'draft';
542 $post_title = $parsed->title[1];
543 $post_content = $parsed->content[1];
544 $post_excerpt = $parsed->summary[1];
545 $pubtimes = $this->get_publish_time($entry->published);
546 $post_date = $pubtimes[0];
547 $post_date_gmt = $pubtimes[1];
548 $pubtimes = $this->get_publish_time($parsed->updated);
549 $post_modified = $pubtimes[0];
550 $post_modified_gmt = $pubtimes[1];
552 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
553 $this->escape($postdata);
555 $result = wp_update_post($postdata);
558 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
561 do_action( 'atompub_put_post', $ID, $parsed );
563 log_app('function',"put_post($postID)");
572 * @param int $postID Post ID.
574 function delete_post($postID) {
576 // check for not found
578 $this->set_current_entry($postID);
580 if(!current_user_can('edit_post', $postID)) {
581 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
584 if ($entry['post_type'] == 'attachment') {
585 $this->delete_attachment($postID);
587 $result = wp_delete_post($postID);
590 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
593 log_app('function',"delete_post($postID)");
600 * Retrieve attachment.
604 * @param int $postID Optional. Post ID.
606 function get_attachment($postID = null) {
607 if( !current_user_can( 'upload_files' ) )
608 $this->auth_required( __( 'Sorry, you do not have permission to upload files.' ) );
610 if (!isset($postID)) {
611 $this->get_attachments();
613 $this->set_current_entry($postID);
614 $output = $this->get_entry($postID, 'attachment');
615 log_app('function',"get_attachment($postID)");
616 $this->output($output);
621 * Create new attachment.
625 function create_attachment() {
627 $type = $this->get_accepted_content_type();
629 if(!current_user_can('upload_files'))
630 $this->auth_required(__('You do not have permission to upload files.'));
632 $fp = fopen("php://input", "rb");
635 $bits .= fread($fp, 4096);
640 if ( isset( $_SERVER['HTTP_SLUG'] ) )
641 $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] );
642 elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
643 $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] );
644 elseif ( empty( $slug ) ) // just make a random name
645 $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
646 $ext = preg_replace( '|.*/([a-z0-9]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
647 $slug = "$slug.$ext";
648 $file = wp_upload_bits( $slug, NULL, $bits);
650 log_app('wp_upload_bits returns:',print_r($file,true));
653 $file = $file['file'];
655 do_action('wp_create_file_in_uploads', $file); // replicate
657 // Construct the attachment array
659 'post_title' => $slug,
660 'post_content' => $slug,
661 'post_status' => 'attachment',
663 'post_mime_type' => $type,
668 $postID = wp_insert_attachment($attachment, $file);
671 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
673 $output = $this->get_entry($postID, 'attachment');
675 $this->created($postID, $output, 'attachment');
676 log_app('function',"create_attachment($postID)");
684 * @param int $postID Post ID.
686 function put_attachment($postID) {
687 // checked for valid content-types (atom+xml)
688 // quick check and exit
689 $this->get_accepted_content_type($this->atom_content_types);
691 $parser = new AtomParser();
692 if(!$parser->parse()) {
693 $this->bad_request();
696 $parsed = array_pop($parser->feed->entries);
698 // check for not found
700 $this->set_current_entry($postID);
702 if(!current_user_can('edit_post', $entry['ID']))
703 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
707 $post_title = $parsed->title[1];
708 $post_content = $parsed->summary[1];
709 $pubtimes = $this->get_publish_time($parsed->updated);
710 $post_modified = $pubtimes[0];
711 $post_modified_gmt = $pubtimes[1];
713 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt');
714 $this->escape($postdata);
716 $result = wp_update_post($postdata);
719 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
722 log_app('function',"put_attachment($postID)");
731 * @param int $postID Post ID.
733 function delete_attachment($postID) {
734 log_app('function',"delete_attachment($postID). File '$location' deleted.");
736 // check for not found
738 $this->set_current_entry($postID);
740 if(!current_user_can('edit_post', $postID)) {
741 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
744 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
745 $filetype = wp_check_filetype($location);
747 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
748 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
754 $result = wp_delete_post($postID);
757 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
760 log_app('function',"delete_attachment($postID). File '$location' deleted.");
765 * Retrieve attachment from post.
769 * @param int $postID Post ID.
771 function get_file($postID) {
773 // check for not found
775 $this->set_current_entry($postID);
777 // then whether user can edit the specific post
778 if(!current_user_can('edit_post', $postID)) {
779 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
782 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
783 $filetype = wp_check_filetype($location);
785 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
786 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
788 status_header('200');
789 header('Content-Type: ' . $entry['post_mime_type']);
790 header('Connection: close');
792 $fp = fopen($location, "rb");
794 echo fread($fp, 4096);
798 log_app('function',"get_file($postID)");
803 * Upload file to blog and add attachment to post.
807 * @param int $postID Post ID.
809 function put_file($postID) {
811 // first check if user can upload
812 if(!current_user_can('upload_files'))
813 $this->auth_required(__('You do not have permission to upload files.'));
815 // check for not found
817 $this->set_current_entry($postID);
819 // then whether user can edit the specific post
820 if(!current_user_can('edit_post', $postID)) {
821 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
824 $upload_dir = wp_upload_dir( );
825 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
826 $filetype = wp_check_filetype($location);
828 $location = "{$upload_dir['basedir']}/{$location}";
830 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
831 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
833 $fp = fopen("php://input", "rb");
834 $localfp = fopen($location, "w+");
836 fwrite($localfp,fread($fp, 4096));
842 $pubtimes = $this->get_publish_time($entry->published);
843 $post_date = $pubtimes[0];
844 $post_date_gmt = $pubtimes[1];
845 $pubtimes = $this->get_publish_time($parsed->updated);
846 $post_modified = $pubtimes[0];
847 $post_modified_gmt = $pubtimes[1];
849 $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
850 $result = wp_update_post($post_data);
853 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
856 wp_update_attachment_metadata( $postID, wp_generate_attachment_metadata( $postID, $location ) );
858 log_app('function',"put_file($postID)");
863 * Retrieve entries URL.
867 * @param int $page Page ID.
870 function get_entries_url($page = null) {
871 if($GLOBALS['post_type'] == 'attachment') {
872 $path = $this->MEDIA_PATH;
874 $path = $this->ENTRIES_PATH;
876 $url = $this->app_base . $path;
877 if(isset($page) && is_int($page)) {
884 * Display entries URL.
888 * @param int $page Page ID.
890 function the_entries_url($page = null) {
891 echo $this->get_entries_url($page);
895 * Retrieve categories URL.
899 * @param mixed $deprecated Optional, not used.
902 function get_categories_url($deprecated = '') {
903 return $this->app_base . $this->CATEGORIES_PATH;
907 * Display category URL.
911 function the_categories_url() {
912 echo $this->get_categories_url();
916 * Retrieve attachment URL.
920 * @param int $page Page ID.
923 function get_attachments_url($page = null) {
924 $url = $this->app_base . $this->MEDIA_PATH;
925 if(isset($page) && is_int($page)) {
932 * Display attachment URL.
936 * @param int $page Page ID.
938 function the_attachments_url($page = null) {
939 echo $this->get_attachments_url($page);
943 * Retrieve service URL.
949 function get_service_url() {
950 return $this->app_base . $this->SERVICE_PATH;
954 * Retrieve entry URL.
958 * @param int $postID Post ID.
961 function get_entry_url($postID = null) {
962 if(!isset($postID)) {
964 $postID = (int) $post->ID;
967 $url = $this->app_base . $this->ENTRY_PATH . "/$postID";
969 log_app('function',"get_entry_url() = $url");
978 * @param int $postID Post ID.
980 function the_entry_url($postID = null) {
981 echo $this->get_entry_url($postID);
985 * Retrieve media URL.
989 * @param int $postID Post ID.
992 function get_media_url($postID = null) {
993 if(!isset($postID)) {
995 $postID = (int) $post->ID;
998 $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID";
1000 log_app('function',"get_media_url() = $url");
1005 * Display the media URL.
1009 * @param int $postID Post ID.
1011 function the_media_url($postID = null) {
1012 echo $this->get_media_url($postID);
1016 * Set the current entry to post ID.
1020 * @param int $postID Post ID.
1022 function set_current_entry($postID) {
1024 log_app('function',"set_current_entry($postID)");
1026 if(!isset($postID)) {
1027 // $this->bad_request();
1031 $entry = wp_get_single_post($postID,ARRAY_A);
1033 if(!isset($entry) || !isset($entry['ID']))
1040 * Display posts XML.
1044 * @param int $page Optional. Page ID.
1045 * @param string $post_type Optional, default is 'post'. Post Type.
1047 function get_posts($page = 1, $post_type = 'post') {
1048 log_app('function',"get_posts($page, '$post_type')");
1049 $feed = $this->get_feed($page, $post_type);
1050 $this->output($feed);
1054 * Display attachment XML.
1058 * @param int $page Page ID.
1059 * @param string $post_type Optional, default is 'attachment'. Post type.
1061 function get_attachments($page = 1, $post_type = 'attachment') {
1062 log_app('function',"get_attachments($page, '$post_type')");
1063 $GLOBALS['post_type'] = $post_type;
1064 $feed = $this->get_feed($page, $post_type);
1065 $this->output($feed);
1069 * Retrieve feed XML.
1073 * @param int $page Page ID.
1074 * @param string $post_type Optional, default is post. Post type.
1077 function get_feed($page = 1, $post_type = 'post') {
1078 global $post, $wp, $wp_query, $posts, $wpdb, $blog_id;
1079 log_app('function',"get_feed($page, '$post_type')");
1082 $this->ENTRY_PATH = $post_type;
1087 $page = (int) $page;
1089 $count = get_option('posts_per_rss');
1091 wp('posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified'));
1093 $post = $GLOBALS['post'];
1094 $posts = $GLOBALS['posts'];
1095 $wp = $GLOBALS['wp'];
1096 $wp_query = $GLOBALS['wp_query'];
1097 $wpdb = $GLOBALS['wpdb'];
1098 $blog_id = (int) $GLOBALS['blog_id'];
1099 log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)");
1101 log_app('function',"total_count(# $wp_query->max_num_pages #)");
1102 $last_page = $wp_query->max_num_pages;
1103 $next_page = (($page + 1) > $last_page) ? NULL : $page + 1;
1104 $prev_page = ($page - 1) < 1 ? NULL : $page - 1;
1105 $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page;
1106 $self_page = $page > 1 ? $page : NULL;
1107 ?><feed xmlns="<?php echo $this->ATOM_NS ?>" xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
1108 <id><?php $this->the_entries_url() ?></id>
1109 <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT'), false); ?></updated>
1110 <title type="text"><?php bloginfo_rss('name') ?></title>
1111 <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle>
1112 <link rel="first" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url() ?>" />
1113 <?php if(isset($prev_page)): ?>
1114 <link rel="previous" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($prev_page) ?>" />
1116 <?php if(isset($next_page)): ?>
1117 <link rel="next" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($next_page) ?>" />
1119 <link rel="last" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($last_page) ?>" />
1120 <link rel="self" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($self_page) ?>" />
1121 <rights type="text">Copyright <?php echo date('Y'); ?></rights>
1122 <?php the_generator( 'atom' ); ?>
1123 <?php if ( have_posts() ) {
1124 while ( have_posts() ) {
1126 $this->echo_entry();
1131 $feed = ob_get_contents();
1137 * Display entry XML.
1141 * @param int $postID Post ID.
1142 * @param string $post_type Optional, default is post. Post type.
1145 function get_entry($postID, $post_type = 'post') {
1146 log_app('function',"get_entry($postID, '$post_type')");
1148 switch($post_type) {
1153 $this->ENTRY_PATH = 'attachment';
1154 $varname = 'attachment_id';
1157 query_posts($varname . '=' . $postID);
1158 if ( have_posts() ) {
1159 while ( have_posts() ) {
1161 $this->echo_entry();
1162 log_app('$post',print_r($GLOBALS['post'],true));
1163 $entry = ob_get_contents();
1169 log_app('get_entry returning:',$entry);
1174 * Display post content XML.
1178 function echo_entry() { ?>
1179 <entry xmlns="<?php echo $this->ATOM_NS ?>"
1180 xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
1181 <id><?php the_guid($GLOBALS['post']->ID); ?></id>
1182 <?php list($content_type, $content) = prep_atom_text_construct(get_the_title()); ?>
1183 <title type="<?php echo $content_type ?>"><?php echo $content ?></title>
1184 <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
1185 <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
1186 <app:edited><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></app:edited>
1188 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
1191 <name><?php the_author()?></name>
1192 <?php if ( get_the_author_meta('url') && get_the_author_meta('url') != 'http://' ) { ?>
1193 <uri><?php the_author_meta('url') ?></uri>
1196 <?php if($GLOBALS['post']->post_type == 'attachment') { ?>
1197 <link rel="edit-media" href="<?php $this->the_media_url() ?>" />
1198 <content type="<?php echo $GLOBALS['post']->post_mime_type ?>" src="<?php the_guid(); ?>"/>
1200 <link href="<?php the_permalink_rss() ?>" />
1201 <?php if ( strlen( $GLOBALS['post']->post_content ) ) :
1202 list($content_type, $content) = prep_atom_text_construct(get_the_content()); ?>
1203 <content type="<?php echo $content_type ?>"><?php echo $content ?></content>
1206 <link rel="edit" href="<?php $this->the_entry_url() ?>" />
1207 <?php the_category_rss( 'atom' ); ?>
1208 <?php list($content_type, $content) = prep_atom_text_construct(get_the_excerpt()); ?>
1209 <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
1214 * Set 'OK' (200) status header.
1219 log_app('Status','200: OK');
1220 header('Content-Type: text/plain');
1221 status_header('200');
1226 * Set 'No Content' (204) status header.
1230 function no_content() {
1231 log_app('Status','204: No Content');
1232 header('Content-Type: text/plain');
1233 status_header('204');
1239 * Display 'Internal Server Error' (500) status header.
1243 * @param string $msg Optional. Status string.
1245 function internal_error($msg = 'Internal Server Error') {
1246 log_app('Status','500: Server Error');
1247 header('Content-Type: text/plain');
1248 status_header('500');
1254 * Set 'Bad Request' (400) status header.
1258 function bad_request() {
1259 log_app('Status','400: Bad Request');
1260 header('Content-Type: text/plain');
1261 status_header('400');
1266 * Set 'Length Required' (411) status header.
1270 function length_required() {
1271 log_app('Status','411: Length Required');
1272 header("HTTP/1.1 411 Length Required");
1273 header('Content-Type: text/plain');
1274 status_header('411');
1279 * Set 'Unsupported Media Type' (415) status header.
1283 function invalid_media() {
1284 log_app('Status','415: Unsupported Media Type');
1285 header("HTTP/1.1 415 Unsupported Media Type");
1286 header('Content-Type: text/plain');
1291 * Set 'Forbidden' (403) status header.
1295 function forbidden($reason='') {
1296 log_app('Status','403: Forbidden');
1297 header('Content-Type: text/plain');
1298 status_header('403');
1304 * Set 'Not Found' (404) status header.
1308 function not_found() {
1309 log_app('Status','404: Not Found');
1310 header('Content-Type: text/plain');
1311 status_header('404');
1316 * Set 'Not Allowed' (405) status header.
1320 function not_allowed($allow) {
1321 log_app('Status','405: Not Allowed');
1322 header('Allow: ' . join(',', $allow));
1323 status_header('405');
1328 * Display Redirect (302) content and set status headers.
1332 function redirect($url) {
1334 log_app('Status','302: Redirect');
1335 $escaped_url = esc_attr($url);
1337 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1340 <title>302 Found</title>
1344 <p>The document has moved <a href="$escaped_url">here</a>.</p>
1349 header('HTTP/1.1 302 Moved');
1350 header('Content-Type: text/html');
1351 header('Location: ' . $url);
1358 * Set 'Client Error' (400) status header.
1362 function client_error($msg = 'Client Error') {
1363 log_app('Status','400: Client Error');
1364 header('Content-Type: text/plain');
1365 status_header('400');
1370 * Set created status headers (201).
1372 * Sets the 'content-type', 'content-location', and 'location'.
1376 function created($post_ID, $content, $post_type = 'post') {
1377 log_app('created()::$post_ID',"$post_ID, $post_type");
1378 $edit = $this->get_entry_url($post_ID);
1379 switch($post_type) {
1381 $ctloc = $this->get_entry_url($post_ID);
1384 $edit = $this->app_base . "attachments/$post_ID";
1387 header("Content-Type: $this->ATOM_CONTENT_TYPE");
1389 header('Content-Location: ' . $ctloc);
1390 header('Location: ' . $edit);
1391 status_header('201');
1397 * Set 'Auth Required' (401) headers.
1401 * @param string $msg Status header content and HTML content.
1403 function auth_required($msg) {
1404 log_app('Status','401: Auth Required');
1406 header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"');
1407 header("HTTP/1.1 401 $msg");
1408 header('Status: 401 ' . $msg);
1409 header('Content-Type: text/html');
1411 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
1414 <title>401 Unauthorized</title>
1417 <h1>401 Unauthorized</h1>
1428 * Display XML and set headers with content type.
1432 * @param string $xml Display feed content.
1433 * @param string $ctype Optional, default is 'atom+xml'. Feed content type.
1435 function output($xml, $ctype = 'application/atom+xml') {
1436 status_header('200');
1437 $xml = '<?xml version="1.0" encoding="' . strtolower(get_option('blog_charset')) . '"?>'."\n".$xml;
1438 header('Connection: close');
1439 header('Content-Length: '. strlen($xml));
1440 header('Content-Type: ' . $ctype);
1441 header('Content-Disposition: attachment; filename=atom.xml');
1442 header('Date: '. date('r'));
1443 if($this->do_output)
1445 log_app('function', "output:\n$xml");
1450 * Sanitize content for database usage.
1454 * @param array $array Sanitize array and multi-dimension array.
1456 function escape(&$array) {
1459 foreach ($array as $k => $v) {
1461 $this->escape($array[$k]);
1462 } else if (is_object($v)) {
1465 $array[$k] = $wpdb->escape($v);
1471 * Access credential through various methods and perform login.
1477 function authenticate() {
1478 log_app("authenticate()",print_r($_ENV, true));
1480 // if using mod_rewrite/ENV hack
1481 // http://www.besthostratings.com/articles/http-auth-php-cgi.html
1482 if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
1483 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1484 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
1485 } else if (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
1486 // Workaround for setups that do not forward HTTP_AUTHORIZATION
1487 // See http://trac.wordpress.org/ticket/7361
1488 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1489 explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
1492 // If Basic Auth is working...
1493 if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
1494 log_app("Basic Auth",$_SERVER['PHP_AUTH_USER']);
1497 $user = wp_authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
1498 if ( $user && !is_wp_error($user) ) {
1499 wp_set_current_user($user->ID);
1500 log_app("authenticate()", $user->user_login);
1508 * Retrieve accepted content types.
1512 * @param array $types Optional. Content Types.
1515 function get_accepted_content_type($types = null) {
1517 if(!isset($types)) {
1518 $types = $this->media_content_types;
1521 if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1522 $this->length_required();
1525 $type = $_SERVER['CONTENT_TYPE'];
1526 list($type,$subtype) = explode('/',$type);
1527 list($subtype) = explode(";",$subtype); // strip MIME parameters
1528 log_app("get_accepted_content_type", "type=$type, subtype=$subtype");
1530 foreach($types as $t) {
1531 list($acceptedType,$acceptedSubtype) = explode('/',$t);
1532 if($acceptedType == '*' || $acceptedType == $type) {
1533 if($acceptedSubtype == '*' || $acceptedSubtype == $subtype)
1534 return $type . "/" . $subtype;
1538 $this->invalid_media();
1542 * Process conditionals for posts.
1546 function process_conditionals() {
1548 if(empty($this->params)) return;
1549 if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1551 switch($this->params[0]) {
1552 case $this->ENTRY_PATH:
1554 $post = wp_get_single_post($this->params[1]);
1555 $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true);
1558 case $this->ENTRIES_PATH:
1559 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1564 $wp_etag = md5($wp_last_modified);
1565 @header("Last-Modified: $wp_last_modified");
1566 @header("ETag: $wp_etag");
1568 // Support for Conditional GET
1569 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1570 $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1572 $client_etag = false;
1574 $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1575 // If string is empty, return 0. If not, attempt to parse into a timestamp
1576 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
1578 // Make a timestamp for our most recent modification...
1579 $wp_modified_timestamp = strtotime($wp_last_modified);
1581 if ( ($client_last_modified && $client_etag) ?
1582 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
1583 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
1584 status_header( 304 );
1590 * Convert RFC3339 time string to timestamp.
1594 * @param string $str String to time.
1595 * @return bool|int false if format is incorrect.
1597 function rfc3339_str2time($str) {
1600 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))
1603 if($match[3] == 'Z')
1604 $match[3] == '+0000';
1606 return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1610 * Retrieve published time to display in XML.
1614 * @param string $published Time string.
1617 function get_publish_time($published) {
1619 $pubtime = $this->rfc3339_str2time($published);
1622 return array(current_time('mysql'),current_time('mysql',1));
1624 return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1633 * @global object $server
1635 $server = new AtomServer();
1636 $server->handle_request();