root/tags/2.3.3/wp-app.php

Revision 6508, 32.7 kB (checked in by ryan, 1 year ago)

Some cap checks for app from josephscott.

  • 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
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(