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');
16 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
20 // TODO: Should be an option somewhere
21 $always_authenticate = 1;
23 function log_app($label,$msg) {
26 $fp = fopen( 'wp-app.log', 'a+');
27 $date = gmdate( 'Y-m-d H:i:s' );
28 fwrite($fp, "\n\n$date - $label\n$msg\n");
33 if ( !function_exists('wp_set_current_user') ) :
34 function wp_set_current_user($id, $name = '') {
37 if ( isset($current_user) && ($id == $current_user->ID) )
40 $current_user = new WP_User($id, $name);
46 function wa_posts_where_include_drafts_filter($where) {
47 $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where);
51 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
55 var $ATOM_CONTENT_TYPE = 'application/atom+xml';
56 var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
57 var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
59 var $ATOM_NS = 'http://www.w3.org/2005/Atom';
60 var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
62 var $ENTRIES_PATH = "posts";
63 var $CATEGORIES_PATH = "categories";
64 var $MEDIA_PATH = "attachments";
65 var $ENTRY_PATH = "post";
66 var $SERVICE_PATH = "service";
67 var $MEDIA_SINGLE_PATH = "attachment";
69 var $params = array();
70 var $script_name = "wp-app.php";
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']));
83 $this->selectors = array(
85 array('GET' => 'get_service'),
87 array('GET' => 'get_categories_xml'),
89 array('GET' => 'get_post',
91 'DELETE' => 'delete_post'),
92 '@/posts/?(\d+)?$@' =>
93 array('GET' => 'get_posts',
94 'POST' => 'create_post'),
95 '@/attachments/?(\d+)?$@' =>
96 array('GET' => 'get_attachment',
97 'POST' => 'create_attachment'),
98 '@/attachment/file/(\d+)$@' =>
99 array('GET' => 'get_file',
101 'DELETE' => 'delete_file'),
102 '@/attachment/(\d+)$@' =>
103 array('GET' => 'get_attachment',
104 'PUT' => 'put_attachment',
105 'DELETE' => 'delete_attachment'),
109 function handle_request() {
110 global $always_authenticate;
112 $path = $_SERVER['PATH_INFO'];
113 $method = $_SERVER['REQUEST_METHOD'];
115 log_app('REQUEST',"$method $path\n================");
117 $this->process_conditionals();
118 //$this->process_conditionals();
120 // exception case for HEAD (treat exactly as GET, but don't output)
121 if($method == 'HEAD') {
122 $this->do_output = false;
126 // redirect to /service in case no path is found.
127 if(strlen($path) == 0 || $path == '/') {
128 $this->redirect($this->get_service_url());
132 foreach($this->selectors as $regex => $funcs) {
133 if(preg_match($regex, $path, $matches)) {
134 if(isset($funcs[$method])) {
136 // authenticate regardless of the operation and set the current
137 // user. each handler will decide if auth is required or not.
138 $this->authenticate();
139 $u = wp_get_current_user();
140 if(!isset($u) || $u->ID == 0) {
141 if ($always_authenticate) {
142 $this->auth_required('Credentials required.');
146 array_shift($matches);
147 call_user_func_array(array(&$this,$funcs[$method]), $matches);
150 // only allow what we have handlers for...
151 $this->not_allowed(array_keys($funcs));
156 // oops, nothing found
160 function get_service() {
161 log_app('function','get_service()');
163 if( !current_user_can( 'edit_posts' ) )
164 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
166 $entries_url = attribute_escape($this->get_entries_url());
167 $categories_url = attribute_escape($this->get_categories_url());
168 $media_url = attribute_escape($this->get_attachments_url());
169 foreach ($this->media_content_types as $med) {
170 $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
173 $service_doc = <<<EOD
174 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
176 <$atom_prefix:title>WordPress Workspace</$atom_prefix:title>
177 <collection href="$entries_url">
178 <$atom_prefix:title>WordPress Posts</$atom_prefix:title>
179 <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
180 <categories href="$categories_url" />
182 <collection href="$media_url">
183 <$atom_prefix:title>WordPress Media</$atom_prefix:title>
184 $accepted_media_types
191 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
194 function get_categories_xml() {
195 log_app('function','get_categories_xml()');
197 if( !current_user_can( 'edit_posts' ) )
198 $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
200 $home = attribute_escape(get_bloginfo_rss('home'));
203 $cats = get_categories("hierarchical=0&hide_empty=0");
204 foreach ((array) $cats as $cat) {
205 $categories .= " <category term=\"" . attribute_escape($cat->name) . "\" />\n";
208 <app:categories xmlns:app="$this->ATOMPUB_NS"
209 xmlns="$this->ATOM_NS"
210 fixed="yes" scheme="$home">
214 $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
218 * Create Post (No arguments)
220 function create_post() {
221 global $blog_id, $wpdb;
222 $this->get_accepted_content_type($this->atom_content_types);
224 $parser = new AtomParser();
225 if(!$parser->parse()) {
226 $this->client_error();
229 $entry = array_pop($parser->feed->entries);
231 log_app('Received entry:', print_r($entry,true));
234 foreach($entry->categories as $cat)
235 array_push($catnames, $cat["term"]);
237 $wp_cats = get_categories(array('hide_empty' => false));
239 $post_category = array();
241 foreach($wp_cats as $cat) {
242 if(in_array($cat->name, $catnames))
243 array_push($post_category, $cat->term_id);
246 $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
248 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
250 if(!current_user_can($cap))
251 $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
253 $blog_ID = (int ) $blog_id;
254 $post_status = ($publish) ? 'publish' : 'draft';
255 $post_author = (int) $user->ID;
256 $post_title = $entry->title[1];
257 $post_content = $entry->content[1];
258 $post_excerpt = $entry->summary[1];
259 $pubtimes = $this->get_publish_time($entry);
260 $post_date = $pubtimes[0];
261 $post_date_gmt = $pubtimes[1];
263 if ( isset( $_SERVER['HTTP_SLUG'] ) )
264 $post_name = $_SERVER['HTTP_SLUG'];
266 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
268 $this->escape($post_data);
269 log_app('Inserting Post. Data:', print_r($post_data,true));
271 $postID = wp_insert_post($post_data);
272 if ( is_wp_error( $postID ) )
273 $this->internal_error($postID->get_error_message());
276 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
279 // getting warning here about unable to set headers
280 // because something in the cache is printing to the buffer
281 // could we clean up wp_set_post_categories or cache to not print
282 // this could affect our ability to send back the right headers
283 @wp_set_post_categories($postID, $post_category);
285 $output = $this->get_entry($postID);
287 log_app('function',"create_post($postID)");
288 $this->created($postID, $output);
291 function get_post($postID) {
294 if( !current_user_can( 'edit_post', $postID ) )
295 $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
297 $this->set_current_entry($postID);
298 $output = $this->get_entry($postID);
299 log_app('function',"get_post($postID)");
300 $this->output($output);
304 function put_post($postID) {
307 // checked for valid content-types (atom+xml)
308 // quick check and exit
309 $this->get_accepted_content_type($this->atom_content_types);
311 $parser = new AtomParser();
312 if(!$parser->parse()) {
313 $this->bad_request();
316 $parsed = array_pop($parser->feed->entries);
318 log_app('Received UPDATED entry:', print_r($parsed,true));
320 // check for not found
322 $entry = $GLOBALS['entry'];
323 $this->set_current_entry($postID);
325 if(!current_user_can('edit_post', $entry['ID']))
326 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
328 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
332 $post_title = $parsed->title[1];
333 $post_content = $parsed->content[1];
334 $post_excerpt = $parsed->summary[1];
335 $pubtimes = $this->get_publish_time($entry);
336 $post_date = $pubtimes[0];
337 $post_date_gmt = $pubtimes[1];
339 // let's not go backwards and make something draft again.
340 if(!$publish && $post_status == 'draft') {
341 $post_status = ($publish) ? 'publish' : 'draft';
343 $post_status = 'publish';
346 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt');
347 $this->escape($postdata);
349 $result = wp_update_post($postdata);
352 $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
355 log_app('function',"put_post($postID)");
359 function delete_post($postID) {
361 // check for not found
363 $this->set_current_entry($postID);
365 if(!current_user_can('edit_post', $postID)) {
366 $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
369 if ($entry['post_type'] == 'attachment') {
370 $this->delete_attachment($postID);
372 $result = wp_delete_post($postID);
375 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
378 log_app('function',"delete_post($postID)");
384 function get_attachment($postID = NULL) {
385 if( !current_user_can( 'upload_files' ) )
386 $this->auth_required( __( 'Sorry, you do not have the right to file uploads on this blog.' ) );
388 if (!isset($postID)) {
389 $this->get_attachments();
391 $this->set_current_entry($postID);
392 $output = $this->get_entry($postID, 'attachment');
393 log_app('function',"get_attachment($postID)");
394 $this->output($output);
398 function create_attachment() {
399 global $wp, $wpdb, $wp_query, $blog_id;
401 $type = $this->get_accepted_content_type();
403 if(!current_user_can('upload_files'))
404 $this->auth_required(__('You do not have permission to upload files.'));
406 $fp = fopen("php://input", "rb");
409 $bits .= fread($fp, 4096);
414 if ( isset( $_SERVER['HTTP_SLUG'] ) )
415 $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] );
416 elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
417 $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] );
418 elseif ( empty( $slug ) ) // just make a random name
419 $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
420 $ext = preg_replace( '|.*/([a-z]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
421 $slug = "$slug.$ext";
422 $file = wp_upload_bits( $slug, NULL, $bits);
424 log_app('wp_upload_bits returns:',print_r($file,true));
427 $file = $file['file'];
428 $filename = basename($file);
430 $header = apply_filters('wp_create_file_in_uploads', $file); // replicate
432 // Construct the attachment array
434 'post_title' => $slug,
435 'post_content' => $slug,
436 'post_status' => 'attachment',
438 'post_mime_type' => $type,
443 $postID = wp_insert_attachment($attachment, $file, $post);
446 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
449 $output = $this->get_entry($postID, 'attachment');
451 $this->created($postID, $output, 'attachment');
452 log_app('function',"create_attachment($postID)");
455 function put_attachment($postID) {
458 // checked for valid content-types (atom+xml)
459 // quick check and exit
460 $this->get_accepted_content_type($this->atom_content_types);
462 $parser = new AtomParser();
463 if(!$parser->parse()) {
464 $this->bad_request();
467 $parsed = array_pop($parser->feed->entries);
469 // check for not found
471 $this->set_current_entry($postID);
473 if(!current_user_can('edit_post', $entry['ID']))
474 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
476 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
480 $post_title = $parsed->title[1];
481 $post_content = $parsed->content[1];
483 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
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 $type = $this->get_accepted_content_type();
562 // first check if user can upload
563 if(!current_user_can('upload_files'))
564 $this->auth_required(__('You do not have permission to upload files.'));
566 // check for not found
568 $this->set_current_entry($postID);
570 // then whether user can edit the specific post
571 if(!current_user_can('edit_post', $postID)) {
572 $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
575 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
576 $filetype = wp_check_filetype($location);
578 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
579 $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
581 $fp = fopen("php://input", "rb");
582 $localfp = fopen($location, "w+");
584 fwrite($localfp,fread($fp, 4096));
590 $pubtimes = $this->get_publish_time($entry);
591 $post_date = $pubtimes[0];
592 $post_date_gmt = $pubtimes[1];
594 $post_data = compact('ID', 'post_date', 'post_date_gmt');
595 $result = wp_update_post($post_data);
598 $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
601 log_app('function',"put_file($postID)");
605 function get_entries_url($page = NULL) {
606 if($GLOBALS['post_type'] == 'attachment') {
607 $path = $this->MEDIA_PATH;
609 $path = $this->ENTRIES_PATH;
611 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $path;
612 if(isset($page) && is_int($page)) {
618 function the_entries_url($page = NULL) {
619 $url = $this->get_entries_url($page);
623 function get_categories_url($page = NULL) {
624 return get_bloginfo('url') . '/' . $this->script_name . '/' . $this->CATEGORIES_PATH;
627 function the_categories_url() {
628 $url = $this->get_categories_url();
632 function get_attachments_url($page = NULL) {
633 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $this->MEDIA_PATH;
634 if(isset($page) && is_int($page)) {
640 function the_attachments_url($page = NULL) {
641 $url = $this->get_attachments_url($page);
645 function get_service_url() {
646 return get_bloginfo('url') . '/' . $this->script_name . '/' . $this->SERVICE_PATH;
649 function get_entry_url($postID = NULL) {
650 if(!isset($postID)) {
652 $postID = (int) $GLOBALS['post']->ID;
655 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $this->ENTRY_PATH . "/$postID";
657 log_app('function',"get_entry_url() = $url");
661 function the_entry_url($postID = NULL) {
662 $url = $this->get_entry_url($postID);
666 function get_media_url($postID = NULL) {
667 if(!isset($postID)) {
669 $postID = (int) $GLOBALS['post']->ID;
672 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $this->MEDIA_SINGLE_PATH ."/file/$postID";
674 log_app('function',"get_media_url() = $url");
678 function the_media_url($postID = NULL) {
679 $url = $this->get_media_url($postID);
683 function set_current_entry($postID) {
685 log_app('function',"set_current_entry($postID)");
687 if(!isset($postID)) {
688 // $this->bad_request();
692 $entry = wp_get_single_post($postID,ARRAY_A);
694 if(!isset($entry) || !isset($entry['ID']))
700 function get_posts($page = 1, $post_type = 'post') {
701 log_app('function',"get_posts($page, '$post_type')");
702 $feed = $this->get_feed($page, $post_type);
703 $this->output($feed);
706 function get_attachments($page = 1, $post_type = 'attachment') {
707 log_app('function',"get_attachments($page, '$post_type')");
708 $GLOBALS['post_type'] = $post_type;
709 $feed = $this->get_feed($page, $post_type);
710 $this->output($feed);
713 function get_feed($page = 1, $post_type = 'post') {
714 global $post, $wp, $wp_query, $posts, $wpdb, $blog_id, $post_cache;
715 log_app('function',"get_feed($page, '$post_type')");
723 $count = get_option('posts_per_rss');
725 wp('what_to_show=posts&posts_per_page=' . $count . '&offset=' . ($count * ($page-1) ));
727 $post = $GLOBALS['post'];
728 $posts = $GLOBALS['posts'];
729 $wp = $GLOBALS['wp'];
730 $wp_query = $GLOBALS['wp_query'];
731 $wpdb = $GLOBALS['wpdb'];
732 $blog_id = (int) $GLOBALS['blog_id'];
733 $post_cache = $GLOBALS['post_cache'];
734 log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)");
736 log_app('function',"total_count(# $wp_query->max_num_pages #)");
737 $last_page = $wp_query->max_num_pages;
738 $next_page = (($page + 1) > $last_page) ? NULL : $page + 1;
739 $prev_page = ($page - 1) < 1 ? NULL : $page - 1;
740 $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page;
741 $self_page = $page > 1 ? $page : NULL;
742 ?><feed xmlns="<?php echo $this->ATOM_NS ?>" xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
743 <id><?php $this->the_entries_url() ?></id>
744 <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT')); ?></updated>
745 <title type="text"><?php bloginfo_rss('name') ?></title>
746 <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle>
747 <link rel="first" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url() ?>" />
748 <?php if(isset($prev_page)): ?>
749 <link rel="previous" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($prev_page) ?>" />
751 <?php if(isset($next_page)): ?>
752 <link rel="next" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($next_page) ?>" />
754 <link rel="last" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($last_page) ?>" />
755 <link rel="self" type="<?php echo $this->ATOM_CONTENT_TYPE ?>" href="<?php $this->the_entries_url($self_page) ?>" />
756 <rights type="text">Copyright <?php echo mysql2date('Y', get_lastpostdate('blog')); ?></rights>
757 <generator uri="http://wordpress.com/" version="1.0.5-dc">WordPress.com Atom API</generator>
758 <?php if ( have_posts() ) {
759 while ( have_posts() ) {
766 $feed = ob_get_contents();
771 function get_entry($postID, $post_type = 'post') {
772 log_app('function',"get_entry($postID, '$post_type')");
774 global $posts, $post, $wp_query, $wp, $wpdb, $blog_id, $post_cache;
780 $varname = 'attachment_id';
783 query_posts($varname . '=' . $postID);
784 if ( have_posts() ) {
785 while ( have_posts() ) {
788 log_app('$post',print_r($GLOBALS['post'],true));
789 $entry = ob_get_contents();
795 log_app('get_entry returning:',$entry);
799 function echo_entry() { ?>
800 <entry xmlns="<?php echo $this->ATOM_NS ?>"
801 xmlns:app="<?php echo $this->ATOMPUB_NS ?>" xml:lang="<?php echo get_option('rss_language'); ?>">
802 <id><?php the_guid($GLOBALS['post']->ID); ?></id>
803 <?php list($content_type, $content) = $this->prep_content(get_the_title()); ?>
804 <title type="<?php echo $content_type ?>"><?php echo $content ?></title>
805 <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated>
806 <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published>
807 <app:edited><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></app:edited>
809 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
812 <name><?php the_author()?></name>
813 <?php if (get_the_author_url() && get_the_author_url() != 'http://') { ?>
814 <uri><?php the_author_url()?></uri>
817 <?php if($GLOBALS['post']->post_type == 'attachment') { ?>
818 <link rel="edit-media" href="<?php $this->the_media_url() ?>" />
819 <content type="<?php echo $GLOBALS['post']->post_mime_type ?>" src="<?php the_guid(); ?>"/>
821 <link href="<?php the_permalink_rss() ?>" />
822 <?php if ( strlen( $GLOBALS['post']->post_content ) ) :
823 list($content_type, $content) = $this->prep_content(get_the_content()); ?>
824 <content type="<?php echo $content_type ?>"><?php echo $content ?></content>
827 <link rel="edit" href="<?php $this->the_entry_url() ?>" />
828 <?php foreach(get_the_category() as $category) { ?>
829 <category scheme="<?php bloginfo_rss('home') ?>" term="<?php echo $category->name?>" />
831 <?php list($content_type, $content) = $this->prep_content(get_the_excerpt()); ?>
832 <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
836 function prep_content($data) {
837 if (strpos($data, '<') === false && strpos($data, '&') === false) {
838 return array('text', $data);
841 $parser = xml_parser_create();
842 xml_parse($parser, '<div>' . $data . '</div>', true);
843 $code = xml_get_error_code($parser);
844 xml_parser_free($parser);
847 if (strpos($data, '<') === false) {
848 return array('text', $data);
850 $data = "<div xmlns='http://www.w3.org/1999/xhtml'>$data</div>";
851 return array('xhtml', $data);
855 if (strpos($data, ']]>') == false) {
856 return array('html', "<![CDATA[$data]]>");
858 return array('html', htmlspecialchars($data));
863 log_app('Status','200: OK');
864 header('Content-Type: text/plain');
865 status_header('200');
869 function no_content() {
870 log_app('Status','204: No Content');
871 header('Content-Type: text/plain');
872 status_header('204');
877 function internal_error($msg = 'Internal Server Error') {
878 log_app('Status','500: Server Error');
879 header('Content-Type: text/plain');
880 status_header('500');
885 function bad_request() {
886 log_app('Status','400: Bad Request');
887 header('Content-Type: text/plain');
888 status_header('400');
892 function length_required() {
893 log_app('Status','411: Length Required');
894 header("HTTP/1.1 411 Length Required");
895 header('Content-Type: text/plain');
896 status_header('411');
900 function invalid_media() {
901 log_app('Status','415: Unsupported Media Type');
902 header("HTTP/1.1 415 Unsupported Media Type");
903 header('Content-Type: text/plain');
907 function not_found() {
908 log_app('Status','404: Not Found');
909 header('Content-Type: text/plain');
910 status_header('404');
914 function not_allowed($allow) {
915 log_app('Status','405: Not Allowed');
916 header('Allow: ' . join(',', $allow));
917 status_header('405');
921 function redirect($url) {
923 log_app('Status','302: Redirect');
924 $escaped_url = attribute_escape($url);
926 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
929 <title>302 Found</title>
933 <p>The document has moved <a href="$escaped_url">here</a>.</p>
938 header('HTTP/1.1 302 Moved');
939 header('Content-Type: text/html');
940 header('Location: ' . $url);
947 function client_error($msg = 'Client Error') {
948 log_app('Status','400: Client Error');
949 header('Content-Type: text/plain');
950 status_header('400');
954 function created($post_ID, $content, $post_type = 'post') {
955 log_app('created()::$post_ID',"$post_ID, $post_type");
956 $edit = $this->get_entry_url($post_ID);
959 $ctloc = $this->get_entry_url($post_ID);
962 $edit = get_bloginfo('url') . '/' . $this->script_name . "/attachments/$post_ID";
965 header("Content-Type: $this->ATOM_CONTENT_TYPE");
967 header('Content-Location: ' . $ctloc);
968 header('Location: ' . $edit);
969 status_header('201');
974 function auth_required($msg) {
975 log_app('Status','401: Auth Required');
977 header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"');
978 header("HTTP/1.1 401 $msg");
979 header('Status: ' . $msg);
980 header('Content-Type: text/html');
982 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
985 <title>401 Unauthorized</title>
988 <h1>401 Unauthorized</h1>
998 function output($xml, $ctype = 'application/atom+xml') {
999 status_header('200');
1000 $xml = '<?xml version="1.0" encoding="' . strtolower(get_option('blog_charset')) . '"?>'."\n".$xml;
1001 header('Connection: close');
1002 header('Content-Length: '. strlen($xml));
1003 header('Content-Type: ' . $ctype);
1004 header('Content-Disposition: attachment; filename=atom.xml');
1005 header('Date: '. date('r'));
1006 if($this->do_output)
1008 log_app('function', "output:\n$xml");
1012 function escape(&$array) {
1015 foreach ($array as $k => $v) {
1017 $this->escape($array[$k]);
1018 } else if (is_object($v)) {
1021 $array[$k] = $wpdb->escape($v);
1027 * Access credential through various methods and perform login
1029 function authenticate() {
1030 $login_data = array();
1031 $already_md5 = false;
1033 log_app("authenticate()",print_r($_ENV, true));
1035 // if using mod_rewrite/ENV hack
1036 // http://www.besthostratings.com/articles/http-auth-php-cgi.html
1037 if(isset($_SERVER['HTTP_AUTHORIZATION'])) {
1038 list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
1039 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
1042 // If Basic Auth is working...
1043 if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
1044 $login_data = array('login' => $_SERVER['PHP_AUTH_USER'], 'password' => $_SERVER['PHP_AUTH_PW']);
1045 log_app("Basic Auth",$login_data['login']);
1047 // else, do cookie-based authentication
1048 if (function_exists('wp_get_cookie_login')) {
1049 $login_data = wp_get_cookie_login();
1050 $already_md5 = true;
1054 // call wp_login and set current user
1055 if (!empty($login_data) && wp_login($login_data['login'], $login_data['password'], $already_md5)) {
1056 $current_user = new WP_User(0, $login_data['login']);
1057 wp_set_current_user($current_user->ID);
1058 log_app("authenticate()",$login_data['login']);
1062 function get_accepted_content_type($types = NULL) {
1064 if(!isset($types)) {
1065 $types = $this->media_content_types;
1068 if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1069 $this->length_required();
1072 $type = $_SERVER['CONTENT_TYPE'];
1073 list($type,$subtype) = explode('/',$type);
1074 list($subtype) = explode(";",$subtype); // strip MIME parameters
1075 log_app("get_accepted_content_type", "type=$type, subtype=$subtype");
1077 foreach($types as $t) {
1078 list($acceptedType,$acceptedSubtype) = explode('/',$t);
1079 if($acceptedType == '*' || $acceptedType == $type) {
1080 if($acceptedSubtype == '*' || $acceptedSubtype == $subtype)
1081 return $type . "/" . $subtype;
1085 $this->invalid_media();
1088 function process_conditionals() {
1090 if(empty($this->params)) return;
1091 if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1093 switch($this->params[0]) {
1094 case $this->ENTRY_PATH:
1096 $post = wp_get_single_post($this->params[1]);
1097 $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true);
1100 case $this->ENTRIES_PATH:
1101 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1106 $wp_etag = md5($wp_last_modified);
1107 @header("Last-Modified: $wp_last_modified");
1108 @header("ETag: $wp_etag");
1110 // Support for Conditional GET
1111 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1112 $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1114 $client_etag = false;
1116 $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']);
1117 // If string is empty, return 0. If not, attempt to parse into a timestamp
1118 $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
1120 // Make a timestamp for our most recent modification...
1121 $wp_modified_timestamp = strtotime($wp_last_modified);
1123 if ( ($client_last_modified && $client_etag) ?
1124 (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
1125 (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
1126 status_header( 304 );
1131 function rfc3339_str2time($str) {
1134 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))
1137 if($match[3] == 'Z')
1138 $match[3] == '+0000';
1140 return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1143 function get_publish_time($entry) {
1145 $pubtime = $this->rfc3339_str2time($entry->published);
1148 return array(current_time('mysql'),current_time('mysql',1));
1150 return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1156 $server = new AtomServer();
1157 $server->handle_request();