]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-app.php
Wordpress 2.5.1-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 require_once(ABSPATH . WPINC . '/feed.php');
16
17 $_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] );
18
19 $app_logging = 0;
20
21 // TODO: Should be an option somewhere
22 $always_authenticate = 1;
23
24 function log_app($label,$msg) {
25         global $app_logging;
26         if ($app_logging) {
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");
30                 fclose($fp);
31         }
32 }
33
34 if ( !function_exists('wp_set_current_user') ) :
35 function wp_set_current_user($id, $name = '') {
36         global $current_user;
37
38         if ( isset($current_user) && ($id == $current_user->ID) )
39                 return $current_user;
40
41         $current_user = new WP_User($id, $name);
42
43         return $current_user;
44 }
45 endif;
46
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);
49         return $where;
50
51 }
52 add_filter('posts_where', 'wa_posts_where_include_drafts_filter');
53
54 class AtomServer {
55
56         var $ATOM_CONTENT_TYPE = 'application/atom+xml';
57         var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml';
58         var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml';
59
60         var $ATOM_NS = 'http://www.w3.org/2005/Atom';
61         var $ATOMPUB_NS = 'http://www.w3.org/2007/app';
62
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";
69
70         var $params = array();
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                 $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 );
85                 }
86
87                 $this->selectors = array(
88                         '@/service$@' =>
89                                 array('GET' => 'get_service'),
90                         '@/categories$@' =>
91                                 array('GET' => 'get_categories_xml'),
92                         '@/post/(\d+)$@' =>
93                                 array('GET' => 'get_post',
94                                                 'PUT' => 'put_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',
104                                                 'PUT' => 'put_file',
105                                                 'DELETE' => 'delete_file'),
106                         '@/attachment/(\d+)$@' =>
107                                 array('GET' => 'get_attachment',
108                                                 'PUT' => 'put_attachment',
109                                                 'DELETE' => 'delete_attachment'),
110                 );
111         }
112
113         function handle_request() {
114                 global $always_authenticate;
115
116                 $path = $_SERVER['PATH_INFO'];
117                 $method = $_SERVER['REQUEST_METHOD'];
118
119                 log_app('REQUEST',"$method $path\n================");
120
121                 $this->process_conditionals();
122                 //$this->process_conditionals();
123
124                 // exception case for HEAD (treat exactly as GET, but don't output)
125                 if($method == 'HEAD') {
126                         $this->do_output = false;
127                         $method = 'GET';
128                 }
129
130                 // redirect to /service in case no path is found.
131                 if(strlen($path) == 0 || $path == '/') {
132                         $this->redirect($this->get_service_url());
133                 }
134
135                 // dispatch
136                 foreach($this->selectors as $regex => $funcs) {
137                         if(preg_match($regex, $path, $matches)) {
138                         if(isset($funcs[$method])) {
139
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.');
147                                         }
148                                 }
149
150                                 array_shift($matches);
151                                 call_user_func_array(array(&$this,$funcs[$method]), $matches);
152                                 exit();
153                         } else {
154                                 // only allow what we have handlers for...
155                                 $this->not_allowed(array_keys($funcs));
156                         }
157                         }
158                 }
159
160                 // oops, nothing found
161                 $this->not_found();
162         }
163
164         function get_service() {
165                 log_app('function','get_service()');
166
167                 if( !current_user_can( 'edit_posts' ) )
168                         $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
169
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>";
175                 }
176                 $atom_prefix="atom";
177                 $atom_blogname=get_bloginfo('name');
178                 $service_doc = <<<EOD
179 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
180   <workspace>
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" />
186     </collection>
187     <collection href="$media_url">
188       <$atom_prefix:title>$atom_blogname Media</$atom_prefix:title>
189       $accepted_media_types
190     </collection>
191   </workspace>
192 </service>
193
194 EOD;
195
196                 $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
197         }
198
199         function get_categories_xml() {
200                 log_app('function','get_categories_xml()');
201
202                 if( !current_user_can( 'edit_posts' ) )
203                         $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) );
204
205                 $home = attribute_escape(get_bloginfo_rss('home'));
206
207                 $categories = "";
208                 $cats = get_categories("hierarchical=0&hide_empty=0");
209                 foreach ((array) $cats as $cat) {
210                         $categories .= "    <category term=\"" . attribute_escape($cat->name) .  "\" />\n";
211 }
212                 $output = <<<EOD
213 <app:categories xmlns:app="$this->ATOMPUB_NS"
214         xmlns="$this->ATOM_NS"
215         fixed="yes" scheme="$home">
216         $categories
217 </app:categories>
218 EOD;
219         $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
220 }
221
222         /*
223          * Create Post (No arguments)
224          */
225         function create_post() {
226                 global $blog_id, $user_ID;
227                 $this->get_accepted_content_type($this->atom_content_types);
228
229                 $parser = new AtomParser();
230                 if(!$parser->parse()) {
231                         $this->client_error();
232                 }
233
234                 $entry = array_pop($parser->feed->entries);
235
236                 log_app('Received entry:', print_r($entry,true));
237
238                 $catnames = array();
239                 foreach($entry->categories as $cat)
240                         array_push($catnames, $cat["term"]);
241
242                 $wp_cats = get_categories(array('hide_empty' => false));
243
244                 $post_category = array();
245
246                 foreach($wp_cats as $cat) {
247                         if(in_array($cat->name, $catnames))
248                                 array_push($post_category, $cat->term_id);
249                 }
250
251                 $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
252
253                 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
254
255                 if(!current_user_can($cap))
256                         $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
257
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];
267
268                 if ( isset( $_SERVER['HTTP_SLUG'] ) )
269                         $post_name = $_SERVER['HTTP_SLUG'];
270
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');
272
273                 $this->escape($post_data);
274                 log_app('Inserting Post. Data:', print_r($post_data,true));
275
276                 $postID = wp_insert_post($post_data);
277                 if ( is_wp_error( $postID ) )
278                         $this->internal_error($postID->get_error_message());
279
280                 if (!$postID)
281                         $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
282
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);
288
289                 $output = $this->get_entry($postID);
290
291                 log_app('function',"create_post($postID)");
292                 $this->created($postID, $output);
293         }
294
295         function get_post($postID) {
296                 global $entry;
297
298                 if( !current_user_can( 'edit_post', $postID ) )
299                         $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) );
300
301                 $this->set_current_entry($postID);
302                 $output = $this->get_entry($postID);
303                 log_app('function',"get_post($postID)");
304                 $this->output($output);
305
306         }
307
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);
312
313                 $parser = new AtomParser();
314                 if(!$parser->parse()) {
315                         $this->bad_request();
316                 }
317
318                 $parsed = array_pop($parser->feed->entries);
319
320                 log_app('Received UPDATED entry:', print_r($parsed,true));
321
322                 // check for not found
323                 global $entry;
324                 $this->set_current_entry($postID);
325
326                 if(!current_user_can('edit_post', $entry['ID']))
327                         $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
328
329                 $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
330
331                 extract($entry);
332
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];
342
343                 // let's not go backwards and make something draft again.
344                 if(!$publish && $post_status == 'draft') {
345                         $post_status = ($publish) ? 'publish' : 'draft';
346                 } elseif($publish) {
347                         $post_status = 'publish';
348                 }
349
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);
352
353                 $result = wp_update_post($postdata);
354
355                 if (!$result) {
356                         $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
357                 }
358
359                 log_app('function',"put_post($postID)");
360                 $this->ok();
361         }
362
363         function delete_post($postID) {
364
365                 // check for not found
366                 global $entry;
367                 $this->set_current_entry($postID);
368
369                 if(!current_user_can('edit_post', $postID)) {
370                         $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
371                 }
372
373                 if ($entry['post_type'] == 'attachment') {
374                         $this->delete_attachment($postID);
375                 } else {
376                         $result = wp_delete_post($postID);
377
378                         if (!$result) {
379                                 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
380                         }
381
382                         log_app('function',"delete_post($postID)");
383                         $this->ok();
384                 }
385
386         }
387
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.' ) );
391
392                 if (!isset($postID)) {
393                         $this->get_attachments();
394                 } else {
395                         $this->set_current_entry($postID);
396                         $output = $this->get_entry($postID, 'attachment');
397                         log_app('function',"get_attachment($postID)");
398                         $this->output($output);
399                 }
400         }
401
402         function create_attachment() {
403
404                 $type = $this->get_accepted_content_type();
405
406                 if(!current_user_can('upload_files'))
407                         $this->auth_required(__('You do not have permission to upload files.'));
408
409                 $fp = fopen("php://input", "rb");
410                 $bits = NULL;
411                 while(!feof($fp)) {
412                         $bits .= fread($fp, 4096);
413                 }
414                 fclose($fp);
415
416                 $slug = '';
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);
426
427                 log_app('wp_upload_bits returns:',print_r($file,true));
428
429                 $url = $file['url'];
430                 $file = $file['file'];
431
432                 do_action('wp_create_file_in_uploads', $file); // replicate
433
434                 // Construct the attachment array
435                 $attachment = array(
436                         'post_title' => $slug,
437                         'post_content' => $slug,
438                         'post_status' => 'attachment',
439                         'post_parent' => 0,
440                         'post_mime_type' => $type,
441                         'guid' => $url
442                         );
443
444                 // Save the data
445                 $postID = wp_insert_attachment($attachment, $file);
446
447                 if (!$postID)
448                         $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
449
450                 $output = $this->get_entry($postID, 'attachment');
451
452                 $this->created($postID, $output, 'attachment');
453                 log_app('function',"create_attachment($postID)");
454         }
455
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);
460
461                 $parser = new AtomParser();
462                 if(!$parser->parse()) {
463                         $this->bad_request();
464                 }
465
466                 $parsed = array_pop($parser->feed->entries);
467
468                 // check for not found
469                 global $entry;
470                 $this->set_current_entry($postID);
471
472                 if(!current_user_can('edit_post', $entry['ID']))
473                         $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
474
475                 extract($entry);
476
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];
482
483                 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt');
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                 // 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.'));
563
564                 // check for not found
565                 global $entry;
566                 $this->set_current_entry($postID);
567
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.'));
571                 }
572
573                 $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
574                 $filetype = wp_check_filetype($location);
575
576                 if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext']))
577                         $this->internal_error(__('Error ocurred while accessing post metadata for file location.'));
578
579                 $fp = fopen("php://input", "rb");
580                 $localfp = fopen($location, "w+");
581                 while(!feof($fp)) {
582                         fwrite($localfp,fread($fp, 4096));
583                 }
584                 fclose($fp);
585                 fclose($localfp);
586
587                 $ID = $entry['ID'];
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];
594
595                 $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt');
596                 $result = wp_update_post($post_data);
597
598                 if (!$result) {
599                         $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
600                 }
601
602                 log_app('function',"put_file($postID)");
603                 $this->ok();
604         }
605
606         function get_entries_url($page = NULL) {
607                 if($GLOBALS['post_type'] == 'attachment') {
608                         $path = $this->MEDIA_PATH;
609                 } else {
610                         $path = $this->ENTRIES_PATH;
611                 }
612                 $url = $this->app_base . $path;
613                 if(isset($page) && is_int($page)) {
614                         $url .= "/$page";
615                 }
616                 return $url;
617         }
618
619         function the_entries_url($page = NULL) {
620                 echo $this->get_entries_url($page);
621         }
622
623         function get_categories_url($deprecated = '') {
624                 return $this->app_base . $this->CATEGORIES_PATH;
625         }
626
627         function the_categories_url() {
628                 echo $this->get_categories_url();
629         }
630
631         function get_attachments_url($page = NULL) {
632                 $url = $this->app_base . $this->MEDIA_PATH;
633                 if(isset($page) && is_int($page)) {
634                         $url .= "/$page";
635                 }
636                 return $url;
637         }
638
639         function the_attachments_url($page = NULL) {
640                 echo $this->get_attachments_url($page);
641         }
642
643         function get_service_url() {
644                 return $this->app_base . $this->SERVICE_PATH;
645         }
646
647         function get_entry_url($postID = NULL) {
648                 if(!isset($postID)) {
649                         global $post;
650                         $postID = (int) $post->ID;
651                 }
652
653                 $url = $this->app_base . $this->ENTRY_PATH . "/$postID";
654
655                 log_app('function',"get_entry_url() = $url");
656                 return $url;
657         }
658
659         function the_entry_url($postID = NULL) {
660                 echo $this->get_entry_url($postID);
661         }
662
663         function get_media_url($postID = NULL) {
664                 if(!isset($postID)) {
665                         global $post;
666                         $postID = (int) $post->ID;
667                 }
668
669                 $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID";
670
671                 log_app('function',"get_media_url() = $url");
672                 return $url;
673         }
674
675         function the_media_url($postID = NULL) {
676                 echo $this->get_media_url($postID);
677         }
678
679         function set_current_entry($postID) {
680                 global $entry;
681                 log_app('function',"set_current_entry($postID)");
682
683                 if(!isset($postID)) {
684                         // $this->bad_request();
685                         $this->not_found();
686                 }
687
688                 $entry = wp_get_single_post($postID,ARRAY_A);
689
690                 if(!isset($entry) || !isset($entry['ID']))
691                         $this->not_found();
692
693                 return;
694         }
695
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);
700         }
701
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);
707         }
708
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')");
712                 ob_start();
713
714                 if(!isset($page)) {
715                         $page = 1;
716                 }
717                 $page = (int) $page;
718
719                 $count = get_option('posts_per_rss');
720
721                 wp('what_to_show=posts&posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified'));
722
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) . "#)");
730
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) ?>" />
745 <?php endif; ?>
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) ?>" />
748 <?php endif; ?>
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() ) {
755                                 the_post();
756                                 $this->echo_entry();
757                         }
758                 }
759 ?></feed>
760 <?php
761                 $feed = ob_get_contents();
762                 ob_end_clean();
763                 return $feed;
764         }
765
766         function get_entry($postID, $post_type = 'post') {
767                 log_app('function',"get_entry($postID, '$post_type')");
768                 ob_start();
769                 switch($post_type) {
770                         case 'post':
771                                 $varname = 'p';
772                                 break;
773                         case 'attachment':
774                                 $varname = 'attachment_id';
775                                 break;
776                 }
777                 query_posts($varname . '=' . $postID);
778                 if ( have_posts() ) {
779                         while ( have_posts() ) {
780                                 the_post();
781                                 $this->echo_entry();
782                                 log_app('$post',print_r($GLOBALS['post'],true));
783                                 $entry = ob_get_contents();
784                                 break;
785                         }
786                 }
787                 ob_end_clean();
788
789                 log_app('get_entry returning:',$entry);
790                 return $entry;
791         }
792
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>
802         <app:control>
803                 <app:draft><?php echo ($GLOBALS['post']->post_status == 'draft' ? 'yes' : 'no') ?></app:draft>
804         </app:control>
805         <author>
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>
809 <?php } ?>
810         </author>
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(); ?>"/>
814 <?php } else { ?>
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>
819 <?php endif; ?>
820 <?php } ?>
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?>" />
824 <?php } ?>
825 <?php list($content_type, $content) = prep_atom_text_construct(get_the_excerpt()); ?>
826         <summary type="<?php echo $content_type ?>"><?php echo $content ?></summary>
827 </entry>
828 <?php }
829
830         function ok() {
831                 log_app('Status','200: OK');
832                 header('Content-Type: text/plain');
833                 status_header('200');
834                 exit;
835         }
836
837         function no_content() {
838                 log_app('Status','204: No Content');
839                 header('Content-Type: text/plain');
840                 status_header('204');
841                 echo "Deleted.";
842                 exit;
843         }
844
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');
849                 echo $msg;
850                 exit;
851         }
852
853         function bad_request() {
854                 log_app('Status','400: Bad Request');
855                 header('Content-Type: text/plain');
856                 status_header('400');
857                 exit;
858         }
859
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');
865                 exit;
866         }
867
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');
872                 exit;
873         }
874
875         function not_found() {
876                 log_app('Status','404: Not Found');
877                 header('Content-Type: text/plain');
878                 status_header('404');
879                 exit;
880         }
881
882         function not_allowed($allow) {
883                 log_app('Status','405: Not Allowed');
884                 header('Allow: ' . join(',', $allow));
885                 status_header('405');
886                 exit;
887         }
888
889         function redirect($url) {
890
891                 log_app('Status','302: Redirect');
892                 $escaped_url = attribute_escape($url);
893                 $content = <<<EOD
894 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
895 <html>
896   <head>
897     <title>302 Found</title>
898   </head>
899 <body>
900   <h1>Found</h1>
901   <p>The document has moved <a href="$escaped_url">here</a>.</p>
902   </body>
903 </html>
904
905 EOD;
906                 header('HTTP/1.1 302 Moved');
907                 header('Content-Type: text/html');
908                 header('Location: ' . $url);
909                 echo $content;
910                 exit;
911
912         }
913
914
915         function client_error($msg = 'Client Error') {
916                 log_app('Status','400: Client Error');
917                 header('Content-Type: text/plain');
918                 status_header('400');
919                 exit;
920         }
921
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);
925                 switch($post_type) {
926                         case 'post':
927                                 $ctloc = $this->get_entry_url($post_ID);
928                                 break;
929                         case 'attachment':
930                                 $edit = $this->app_base . "attachments/$post_ID";
931                                 break;
932                 }
933                 header("Content-Type: $this->ATOM_CONTENT_TYPE");
934                 if(isset($ctloc))
935                         header('Content-Location: ' . $ctloc);
936                 header('Location: ' . $edit);
937                 status_header('201');
938                 echo $content;
939                 exit;
940         }
941
942         function auth_required($msg) {
943                 log_app('Status','401: Auth Required');
944                 nocache_headers();
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');
949                 $content = <<<EOD
950 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
951 <html>
952   <head>
953     <title>401 Unauthorized</title>
954   </head>
955 <body>
956     <h1>401 Unauthorized</h1>
957     <p>$msg</p>
958   </body>
959 </html>
960
961 EOD;
962                 echo $content;
963                 exit;
964         }
965
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'));
974                         if($this->do_output)
975                                 echo $xml;
976                         log_app('function', "output:\n$xml");
977                         exit;
978         }
979
980         function escape(&$array) {
981                 global $wpdb;
982
983                 foreach ($array as $k => $v) {
984                                 if (is_array($v)) {
985                                                 $this->escape($array[$k]);
986                                 } else if (is_object($v)) {
987                                                 //skip
988                                 } else {
989                                                 $array[$k] = $wpdb->escape($v);
990                                 }
991                 }
992         }
993
994         /*
995          * Access credential through various methods and perform login
996          */
997         function authenticate() {
998                 $login_data = array();
999                 $already_md5 = false;
1000
1001                 log_app("authenticate()",print_r($_ENV, true));
1002
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)));
1008                 }
1009
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']);
1014                 } else {
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;
1019                         }
1020                 }
1021
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']);
1027                 }
1028         }
1029
1030         function get_accepted_content_type($types = NULL) {
1031
1032                 if(!isset($types)) {
1033                         $types = $this->media_content_types;
1034                 }
1035
1036                 if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) {
1037                         $this->length_required();
1038                 }
1039
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");
1044
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;
1050                         }
1051                 }
1052
1053                 $this->invalid_media();
1054         }
1055
1056         function process_conditionals() {
1057
1058                 if(empty($this->params)) return;
1059                 if($_SERVER['REQUEST_METHOD'] == 'DELETE') return;
1060
1061                 switch($this->params[0]) {
1062                         case $this->ENTRY_PATH:
1063                                 global $post;
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);
1066                                 $post = NULL;
1067                                 break;
1068                         case $this->ENTRIES_PATH:
1069                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
1070                                 break;
1071                         default:
1072                                 return;
1073                 }
1074                 $wp_etag = md5($wp_last_modified);
1075                 @header("Last-Modified: $wp_last_modified");
1076                 @header("ETag: $wp_etag");
1077
1078                 // Support for Conditional GET
1079                 if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
1080                         $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
1081                 else
1082                         $client_etag = false;
1083
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;
1087
1088                 // Make a timestamp for our most recent modification...
1089                 $wp_modified_timestamp = strtotime($wp_last_modified);
1090
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 );
1095                         exit;
1096                 }
1097         }
1098
1099         function rfc3339_str2time($str) {
1100
1101             $match = false;
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))
1103                         return false;
1104
1105             if($match[3] == 'Z')
1106                         $match[3] == '+0000';
1107
1108             return strtotime($match[1] . " " . $match[2] . " " . $match[3]);
1109         }
1110
1111         function get_publish_time($published) {
1112
1113             $pubtime = $this->rfc3339_str2time($published);
1114
1115             if(!$pubtime) {
1116                         return array(current_time('mysql'),current_time('mysql',1));
1117             } else {
1118                         return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime));
1119             }
1120         }
1121
1122 }
1123
1124 $server = new AtomServer();
1125 $server->handle_request();
1126
1127 ?>