PHP Cross Reference of WordPress Subversion HEAD

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]

title

Body

[close]

/ -> wp-app.php (source)

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