3 * wp-app.php - Atom Publishing Protocol support for WordPress
4 * Original code by: Elias Torres, http://torrez.us/archives/2006/08/31/491/
5 * Modified by: Dougal Campbell, http://dougal.gunters.org/
10 define('APP_REQUEST', true);
12 require_once('./wp-config.php');
13 require_once(ABSPATH . WPINC . '/post-template.php');
14 require_once(ABSPATH . WPINC . '/atomlib.php');
15 require_once(ABSPATH . WPINC . '/feed.php');
17 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
21 // TODO: Should be an option somewhere
22 $always_authenticate = 1;
24 function log_app($label,$msg) {
27 $fp = fopen( 'wp-app.log', 'a+');
28 $date = gmdate( 'Y-m-d H:i:s' );
29 fwrite($fp, "\n\n$date - $label\n$msg\n");
34 if ( !function_exists('wp_set_current_user') ) :
35 function wp_set_current_user($id, $name = '') {
38 if ( isset($current_user) && ($id == $current_user->ID) )
41 $current_user = new WP_User($id, $name);
47 function wa_posts_where_include_drafts_filter($where) {
48 $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where);
52 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
56 var $ATOM_CONTENT_TYPE = 'application/atom+xml';
57 var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
58 var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
60 var $ATOM_NS = 'http://www.w3.org/2005/Atom';
61 var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
63 var $ENTRIES_PATH = "posts";
64 var $CATEGORIES_PATH = "categories";
65 var $MEDIA_PATH = "attachments";
66 var $ENTRY_PATH = "post";
67 var $SERVICE_PATH = "service";
68 var $MEDIA_SINGLE_PATH = "attachment";
70 var $params = array();
71 var $media_content_types = array('image/*','audio/*','video/*');
72 var $atom_content_types = array('application/atom+xml');
74 var $selectors = array();
77 var $do_output = true;
79 function AtomServer() {
81 $this->script_name = array_pop(explode('/',$_SERVER['SCRIPT_NAME']));
82 $this->app_base = get_bloginfo('url') . '/' . $this->script_name . '/';
83 if ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) {
84 $this->app_base = preg_replace( '/^http:\/\//', 'https://', $this->app_base );
87 $this->selectors = array(
89 array('GET' => 'get_service'),
91 array('GET' => 'get_categories_xml'),
93 array('GET' => 'get_post',
95 'DELETE' => 'delete_post'),
96 '@/posts/?(\d+)?$@' =>
97 array('GET' => 'get_posts',
98 'POST' => 'create_post'),
99 '@/attachments/?(\d+)?$@' =>
100 array('GET' => 'get_attachment',
101 'POST' => 'create_attachment'),
102 '@/attachment/file/(\d+)$@' =>
103 array('GET' => 'get_file',
105 'DELETE' => 'delete_file'),
106 '@/attachment/(\d+)$@' =>
107 array('GET' => 'get_attachment',
108 'PUT' => 'put_attachment',
109 'DELETE' => 'delete_attachment'),
113 function handle_request() {
114 global $always_authenticate;
116 $path = $_SERVER['PATH_INFO'];
117 $method = $_SERVER['REQUEST_METHOD'];
119 log_app('REQUEST',"$method $path\n================");
121 $this->process_conditionals();
122 //$this->process_conditionals();
124 // exception case for HEAD (treat exactly as GET, but don't output)
125 if($method == 'HEAD') {
126 $this->do_output = false;
130 // redirect to /service in case no path is found.
131 if(strlen($path) == 0 || $path == '/') {
132 $this->redirect($this->get_service_url());
136 foreach($this->selectors as $regex => $funcs) {
137 if(preg_match($regex, $path, $matches)) {
138 if(isset($funcs[$method])) {
140 // authenticate regardless of the operation and set the current
141 // user. each handler will decide if auth is required or not.
142 $this->authenticate();
143 $u = wp_get_current_user();
144 if(!isset($u) || $u->ID == 0) {
145 if ($always_authenticate) {
146 $this->auth_required('Credentials required.');
150 array_shift($matches);
151 call_user_func_array(array(&$this,$funcs[$method]), $matches);
154 // only allow what we have handlers for...
155 $this->not_allowed(array_keys($funcs));
160 // oops, nothing found
164 function get_service() {
165 log_app('function','get_service()');
167 if( !current_user_can( 'edit_posts' ) )
168 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
170 $entries_url = attribute_escape($this->get_entries_url());
171 $categories_url = attribute_escape($this->get_categories_url());
172 $media_url = attribute_escape($this->get_attachments_url());
173 foreach ($this->media_content_types as $med) {
174 $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
177 $atom_blogname=get_bloginfo('name');
178 $service_doc = <<<EOD
179 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
181 <$atom_prefix:title>$atom_blogname Workspace</$atom_prefix:title>
182 <collection href="$entries_url">
183 <$atom_prefix:title>$atom_blogname Posts</$atom_prefix:title>
184 <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
185 <categories href="$categories_url" />
187 <collection href="$media_url">
188 <$atom_prefix:title>$atom_blogname Media</$atom_prefix:title>
189 $accepted_media_types
196 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
199 function get_categories_xml() {
200 log_app('function','get_categories_xml()');
202 if( !current_user_can( 'edit_posts' ) )
203 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
205 $home = attribute_escape(get_bloginfo_rss('home'));
208 $cats = get_categories("hierarchical=0&hide_empty=0");
209 foreach ((array) $cats as $cat) {
210 $categories .= " <category term=\"" . attribute_escape($cat->name) . "\" />\n";
213 <app:categories xmlns:app="$this->ATOMPUB_NS"
214 xmlns="$this->ATOM_NS"
215 fixed="yes" scheme="$home">
219 $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
223 * Create Post (No arguments)
225 function create_post() {
226 global $blog_id, $user_ID;
227 $this->get_accepted_content_type($this->atom_content_types);
229 $parser = new AtomParser();
230 if(!$parser->parse()) {
231 $this->client_error();
234 $entry = array_pop($parser->feed->entries);
236 log_app('Received entry:', print_r($entry,true));
239 foreach($entry->categories as $cat)
240 array_push($catnames, $cat["term"]);
242 $wp_cats = get_categories(array('hide_empty' => false));
244 $post_category = array();
246 foreach($wp_cats as $cat) {
247 if(in_array($cat->name, $catnames))
248 array_push($post_category, $cat->term_id);
251 $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
253 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
255 if(!current_user_can($cap))
256 $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
258 $blog_ID = (int ) $blog_id;
259 $post_status = ($publish) ? 'publish' : 'draft';
260 $post_author = (int) $user_ID;
261 $post_title = $entry->title[1];
262 $post_content = $entry->content[1];
263 $post_excerpt = $entry->summary[1];
264 $pubtimes = $this->get_publish_time($entry->published);
265 $post_date = $pubtimes[0];
266 $post_date_gmt = $pubtimes[1];
268 if ( isset( $_SERVER['HTTP_SLUG'] ) )
269 $post_name = $_SERVER['HTTP_SLUG'];
271 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
273 $this->escape($post_data);
274 log_app('Inserting Post. Data:', print_r($post_data,true));
276 $postID = wp_insert_post($post_data);
277 if ( is_wp_error( $postID ) )
278 $this->internal_error($postID->get_error_message());
281 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
283 // getting warning here about unable to set headers
284 // because something in the cache is printing to the buffer
285 // could we clean up wp_set_post_categories or cache to not print
286 // this could affect our ability to send back the right headers
287 @wp_set_post_categories($postID, $post_category);
289 $output = $this->get_entry($postID);
291 log_app('function',"create_post($postID)");
292 $this->created($postID, $output);
295 function get_post($postID) {
298 if( !current_user_can( 'edit_post', $postID ) )
299 $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
301 $this->set_current_entry($postID);
302 $output = $this->get_entry($postID);
303 log_app('function',"get_post($postID)");
304 $this->output($output);
308 function put_post($postID) {
309 // checked for valid content-types (atom+xml)
310 // quick check and exit
311 $this->get_accepted_content_type($this->atom_content_types);
313 $parser = new AtomParser();
314 if(!$parser->parse()) {
315 $this->bad_request();
318 $parsed = array_pop($parser->feed->entries);
320 log_app('Received UPDATED entry:', print_r($parsed,true));
322 // check for not found
324 $this->set_current_entry($postID);
326 if(!current_user_can('edit_post', $entry['ID']))
327 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
329 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
333 $post_title = $parsed->title[1];
334 $post_content = $parsed->content[1];
335 $post_excerpt = $parsed->summary[1];
336 $pubtimes = $this->get_publish_time($entry->published);
337 $post_date = $pubtimes[0];
338 $post_date_gmt = $pubtimes[1];
339 $pubtimes = $this->get_publish_time($parsed->updated);
340 $post_modified = $pubtimes[0];
341 $post_modified_gmt = $pubtimes[1];
343 // let's not go backwards and make something draft again.
344 if(!$publish && $post_status == 'draft') {
345 $post_status = ($publish) ? 'publish' : 'draft';
347 $post_status = 'publish';
350 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
351 $this->escape($postdata);
353 $result = wp_update_post($postdata);
356 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
359 log_app('function',"put_post($postID)");
363 function delete_post($postID) {
365 // check for not found
367 $this->set_current_entry($postID);
369 if(!current_user_can('edit_post', $postID)) {
370 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
373 if ($entry['post_type'] == 'attachment') {
374 $this->delete_attachment($postID);
376 $result = wp_delete_post($postID);
379 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
382 log_app('function',"delete_post($postID)");
388 function get_attachment($postID = NULL) {
389 if( !current_user_can( 'upload_files' ) )
390 $this->auth_required( __( 'Sorry, you do not have permission to upload files.' ) );
392 if (!isset($postID)) {
393 $this->get_attachments();
395 $this->set_current_entry($postID);
396 $output = $this->get_entry($postID, 'attachment');
397 log_app('function',"get_attachment($postID)");
398 $this->output($output);
402 function create_attachment() {
404 $type = $this->get_accepted_content_type();
406 if(!current_user_can('upload_files'))
407 $this->auth_required(__('You do not have permission to upload files.'));
409 $fp = fopen("php://input", "rb");
412 $bits .= fread($fp, 4096);
417 if ( isset( $_SERVER['HTTP_SLUG'] ) )
418 $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] );
419 elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
420 $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] );
421 elseif ( empty( $slug ) ) // just make a random name
422 $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
423 $ext = preg_replace( '|.*/([a-z0-9]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
424 $slug = "$slug.$ext";
425 $file = wp_upload_bits( $slug, NULL, $bits);
427 log_app('wp_upload_bits returns:',print_r($file,true));
430 $file = $file['file'];
432 do_action('wp_create_file_in_uploads', $file); // replicate
434 // Construct the attachment array
436 'post_title' => $slug,
437 'post_content' => $slug,
438 'post_status' => 'attachment',
440 'post_mime_type' => $type,
445 $postID = wp_insert_attachment($attachment, $file);
448 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
450 $output = $this->get_entry($postID, 'attachment');
452 $this->created($postID, $output, 'attachment');
453 log_app('function',"create_attachment($postID)");
456 function put_attachment($postID) {
457 // checked for valid content-types (atom+xml)
458 // quick check and exit
459 $this->get_accepted_content_type($this->atom_content_types);
461 $parser = new AtomParser();
462 if(!$parser->parse()) {
463 $this->bad_request();
466 $parsed = array_pop($parser->feed->entries);
468 // check for not found
470 $this->set_current_entry($postID);
472 if(!current_user_can('edit_post', $entry['ID']))
473 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
477 $post_title = $parsed->title[1];
478 $post_content = $parsed->content[1];
479 $pubtimes = $this->get_publish_time($parsed->updated);
480 $post_modified = $pubtimes[0];
481 $post_modified_gmt = $pubtimes[1];
483 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt');
484 $this->escape($postdata);
486 $result = wp_update_post($postdata);
489 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
492 log_app('function',"put_attachment($postID)");
496 function delete_attachment($postID) {
497 log_app('function',"delete_attachment($postID). File '$location' deleted.");
499 // check for not found
501 $this->set_current_entry($postID);
503 if(!current_user_can('edit_post', $postID)) {
504 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
507 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
508 $filetype = wp_check_filetype($location);
510 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
511 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
517 $result = wp_delete_post($postID);
520 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
523 log_app('function',"delete_attachment($postID). File '$location' deleted.");
527 function get_file($postID) {
529 // check for not found
531 $this->set_current_entry($postID);
533 // then whether user can edit the specific post
534 if(!current_user_can('edit_post', $postID)) {
535 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
538 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
539 $filetype = wp_check_filetype($location);
541 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
542 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
544 status_header('200');
545 header('Content-Type: ' . $entry['post_mime_type']);
546 header('Connection: close');
548 $fp = fopen($location, "rb");
550 echo fread($fp, 4096);
554 log_app('function',"get_file($postID)");
558 function put_file($postID) {
560 // first check if user can upload
561 if(!current_user_can('upload_files'))
562 $this->auth_required(__('You do not have permission to upload files.'));
564 // check for not found
566 $this->set_current_entry($postID);
568 // then whether user can edit the specific post
569 if(!current_user_can('edit_post', $postID)) {
570 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
573 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
574 $filetype = wp_check_filetype($location);
576 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
577 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
579 $fp = fopen("php://input", "rb");
580 $localfp = fopen($location, "w+");
582 fwrite($localfp,fread($fp, 4096));
588 $pubtimes = $this->get_publish_time($entry->published);
589 $post_date = $pubtimes[0];
590 $post_date_gmt = $pubtimes[1];
591 $pubtimes = $this->get_publish_time($parsed->updated);
592 $post_modified = $pubtimes[0];
593 $post_modified_gmt = $pubtimes[1];
595 $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
596 $result = wp_update_post($post_data);
599 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
602 log_app('function',"put_file($postID)");
606 function get_entries_url($page = NULL) {
607 if($GLOBALS['post_type'] == 'attachment') {
608 $path = $this->MEDIA_PATH;
610 $path = $this->ENTRIES_PATH;
612 $url = $this->app_base . $path;
613 if(isset($page) && is_int($page)) {
619 function the_entries_url($page = NULL) {
620 echo $this->get_entries_url($page);
623 function get_categories_url($deprecated = '') {
624 return $this->app_base . $this->CATEGORIES_PATH;
627 function the_categories_url() {
628 echo $this->get_categories_url();
631 function get_attachments_url($page = NULL) {
632 $url = $this->app_base . $this->MEDIA_PATH;
633 if(isset($page) && is_int($page)) {
639 function the_attachments_url($page = NULL) {
640 echo $this->get_attachments_url($page);
643 function get_service_url() {
644 return $this->app_base . $this->SERVICE_PATH;
647 function get_entry_url($postID = NULL) {
648 if(!isset($postID)) {
650 $postID = (int) $post->ID;
653 $url = $this->app_base . $this->ENTRY_PATH . "/$postID";
655 log_app('function',"get_entry_url() = $url");
659 function the_entry_url($postID = NULL) {
660 echo $this->get_entry_url($postID);
663 function get_media_url($postID = NULL) {
664 if(!isset($postID)) {
666 $postID = (int) $post->ID;
669 $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID";
671 log_app('function',"get_media_url() = $url");
675 function the_media_url($postID = NULL) {
676 echo $this->get_media_url($postID);
679 function set_current_entry($postID) {
681 log_app('function',"set_current_entry($postID)");
683 if(!isset($postID)) {
684 // $this->bad_request();
688 $entry = wp_get_single_post($postID,ARRAY_A);
690 if(!isset($entry) || !isset($entry['ID']))
696 function get_posts($page = 1, $post_type = 'post') {
697 log_app('function',"get_posts($page, '$post_type')");
698 $feed = $this->get_feed($page, $post_type);
699 $this->output($feed);
702 function get_attachments($page = 1, $post_type = 'attachment') {
703 log_app('function',"get_attachments($page, '$post_type')");
704 $GLOBALS['post_type'] = $post_type;
705 $feed = $this->get_feed($page, $post_type);
706 $this->output($feed);
709 function get_feed($page = 1, $post_type = 'post') {
710 global $post, $wp, $wp_query, $posts, $wpdb, $blog_id;
711 log_app('function',"get_feed($page, '$post_type')");
719 $count = get_option('posts_per_rss');
721 wp('what_to_show=posts&posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified'));
723 $post = $GLOBALS['post'];
724 $posts = $GLOBALS['posts'];
725 $wp = $GLOBALS['wp'];
726 $wp_query = $GLOBALS['wp_query'];
727 $wpdb = $GLOBALS['wpdb'];
728 $blog_id = (int) $GLOBALS['blog_id'];
729 log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)");
731 log_app('function',"total_count(# $wp_query->max_num_pages #)");
732 $last_page = $wp_query->max_num_pages;
733 $next_page = (($page + 1) > $last_page) ? NULL : $page + 1;
734 $prev_page = ($page - 1) < 1 ? NULL : $page - 1;
735 $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page;
736 $self_page = $page > 1 ? $page : NULL;
737 ?><feed xmlns="<?php echo $this->ATOM_NS ?>" xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
738 <id><?php $this->the_entries_url() ?></id>
739 <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT')); ?></updated>
740 <title type="text"><?php bloginfo_rss('name') ?></title>
741 <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle>
742 <link rel="first" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url() ?>" />
743 <?php if(isset($prev_page)): ?>
744 <link rel="previous" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($prev_page) ?>" />
746 <?php if(isset($next_page)): ?>
747 <link rel="next" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($next_page) ?>" />
749 <link rel="last" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($last_page) ?>" />
750 <link rel="self" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($self_page) ?>" />
751 <rights type="text">Copyright <?php echo mysql2date('Y', get_lastpostdate('blog')); ?></rights>
752 <?php the_generator( 'atom' ); ?>
753 <?php if ( have_posts() ) {
754 while ( have_posts() ) {
761 $feed = ob_get_contents();
766 function get_entry($postID, $post_type = 'post') {
767 log_app('function',"get_entry($postID, '$post_type')");
774 $varname = 'attachment_id';
777 query_posts($varname . '=' . $postID);
778 if ( have_posts() ) {
779 while ( have_posts() ) {
782 log_app('$post',print_r($GLOBALS['post'],true));
783 $entry = ob_get_contents();
789 log_app('get_entry returning:',$entry);
793 function echo_entry() { ?>
794 <entry xmlns="<?php echo $this->ATOM_NS ?>"
795 xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
796 <id><?php the_guid($GLOBALS['post']->ID); ?></id>
797 <?php list($content_type, $content) = prep_atom_text_construct(get_the_title()); ?>
798 <title type="<?php echo $content_type ?>"><?php echo $content ?></title>
799 <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
800 <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
801 <app:edited><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></app:edited>
803 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
806 <name><?php the_author()?></name>
807 <?php if (get_the_author_url() && get_the_author_url() != 'http://') { ?>
808 <uri><?php the_author_url()?></uri>
811 <?php if($GLOBALS['post']->post_type == 'attachment') { ?>
812 <link rel="edit-media" href="<?php $this->the_media_url() ?>" />
813 <content type="<?php echo $GLOBALS['post']->post_mime_type ?>" src="<?php the_guid(); ?>"/>
815 <link href="<?php the_permalink_rss() ?>" />
816 <?php if ( strlen( $GLOBALS['post']->post_content ) ) :
817 list($content_type, $content) = prep_atom_text_construct(get_the_content()); ?>
818 <content type="<?php echo $content_type ?>"><?php echo $content ?></content>
821 <link rel="edit" href="<?php $this->the_entry_url() ?>" />
822 <?php foreach(get_the_category() as $category) { ?>
823 <category scheme="<?php bloginfo_rss('home') ?>" term="<?php echo $category->name?>" />
825 <?php list($content_type, $content) = prep_atom_text_construct(get_the_excerpt()); ?>
826 <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
831 log_app('Status','200: OK');
832 header('Content-Type: text/plain');
833 status_header('200');
837 function no_content() {
838 log_app('Status','204: No Content');
839 header('Content-Type: text/plain');
840 status_header('204');
845 function internal_error($msg = 'Internal Server Error') {
846 log_app('Status','500: Server Error');
847 header('Content-Type: text/plain');
848 status_header('500');
853 function bad_request() {
854 log_app('Status','400: Bad Request');
855 header('Content-Type: text/plain');
856 status_header('400');
860 function length_required() {
861 log_app('Status','411: Length Required');
862 header("HTTP/1.1 411 Length Required");
863 header('Content-Type: text/plain');
864 status_header('411');
868 function invalid_media() {
869 log_app('Status','415: Unsupported Media Type');
870 header("HTTP/1.1 415 Unsupported Media Type");
871 header('Content-Type: text/plain');
875 function not_found() {
876 log_app('Status','404: Not Found');
877 header('Content-Type: text/plain');
878 status_header('404');
882 function not_allowed($allow) {
883 log_app('Status','405: Not Allowed');
884 header('Allow: ' . join(',', $allow));
885 status_header('405');
889 function redirect($url) {
891 log_app('Status','302: Redirect');
892 $escaped_url = attribute_escape($url);
894 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
897 <title>302 Found</title>
901 <p>The document has moved <a href="$escaped_url">here</a>.</p>
906 header('HTTP/1.1 302 Moved');
907 header('Content-Type: text/html');
908 header('Location: ' . $url);
915 function client_error($msg = 'Client Error') {
916 log_app('Status','400: Client Error');
917 header('Content-Type: text/plain');
918 status_header('400');
922 function created($post_ID, $content, $post_type = 'post') {
923 log_app('created()::$post_ID',"$post_ID, $post_type");
924 $edit = $this->get_entry_url($post_ID);
927 $ctloc = $this->get_entry_url($post_ID);
930 $edit = $this->app_base . "attachments/$post_ID";
933 header("Content-Type: $this->ATOM_CONTENT_TYPE");
935 header('Content-Location: ' . $ctloc);
936 header('Location: ' . $edit);
937 status_header('201');
942 function auth_required($msg) {
943 log_app('Status','401: Auth Required');
945 header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"');
946 header("HTTP/1.1 401 $msg");
947 header('Status: ' . $msg);
948 header('Content-Type: text/html');
950 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
953 <title>401 Unauthorized</title>
956 <h1>401 Unauthorized</h1>
966 function output($xml, $ctype = 'application/atom+xml') {
967 status_header('200');
968 $xml = '<?xml version="1.0" encoding="' . strtolower(get_option('blog_charset')) . '"?>'."\n".$xml;
969 header('Connection: close');
970 header('Content-Length: '. strlen($xml));
971 header('Content-Type: ' . $ctype);
972 header('Content-Disposition: attachment; filename=atom.xml');
973 header('Date: '. date('r'));
976 log_app('function', "output:\n$xml");
980 function escape(&$array) {
983 foreach ($array as $k => $v) {
985 $this->escape($array[$k]);
986 } else if (is_object($v)) {
989 $array[$k] = $wpdb->escape($v);
995 * Access credential through various methods and perform login
997 function authenticate() {
998 $login_data = array();
999 $already_md5 = false;
1001 log_app("authenticate()",print_r($_ENV, true));
1003 // if using mod_rewrite/ENV hack
1004 // http://www.besthostratings.com/articles/http-auth-php-cgi.html
1005 if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
1006 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1007 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
1010 // If Basic Auth is working...
1011 if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
1012 $login_data = array('login' => $_SERVER['PHP_AUTH_USER'], 'password' => $_SERVER['PHP_AUTH_PW']);
1013 log_app("Basic Auth",$login_data['login']);
1015 // else, do cookie-based authentication
1016 if (function_exists('wp_get_cookie_login')) {
1017 $login_data = wp_get_cookie_login();
1018 $already_md5 = true;
1022 // call wp_login and set current user
1023 if (!empty($login_data) && wp_login($login_data['login'], $login_data['password'], $already_md5)) {
1024 $current_user = new WP_User(0, $login_data['login']);
1025 wp_set_current_user($current_user->ID);
1026 log_app("authenticate()",$login_data['login']);
1030 function get_accepted_content_type($types = NULL) {
1032 if(!isset($types)) {
1033 $types = $this->media_content_types;
1036 if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1037 $this->length_required();
1040 $type = $_SERVER['CONTENT_TYPE'];
1041 list($type,$subtype) = explode('/',$type);
1042 list($subtype) = explode(";",$subtype); // strip MIME parameters
1043 log_app("get_accepted_content_type", "type=$type, subtype=$subtype");
1045 foreach($types as $t) {
1046 list($acceptedType,$acceptedSubtype) = explode('/',$t);
1047 if($acceptedType == '*' || $acceptedType == $type) {
1048 if($acceptedSubtype == '*' || $acceptedSubtype == $subtype)
1049 return $type . "/" . $subtype;
1053 $this->invalid_media();
1056 function process_conditionals() {
1058 if(empty($this->params)) return;
1059 if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1061 switch($this->params[0]) {
1062 case $this->ENTRY_PATH:
1064 $post = wp_get_single_post($this->params[1]);
1065 $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true);
1068 case $this->ENTRIES_PATH:
1069 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1074 $wp_etag = md5($wp_last_modified);
1075 @header("Last-Modified: $wp_last_modified");
1076 @header("ETag: $wp_etag");
1078 // Support for Conditional GET
1079 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1080 $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1082 $client_etag = false;
1084 $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1085 // If string is empty, return 0. If not, attempt to parse into a timestamp
1086 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
1088 // Make a timestamp for our most recent modification...
1089 $wp_modified_timestamp = strtotime($wp_last_modified);
1091 if ( ($client_last_modified && $client_etag) ?
1092 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
1093 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
1094 status_header( 304 );
1099 function rfc3339_str2time($str) {
1102 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))
1105 if($match[3] == 'Z')
1106 $match[3] == '+0000';
1108 return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1111 function get_publish_time($published) {
1113 $pubtime = $this->rfc3339_str2time($published);
1116 return array(current_time('mysql'),current_time('mysql',1));
1118 return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1124 $server = new AtomServer();
1125 $server->handle_request();