Wordpress 2.3.2-scripts
[autoinstalls/wordpress.git] / wp-app.php
1 <?php
2 /*
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/
6  *
7  * Version: 1.0.5-dc
8  */
9
10 define('APP_REQUEST', true);
11
12 require_once('./wp-config.php');
13 require_once(ABSPATH . WPINC . '/post-template.php');
14 require_once(ABSPATH . WPINC . '/atomlib.php');
15
16 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
17
18 $app_logging = 0;
19
20 // TODO: Should be an option somewhere
21 $always_authenticate = 1;
22
23 function log_app($label,$msg) {
24         global $app_logging;
25         if ($app_logging) {
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");
29                 fclose($fp);
30         }
31 }
32
33 if ( !function_exists('wp_set_current_user') ) :
34 function wp_set_current_user($id, $name = '') {
35         global $current_user;
36
37         if ( isset($current_user) && ($id == $current_user->ID) )
38                 return $current_user;
39
40         $current_user = new WP_User($id, $name);
41
42         return $current_user;
43 }
44 endif;
45
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);
48         return $where;
49
50 }
51 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
52
53 class AtomServer {
54
55         var $ATOM_CONTENT_TYPE = 'application/atom+xml';
56         var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
57         var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
58
59         var $ATOM_NS = 'http://www.w3.org/2005/Atom';
60         var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
61
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";
68
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');
73
74         var $selectors = array();
75
76         // support for head
77         var $do_output = true;
78
79         function AtomServer() {
80
81                 $this->script_name = array_pop(explode('/',$_SERVER['SCRIPT_NAME']));
82
83                 $this->selectors = array(
84                         '@/service$@' =>
85                                 array('GET' => 'get_service'),
86                         '@/categories$@' =>
87                                 array('GET' => 'get_categories_xml'),
88                         '@/post/(\d+)$@' =>
89                                 array('GET' => 'get_post',
90                                                 'PUT' => 'put_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',
100                                                 'PUT' => 'put_file',
101                                                 'DELETE' => 'delete_file'),
102                         '@/attachment/(\d+)$@' =>
103                                 array('GET' => 'get_attachment',
104                                                 'PUT' => 'put_attachment',
105                                                 'DELETE' => 'delete_attachment'),
106                 );
107         }
108
109         function handle_request() {
110                 global $always_authenticate;
111
112                 $path = $_SERVER['PATH_INFO'];
113                 $method = $_SERVER['REQUEST_METHOD'];
114
115                 log_app('REQUEST',"$method $path\n================");
116
117                 $this->process_conditionals();
118                 //$this->process_conditionals();
119
120                 // exception case for HEAD (treat exactly as GET, but don't output)
121                 if($method == 'HEAD') {
122                         $this->do_output = false;
123                         $method = 'GET';
124                 }
125
126                 // redirect to /service in case no path is found.
127                 if(strlen($path) == 0 || $path == '/') {
128                         $this->redirect($this->get_service_url());
129                 }
130
131                 // dispatch
132                 foreach($this->selectors as $regex => $funcs) {
133                         if(preg_match($regex, $path, $matches)) {
134                         if(isset($funcs[$method])) {
135
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.');
143                                         }
144                                 }
145
146                                 array_shift($matches);
147                                 call_user_func_array(array(&$this,$funcs[$method]), $matches);
148                                 exit();
149                         } else {
150                                 // only allow what we have handlers for...
151                                 $this->not_allowed(array_keys($funcs));
152                         }
153                         }
154                 }
155
156                 // oops, nothing found
157                 $this->not_found();
158         }
159
160         function get_service() {
161                 log_app('function','get_service()');
162
163                 if( !current_user_can( 'edit_posts' ) ) 
164                         $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
165
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>";
171                 }
172                 $atom_prefix="atom";
173                 $service_doc = <<<EOD
174 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
175   <workspace>
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" />
181     </collection>
182     <collection href="$media_url">
183       <$atom_prefix:title>WordPress Media</$atom_prefix:title>
184       $accepted_media_types
185     </collection>
186   </workspace>
187 </service>
188
189 EOD;
190
191                 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
192         }
193
194         function get_categories_xml() {
195                 log_app('function','get_categories_xml()');
196
197                 if( !current_user_can( 'edit_posts' ) ) 
198                         $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
199
200                 $home = attribute_escape(get_bloginfo_rss('home'));
201
202                 $categories = "";
203                 $cats = get_categories("hierarchical=0&hide_empty=0");
204                 foreach ((array) $cats as $cat) {
205                         $categories .= "    <category term=\"" . attribute_escape($cat->name) .  "\" />\n";
206 }
207                 $output = <<<EOD
208 <app:categories xmlns:app="$this->ATOMPUB_NS"
209         xmlns="$this->ATOM_NS"
210         fixed="yes" scheme="$home">
211         $categories
212 </app:categories>
213 EOD;
214         $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
215 }
216
217         /*
218          * Create Post (No arguments)
219          */
220         function create_post() {
221                 global $blog_id, $wpdb;
222                 $this->get_accepted_content_type($this->atom_content_types);
223
224                 $parser = new AtomParser();
225                 if(!$parser->parse()) {
226                         $this->client_error();
227                 }
228
229                 $entry = array_pop($parser->feed->entries);
230
231                 log_app('Received entry:', print_r($entry,true));
232
233                 $catnames = array();
234                 foreach($entry->categories as $cat)
235                         array_push($catnames, $cat["term"]);
236
237                 $wp_cats = get_categories(array('hide_empty' => false));
238
239                 $post_category = array();
240
241                 foreach($wp_cats as $cat) {
242                         if(in_array($cat->name, $catnames))
243                                 array_push($post_category, $cat->term_id);
244                 }
245
246                 $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
247
248                 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
249
250                 if(!current_user_can($cap))
251                         $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
252
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];
262
263                 if ( isset( $_SERVER['HTTP_SLUG'] ) )
264                         $post_name = $_SERVER['HTTP_SLUG'];
265
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');
267
268                 $this->escape($post_data);
269                 log_app('Inserting Post. Data:', print_r($post_data,true));
270
271                 $postID = wp_insert_post($post_data);
272                 if ( is_wp_error( $postID ) )
273                         $this->internal_error($postID->get_error_message());
274
275                 if (!$postID) {
276                         $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
277                 }
278
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);
284
285                 $output = $this->get_entry($postID);
286
287                 log_app('function',"create_post($postID)");
288                 $this->created($postID, $output);
289         }
290
291         function get_post($postID) {
292                 global $entry;
293
294                 if( !current_user_can( 'edit_post', $postID ) )
295                         $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) ); 
296
297                 $this->set_current_entry($postID);
298                 $output = $this->get_entry($postID);
299                 log_app('function',"get_post($postID)");
300                 $this->output($output);
301
302         }
303
304         function put_post($postID) {
305                 global $wpdb;
306
307                 // checked for valid content-types (atom+xml)
308                 // quick check and exit
309                 $this->get_accepted_content_type($this->atom_content_types);
310
311                 $parser = new AtomParser();
312                 if(!$parser->parse()) {
313                         $this->bad_request();
314                 }
315
316                 $parsed = array_pop($parser->feed->entries);
317
318                 log_app('Received UPDATED entry:', print_r($parsed,true));
319
320                 // check for not found
321                 global $entry;
322                 $entry = $GLOBALS['entry'];
323                 $this->set_current_entry($postID);
324
325                 if(!current_user_can('edit_post', $entry['ID']))
326                         $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
327
328                 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
329
330                 extract($entry);
331
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];
338
339                 // let's not go backwards and make something draft again.
340                 if(!$publish && $post_status == 'draft') {
341                         $post_status = ($publish) ? 'publish' : 'draft';
342                 } elseif($publish) {
343                         $post_status = 'publish';
344                 }
345
346                 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt');
347                 $this->escape($postdata);
348
349                 $result = wp_update_post($postdata);
350
351                 if (!$result) {
352                         $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
353                 }
354
355                 log_app('function',"put_post($postID)");
356                 $this->ok();
357         }
358
359         function delete_post($postID) {
360
361                 // check for not found
362                 global $entry;
363                 $this->set_current_entry($postID);
364
365                 if(!current_user_can('edit_post', $postID)) {
366                         $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
367                 }
368
369                 if ($entry['post_type'] == 'attachment') {
370                         $this->delete_attachment($postID);
371                 } else {
372                         $result = wp_delete_post($postID);
373
374                         if (!$result) {
375                                 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
376                         }
377
378                         log_app('function',"delete_post($postID)");
379                         $this->ok();
380                 }
381
382         }
383
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.' ) );
387
388                 if (!isset($postID)) {
389                         $this->get_attachments();
390                 } else {
391                         $this->set_current_entry($postID);
392                         $output = $this->get_entry($postID, 'attachment');
393                         log_app('function',"get_attachment($postID)");
394                         $this->output($output);
395                 }
396         }
397
398         function create_attachment() {
399                 global $wp, $wpdb, $wp_query, $blog_id;
400
401                 $type = $this->get_accepted_content_type();
402
403                 if(!current_user_can('upload_files'))
404                         $this->auth_required(__('You do not have permission to upload files.'));
405
406                 $fp = fopen("php://input", "rb");
407                 $bits = NULL;
408                 while(!feof($fp)) {
409                         $bits .= fread($fp, 4096);
410                 }
411                 fclose($fp);
412
413                 $slug = '';
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);
423
424                 log_app('wp_upload_bits returns:',print_r($file,true));
425
426                 $url = $file['url'];
427                 $file = $file['file'];
428                 $filename = basename($file);
429
430                 $header = apply_filters('wp_create_file_in_uploads', $file); // replicate
431
432                 // Construct the attachment array
433                 $attachment = array(
434                         'post_title' => $slug,
435                         'post_content' => $slug,
436                         'post_status' => 'attachment',
437                         'post_parent' => 0,
438                         'post_mime_type' => $type,
439                         'guid' => $url
440                         );
441
442                 // Save the data
443                 $postID = wp_insert_attachment($attachment, $file, $post);
444
445                 if (!$postID) {
446                         $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
447                 }
448
449                 $output = $this->get_entry($postID, 'attachment');
450
451                 $this->created($postID, $output, 'attachment');
452                 log_app('function',"create_attachment($postID)");
453         }
454
455         function put_attachment($postID) {
456                 global $wpdb;
457
458                 // checked for valid content-types (atom+xml)
459                 // quick check and exit
460                 $this->get_accepted_content_type($this->atom_content_types);
461
462                 $parser = new AtomParser();
463                 if(!$parser->parse()) {
464                         $this->bad_request();
465                 }
466
467                 $parsed = array_pop($parser->feed->entries);
468
469                 // check for not found
470                 global $entry;
471                 $this->set_current_entry($postID);
472
473                 if(!current_user_can('edit_post', $entry['ID']))
474                         $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
475
476                 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
477
478                 extract($entry);
479
480                 $post_title = $parsed->title[1];
481                 $post_content = $parsed->content[1];
482
483                 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
484                 $this->escape($postdata);
485
486                 $result = wp_update_post($postdata);
487
488                 if (!$result) {
489                         $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
490                 }
491
492                 log_app('function',"put_attachment($postID)");
493                 $this->ok();
494         }
495
496         function delete_attachment($postID) {
497                 log_app('function',"delete_attachment($postID). File '$location' deleted.");
498
499                 // check for not found
500                 global $entry;
501                 $this->set_current_entry($postID);
502
503                 if(!current_user_can('edit_post', $postID)) {
504                         $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
505                 }
506
507                 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
508                 $filetype = wp_check_filetype($location);
509
510                 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
511                         $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
512
513                 // delete file
514                 @unlink($location);
515
516                 // delete attachment
517                 $result = wp_delete_post($postID);
518
519                 if (!$result) {
520                         $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
521                 }
522
523                 log_app('function',"delete_attachment($postID). File '$location' deleted.");
524                 $this->ok();
525         }
526
527         function get_file($postID) {
528
529                 // check for not found
530                 global $entry;
531                 $this->set_current_entry($postID);
532
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.'));
536                 }
537
538                 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
539                 $filetype = wp_check_filetype($location);
540
541                 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
542                         $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
543
544                 status_header('200');
545                 header('Content-Type: ' . $entry['post_mime_type']);
546                 header('Connection: close');
547
548                 $fp = fopen($location, "rb");
549                 while(!feof($fp)) {
550                         echo fread($fp, 4096);
551                 }
552                 fclose($fp);
553
554                 log_app('function',"get_file($postID)");
555                 exit;
556         }
557
558         function put_file($postID) {
559
560                 $type = $this->get_accepted_content_type();
561
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.'));
565
566                 // check for not found
567                 global $entry;
568                 $this->set_current_entry($postID);
569
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.'));
573                 }
574
575                 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
576                 $filetype = wp_check_filetype($location);
577
578                 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
579                         $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
580
581                 $fp = fopen("php://input", "rb");
582                 $localfp = fopen($location, "w+");
583                 while(!feof($fp)) {
584                         fwrite($localfp,fread($fp, 4096));
585                 }
586                 fclose($fp);
587                 fclose($localfp);
588
589                 $ID = $entry['ID'];
590                 $pubtimes = $this->get_publish_time($entry);
591                 $post_date = $pubtimes[0];
592                 $post_date_gmt = $pubtimes[1];
593
594                 $post_data = compact('ID', 'post_date', 'post_date_gmt');
595                 $result = wp_update_post($post_data);
596
597                 if (!$result) {
598                         $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
599                 }
600
601                 log_app('function',"put_file($postID)");
602                 $this->ok();
603         }
604
605         function get_entries_url($page = NULL) {
606                 if($GLOBALS['post_type'] == 'attachment') {
607                         $path = $this->MEDIA_PATH;
608                 } else {
609                         $path = $this->ENTRIES_PATH;
610                 }
611                 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $path;
612                 if(isset($page) && is_int($page)) {
613                         $url .= "/$page";
614                 }
615                 return $url;
616         }
617
618         function the_entries_url($page = NULL) {
619                 $url = $this->get_entries_url($page);
620                 echo $url;
621         }
622
623         function get_categories_url($page = NULL) {
624                 return get_bloginfo('url') . '/' . $this->script_name . '/' . $this->CATEGORIES_PATH;
625         }
626
627         function the_categories_url() {
628                 $url = $this->get_categories_url();
629                 echo $url;
630         }
631
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)) {
635                         $url .= "/$page";
636                 }
637                 return $url;
638         }
639
640         function the_attachments_url($page = NULL) {
641                 $url = $this->get_attachments_url($page);
642                 echo $url;
643         }
644
645         function get_service_url() {
646                 return get_bloginfo('url') . '/' . $this->script_name . '/' . $this->SERVICE_PATH;
647         }
648
649         function get_entry_url($postID = NULL) {
650                 if(!isset($postID)) {
651                         global $post;
652                         $postID = (int) $GLOBALS['post']->ID;
653                 }
654
655                 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $this->ENTRY_PATH . "/$postID";
656
657                 log_app('function',"get_entry_url() = $url");
658                 return $url;
659         }
660
661         function the_entry_url($postID = NULL) {
662                 $url = $this->get_entry_url($postID);
663                 echo $url;
664         }
665
666         function get_media_url($postID = NULL) {
667                 if(!isset($postID)) {
668                         global $post;
669                         $postID = (int) $GLOBALS['post']->ID;
670                 }
671
672                 $url = get_bloginfo('url') . '/' . $this->script_name . '/' . $this->MEDIA_SINGLE_PATH ."/file/$postID";
673
674                 log_app('function',"get_media_url() = $url");
675                 return $url;
676         }
677
678         function the_media_url($postID = NULL) {
679                 $url = $this->get_media_url($postID);
680                 echo $url;
681         }
682
683         function set_current_entry($postID) {
684                 global $entry;
685                 log_app('function',"set_current_entry($postID)");
686
687                 if(!isset($postID)) {
688                         // $this->bad_request();
689                         $this->not_found();
690                 }
691
692                 $entry = wp_get_single_post($postID,ARRAY_A);
693
694                 if(!isset($entry) || !isset($entry['ID']))
695                         $this->not_found();
696
697                 return;
698         }
699
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);
704         }
705
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);
711         }
712
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')");
716                 ob_start();
717
718                 if(!isset($page)) {
719                         $page = 1;
720                 }
721                 $page = (int) $page;
722
723                 $count = get_option('posts_per_rss');
724
725                 wp('what_to_show=posts&posts_per_page=' . $count . '&offset=' . ($count * ($page-1) ));
726
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) . "#)");
735
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) ?>" />
750 <?php endif; ?>
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) ?>" />
753 <?php endif; ?>
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() ) {
760                                 the_post();
761                                 $this->echo_entry();
762                         }
763                 }
764 ?></feed>
765 <?php
766                 $feed = ob_get_contents();
767                 ob_end_clean();
768                 return $feed;
769         }
770
771         function get_entry($postID, $post_type = 'post') {
772                 log_app('function',"get_entry($postID, '$post_type')");
773                 ob_start();
774                 global $posts, $post, $wp_query, $wp, $wpdb, $blog_id, $post_cache;
775                 switch($post_type) {
776                         case 'post':
777                                 $varname = 'p';
778                                 break;
779                         case 'attachment':
780                                 $varname = 'attachment_id';
781                                 break;
782                 }
783                 query_posts($varname . '=' . $postID);
784                 if ( have_posts() ) {
785                         while ( have_posts() ) {
786                                 the_post();
787                                 $this->echo_entry();
788                                 log_app('$post',print_r($GLOBALS['post'],true));
789                                 $entry = ob_get_contents();
790                                 break;
791                         }
792                 }
793                 ob_end_clean();
794
795                 log_app('get_entry returning:',$entry);
796                 return $entry;
797         }
798
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>
808         <app:control>
809                 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
810         </app:control>
811         <author>
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>
815 <?php } ?>
816         </author>
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(); ?>"/>
820 <?php } else { ?>
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>
825 <?php endif; ?>
826 <?php } ?>
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?>" />
830 <?php } ?>
831 <?php list($content_type, $content) = $this->prep_content(get_the_excerpt()); ?>
832         <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
833 </entry>
834 <?php }
835
836         function prep_content($data) {
837                 if (strpos($data, '<') === false && strpos($data, '&') === false) {
838                         return array('text', $data);
839                 }
840
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);
845
846                 if (!$code) {
847                         if (strpos($data, '<') === false) {
848                                 return array('text', $data);
849                         } else {
850                                 $data = "<div xmlns='http://www.w3.org/1999/xhtml'>$data</div>";
851                                 return array('xhtml', $data);
852                         }
853                 }
854
855                 if (strpos($data, ']]>') == false) {
856                         return array('html', "<![CDATA[$data]]>");
857                 } else {
858                         return array('html', htmlspecialchars($data));
859                 }
860         }
861
862         function ok() {
863                 log_app('Status','200: OK');
864                 header('Content-Type: text/plain');
865                 status_header('200');
866                 exit;
867         }
868
869         function no_content() {
870                 log_app('Status','204: No Content');
871                 header('Content-Type: text/plain');
872                 status_header('204');
873                 echo "Deleted.";
874                 exit;
875         }
876
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');
881                 echo $msg;
882                 exit;
883         }
884
885         function bad_request() {
886                 log_app('Status','400: Bad Request');
887                 header('Content-Type: text/plain');
888                 status_header('400');
889                 exit;
890         }
891
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');
897                 exit;
898         }
899
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');
904                 exit;
905         }
906
907         function not_found() {
908                 log_app('Status','404: Not Found');
909                 header('Content-Type: text/plain');
910                 status_header('404');
911                 exit;
912         }
913
914         function not_allowed($allow) {
915                 log_app('Status','405: Not Allowed');
916                 header('Allow: ' . join(',', $allow));
917                 status_header('405');
918                 exit;
919         }
920
921         function redirect($url) {
922
923                 log_app('Status','302: Redirect');
924                 $escaped_url = attribute_escape($url);
925                 $content = <<<EOD
926 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
927 <html>
928   <head>
929     <title>302 Found</title>
930   </head>
931 <body>
932   <h1>Found</h1>
933   <p>The document has moved <a href="$escaped_url">here</a>.</p>
934   </body>
935 </html>
936
937 EOD;
938                 header('HTTP/1.1 302 Moved');
939                 header('Content-Type: text/html');
940                 header('Location: ' . $url);
941                 echo $content;
942                 exit;
943
944         }
945
946
947         function client_error($msg = 'Client Error') {
948                 log_app('Status','400: Client Error');
949                 header('Content-Type: text/plain');
950                 status_header('400');
951                 exit;
952         }
953
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);
957                 switch($post_type) {
958                         case 'post':
959                                 $ctloc = $this->get_entry_url($post_ID);
960                                 break;
961                         case 'attachment':
962                                 $edit = get_bloginfo('url') . '/' . $this->script_name . "/attachments/$post_ID";
963                                 break;
964                 }
965                 header("Content-Type: $this->ATOM_CONTENT_TYPE");
966                 if(isset($ctloc))
967                         header('Content-Location: ' . $ctloc);
968                 header('Location: ' . $edit);
969                 status_header('201');
970                 echo $content;
971                 exit;
972         }
973
974         function auth_required($msg) {
975                 log_app('Status','401: Auth Required');
976                 nocache_headers();
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');
981                 $content = <<<EOD
982 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
983 <html>
984   <head>
985     <title>401 Unauthorized</title>
986   </head>
987 <body>
988     <h1>401 Unauthorized</h1>
989     <p>$msg</p>
990   </body>
991 </html>
992
993 EOD;
994                 echo $content;
995                 exit;
996         }
997
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)
1007                                 echo $xml;
1008                         log_app('function', "output:\n$xml");
1009                         exit;
1010         }
1011
1012         function escape(&$array) {
1013                 global $wpdb;
1014
1015                 foreach ($array as $k => $v) {
1016                                 if (is_array($v)) {
1017                                                 $this->escape($array[$k]);
1018                                 } else if (is_object($v)) {
1019                                                 //skip
1020                                 } else {
1021                                                 $array[$k] = $wpdb->escape($v);
1022                                 }
1023                 }
1024         }
1025
1026         /*
1027          * Access credential through various methods and perform login
1028          */
1029         function authenticate() {
1030                 $login_data = array();
1031                 $already_md5 = false;
1032
1033                 log_app("authenticate()",print_r($_ENV, true));
1034
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)));
1040                 }
1041
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']);
1046                 } else {
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;
1051                         }
1052                 }
1053
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']);
1059                 }
1060         }
1061
1062         function get_accepted_content_type($types = NULL) {
1063
1064                 if(!isset($types)) {
1065                         $types = $this->media_content_types;
1066                 }
1067
1068                 if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1069                         $this->length_required();
1070                 }
1071
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");
1076
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;
1082                         }
1083                 }
1084
1085                 $this->invalid_media();
1086         }
1087
1088         function process_conditionals() {
1089
1090                 if(empty($this->params)) return;
1091                 if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1092
1093                 switch($this->params[0]) {
1094                         case $this->ENTRY_PATH:
1095                                 global $post;
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);
1098                                 $post = NULL;
1099                                 break;
1100                         case $this->ENTRIES_PATH:
1101                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1102                                 break;
1103                         default:
1104                                 return;
1105                 }
1106                 $wp_etag = md5($wp_last_modified);
1107                 @header("Last-Modified: $wp_last_modified");
1108                 @header("ETag: $wp_etag");
1109
1110                 // Support for Conditional GET
1111                 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1112                         $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1113                 else
1114                         $client_etag = false;
1115
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;
1119
1120                 // Make a timestamp for our most recent modification...
1121                 $wp_modified_timestamp = strtotime($wp_last_modified);
1122
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 );
1127                         exit;
1128                 }
1129         }
1130
1131         function rfc3339_str2time($str) {
1132
1133             $match = false;
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))
1135                         return false;
1136
1137             if($match[3] == 'Z')
1138                         $match[3] == '+0000';
1139
1140             return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1141         }
1142
1143         function get_publish_time($entry) {
1144
1145             $pubtime = $this->rfc3339_str2time($entry->published);
1146
1147             if(!$pubtime) {
1148                         return array(current_time('mysql'),current_time('mysql',1));
1149             } else {
1150                         return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1151             }
1152         }
1153
1154 }
1155
1156 $server = new AtomServer();
1157 $server->handle_request();
1158
1159 ?>