root/tags/1.3/wp-app.php

Revision 1139, 32.0 kB (checked in by donncha, 10 months ago)

Merge with WordPress? 2.3.1

  • 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         $entries_url = attribute_escape($this->get_entries_url());
163         $categories_url = attribute_escape($this->get_categories_url());
164         $media_url = attribute_escape($this->get_attachments_url());
165                 foreach ($this->media_content_types as $med) {
166                   $accepted_media_types = $accepted_media_types . "<accept>" . $med . "</accept>";
167                 }
168         $atom_prefix="atom";
169         $service_doc = <<<EOD
170 <service xmlns="$this->ATOMPUB_NS" xmlns:$atom_prefix="$this->ATOM_NS">
171   <workspace>
172     <$atom_prefix:title>WordPress Workspace</$atom_prefix:title>
173     <collection href="$entries_url">
174       <$atom_prefix:title>WordPress Posts</$atom_prefix:title>
175       <accept>$this->ATOM_CONTENT_TYPE;type=entry</accept>
176       <categories href="$categories_url" />
177     </collection>
178     <collection href="$media_url">
179       <$atom_prefix:title>WordPress Media</$atom_prefix:title>
180       $accepted_media_types
181     </collection>
182   </workspace>
183 </service>
184
185 EOD;
186
187         $this->output($service_doc, $this->SERVICE_CONTENT_TYPE);
188     }
189
190     function get_categories_xml() {
191
192         log_app('function','get_categories_xml()');
193         $home = attribute_escape(get_bloginfo_rss('home'));
194
195         $categories = "";
196         $cats = get_categories("hierarchical=0&hide_empty=0");
197         foreach ((array) $cats as $cat) {
198             $categories .= "    <category term=\"" . attribute_escape($cat->name) .  "\" />\n";
199 }
200         $output = <<<EOD
201 <app:categories xmlns:app="$this->ATOMPUB_NS"
202     xmlns="$this->ATOM_NS"
203     fixed="yes" scheme="$home">
204     $categories
205 </app:categories>
206 EOD;
207     $this->output($output, $this->CATEGORIES_CONTENT_TYPE);
208 }
209
210     /*
211      * Create Post (No arguments)
212      */
213     function create_post() {
214         global $blog_id, $wpdb;
215         $this->get_accepted_content_type($this->atom_content_types);
216
217         $parser = new AtomParser();
218         if(!$parser->parse()) {
219             $this->client_error();
220         }
221
222         $entry = array_pop($parser->feed->entries);
223
224         log_app('Received entry:', print_r($entry,true));
225
226         $catnames = array();
227         foreach($entry->categories as $cat)
228             array_push($catnames, $cat["term"]);
229
230         $wp_cats = get_categories(array('hide_empty' => false));
231
232         $post_category = array();
233
234         foreach($wp_cats as $cat) {
235             if(in_array($cat->name, $catnames))
236                 array_push($post_category, $cat->term_id);
237         }
238
239         $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true;
240
241         $cap = ($publish) ? 'publish_posts' : 'edit_posts';
242
243         if(!current_user_can($cap))
244             $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.'));
245
246         $blog_ID = (int ) $blog_id;
247         $post_status = ($publish) ? 'publish' : 'draft';
248         $post_author = (int) $user->ID;
249         $post_title = $entry->title[1];
250         $post_content = $entry->content[1];
251         $post_excerpt = $entry->summary[1];
252         $pubtimes = $this->get_publish_time($entry);
253         $post_date = $pubtimes[0];
254         $post_date_gmt = $pubtimes[1];
255
256         if ( isset( $_SERVER['HTTP_SLUG'] ) )
257             $post_name = $_SERVER['HTTP_SLUG'];
258
259         $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name');
260
261         $this->escape($post_data);
262         log_app('Inserting Post. Data:', print_r($post_data,true));
263
264         $postID = wp_insert_post($post_data);
265         if ( is_wp_error( $postID ) )
266             $this->internal_error($postID->get_error_message());
267
268         if (!$postID) {
269             $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
270         }
271
272         // getting warning here about unable to set headers
273         // because something in the cache is printing to the buffer
274         // could we clean up wp_set_post_categories or cache to not print
275         // this could affect our ability to send back the right headers
276         @wp_set_post_categories($postID, $post_category);
277
278         $output = $this->get_entry($postID);
279
280         log_app('function',"create_post($postID)");
281         $this->created($postID, $output);
282     }
283
284     function get_post($postID) {
285
286         global $entry;
287         $this->set_current_entry($postID);
288         $output = $this->get_entry($postID);
289         log_app('function',"get_post($postID)");
290         $this->output($output);
291
292     }
293
294     function put_post($postID) {
295         global $wpdb;
296
297         // checked for valid content-types (atom+xml)
298         // quick check and exit
299         $this->get_accepted_content_type($this->atom_content_types);
300
301         $parser = new AtomParser();
302         if(!$parser->parse()) {
303             $this->bad_request();
304         }
305
306         $parsed = array_pop($parser->feed->entries);
307
308         log_app('Received UPDATED entry:', print_r($parsed,true));
309
310         // check for not found
311         global $entry;
312         $entry = $GLOBALS['entry'];
313         $this->set_current_entry($postID);
314
315         if(!current_user_can('edit_post', $entry['ID']))
316             $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
317
318         $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
319
320         extract($entry);
321
322         $post_title = $parsed->title[1];
323         $post_content = $parsed->content[1];
324         $post_excerpt = $parsed->summary[1];
325         $pubtimes = $this->get_publish_time($entry);
326         $post_date = $pubtimes[0];
327         $post_date_gmt = $pubtimes[1];
328
329         // let's not go backwards and make something draft again.
330         if(!$publish && $post_status == 'draft') {
331             $post_status = ($publish) ? 'publish' : 'draft';
332         } elseif($publish) {
333             $post_status = 'publish';
334         }
335
336         $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt');
337         $this->escape($postdata);
338
339         $result = wp_update_post($postdata);
340
341         if (!$result) {
342             $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
343         }
344
345         log_app('function',"put_post($postID)");
346         $this->ok();
347     }
348
349     function delete_post($postID) {
350
351         // check for not found
352         global $entry;
353         $this->set_current_entry($postID);
354
355         if(!current_user_can('edit_post', $postID)) {
356             $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
357         }
358
359         if ($entry['post_type'] == 'attachment') {
360             $this->delete_attachment($postID);
361         } else {
362             $result = wp_delete_post($postID);
363
364             if (!$result) {
365                 $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.'));
366             }
367
368             log_app('function',"delete_post($postID)");
369             $this->ok();
370         }
371
372     }
373
374     function get_attachment($postID = NULL) {
375
376         global $entry;
377         if (!isset($postID)) {
378             $this->get_attachments();
379         } else {
380             $this->set_current_entry($postID);
381             $output = $this->get_entry($postID, 'attachment');
382             log_app('function',"get_attachment($postID)");
383             $this->output($output);
384         }
385     }
386
387     function create_attachment() {
388         global $wp, $wpdb, $wp_query, $blog_id;
389
390         $type = $this->get_accepted_content_type();
391
392         if(!current_user_can('upload_files'))
393             $this->auth_required(__('You do not have permission to upload files.'));
394
395         $fp = fopen("php://input", "rb");
396         $bits = NULL;
397         while(!feof($fp)) {
398             $bits .= fread($fp, 4096);
399         }
400         fclose($fp);
401
402         $slug = '';
403         if ( isset( $_SERVER['HTTP_SLUG'] ) )
404             $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] );
405         elseif ( isset( $_SERVER['HTTP_TITLE'] ) )
406             $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] );
407         elseif ( empty( $slug ) ) // just make a random name
408             $slug = substr( md5( uniqid( microtime() ) ), 0, 7);
409         $ext = preg_replace( '|.*/([a-z]+)|', '$1', $_SERVER['CONTENT_TYPE'] );
410         $slug = "$slug.$ext";
411         $file = wp_upload_bits( $slug, NULL, $bits);
412
413         log_app('wp_upload_bits returns:',print_r($file,true));
414
415         $url = $file['url'];
416         $file = $file['file'];
417         $filename = basename($file);
418
419         $header = apply_filters('wp_create_file_in_uploads', $file); // replicate
420
421         // Construct the attachment array
422         $attachment = array(
423             'post_title' => $slug,
424             'post_content' => $slug,
425             'post_status' => 'attachment',
426             'post_parent' => 0,
427             'post_mime_type' => $type,
428             'guid' => $url
429             );
430
431         // Save the data
432         $postID = wp_insert_attachment($attachment, $file, $post);
433
434         if (!$postID) {
435             $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.'));
436         }
437
438         $output = $this->get_entry($postID, 'attachment');
439
440         $this->created($postID, $output, 'attachment');
441         log_app('function',"create_attachment($postID)");
442     }
443
444     function put_attachment($postID) {
445         global $wpdb;
446
447         // checked for valid content-types (atom+xml)
448         // quick check and exit
449         $this->get_accepted_content_type($this->atom_content_types);
450
451         $parser = new AtomParser();
452         if(!$parser->parse()) {
453             $this->bad_request();
454         }
455
456         $parsed = array_pop($parser->feed->entries);
457
458         // check for not found
459         global $entry;
460         $this->set_current_entry($postID);
461
462         if(!current_user_can('edit_post', $entry['ID']))
463             $this->auth_required(__('Sorry, you do not have the right to edit this post.'));
464
465         $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true;
466
467         extract($entry);
468
469         $post_title = $parsed->title[1];
470         $post_content = $parsed->content[1];
471
472         $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
473         $this->escape($postdata);
474
475         $result = wp_update_post($postdata);
476
477         if (!$result) {
478             $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.'));
479         }
480
481         log_app('function',"put_attachment($postID)");
482         $this->ok();
483     }
484
485     function delete_attachment($postID) {
486         log_app('function',"delete_attachment($postID). File '$location' deleted.");
487
488         // check for not found
489         global $entry;
490         $this->set_current_entry($postID);
491
492         if(!current_user_can('edit_post', $postID)) {
493             $this->auth_required(__('Sorry, you do not have the right to delete this post.'));
494         }
495
496         $location = get_post_meta($entry['ID'], '_wp_attached_file', true);
497
498         // delete file