root/tags/1.5-rc1/wp-app.php

Revision 1218, 32.0 kB (checked in by donncha, 8 months ago)

Merged with WordPress? 2.5, unstable, only for testing

  • Property svn:eol-style set to native
Line 
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