[ Index ]

PHP Cross Reference of Wordpress MU 2.7

title

Body

[close]

/ -> xmlrpc.php (source)

   1  <?php
   2  /**
   3   * XML-RPC protocol support for WordPress
   4   *
   5   * @license GPL v2 <./license.txt>
   6   * @package WordPress
   7   */
   8  
   9  /**
  10   * Whether this is a XMLRPC Request
  11   *
  12   * @var bool
  13   */
  14  define('XMLRPC_REQUEST', true);
  15  
  16  // Some browser-embedded clients send cookies. We don't want them.
  17  $_COOKIE = array();
  18  
  19  // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
  20  // but we can do it ourself.
  21  if ( !isset( $HTTP_RAW_POST_DATA ) ) {
  22      $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
  23  }
  24  
  25  // fix for mozBlog and other cases where '<?xml' isn't on the very first line
  26  if ( isset($HTTP_RAW_POST_DATA) )
  27      $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
  28  
  29  /** Include the bootstrap for setting up WordPress environment */
  30  include ('./wp-load.php');
  31  
  32  if ( isset( $_GET['rsd'] ) ) { // http://archipelago.phrasewise.com/rsd
  33  header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true);
  34  ?>
  35  <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
  36  <rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
  37    <service>
  38      <engineName>WordPress</engineName>
  39      <engineLink>http://wordpress.org/</engineLink>
  40      <homePageLink><?php bloginfo_rss('url') ?></homePageLink>
  41      <apis>
  42        <api name="WordPress" blogID="1" preferred="true" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
  43        <api name="Movable Type" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
  44        <api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
  45        <api name="Blogger" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
  46        <api name="Atom" blogID="" preferred="false" apiLink="<?php echo apply_filters('atom_service_url', site_url('wp-app.php/service') ) ?>" />
  47      </apis>
  48    </service>
  49  </rsd>
  50  <?php
  51  exit;
  52  }
  53  
  54  include_once (ABSPATH . 'wp-admin/includes/admin.php');
  55  include_once (ABSPATH . WPINC . '/class-IXR.php');
  56  
  57  // Turn off all warnings and errors.
  58  // error_reporting(0);
  59  
  60  /**
  61   * Posts submitted via the xmlrpc interface get that title
  62   * @name post_default_title
  63   * @var string
  64   */
  65  $post_default_title = "";
  66  
  67  /**
  68   * Whether to enable XMLRPC Logging.
  69   *
  70   * @name xmlrpc_logging
  71   * @var int|bool
  72   */
  73  $xmlrpc_logging = 0;
  74  
  75  /**
  76   * logIO() - Writes logging info to a file.
  77   *
  78   * @uses $xmlrpc_logging
  79   * @package WordPress
  80   * @subpackage Logging
  81   *
  82   * @param string $io Whether input or output
  83   * @param string $msg Information describing logging reason.
  84   * @return bool Always return true
  85   */
  86  function logIO($io,$msg) {
  87      global $xmlrpc_logging;
  88      if ($xmlrpc_logging) {
  89          $fp = fopen("../xmlrpc.log","a+");
  90          $date = gmdate("Y-m-d H:i:s ");
  91          $iot = ($io == "I") ? " Input: " : " Output: ";
  92          fwrite($fp, "\n\n".$date.$iot.$msg);
  93          fclose($fp);
  94      }
  95      return true;
  96  }
  97  
  98  if ( isset($HTTP_RAW_POST_DATA) )
  99      logIO("I", $HTTP_RAW_POST_DATA);
 100  
 101  /**
 102   * WordPress XMLRPC server implementation.
 103   *
 104   * Implements compatability for Blogger API, MetaWeblog API, MovableType, and
 105   * pingback. Additional WordPress API for managing comments, pages, posts,
 106   * options, etc.
 107   *
 108   * Since WordPress 2.6.0, WordPress XMLRPC server can be disabled in the
 109   * administration panels.
 110   *
 111   * @package WordPress
 112   * @subpackage Publishing
 113   * @since 1.5.0
 114   */
 115  class wp_xmlrpc_server extends IXR_Server {
 116  
 117      /**
 118       * Register all of the XMLRPC methods that XMLRPC server understands.
 119       *
 120       * PHP4 constructor and sets up server and method property. Passes XMLRPC
 121       * methods through the 'xmlrpc_methods' filter to allow plugins to extend
 122       * or replace XMLRPC methods.
 123       *
 124       * @since 1.5.0
 125       *
 126       * @return wp_xmlrpc_server
 127       */
 128  	function wp_xmlrpc_server() {
 129          $this->methods = array(
 130              // WordPress API
 131              'wp.getUsersBlogs'        => 'this:wp_getUsersBlogs',
 132              'wp.getPage'            => 'this:wp_getPage',
 133              'wp.getPages'            => 'this:wp_getPages',
 134              'wp.newPage'            => 'this:wp_newPage',
 135              'wp.deletePage'            => 'this:wp_deletePage',
 136              'wp.editPage'            => 'this:wp_editPage',
 137              'wp.getPageList'        => 'this:wp_getPageList',
 138              'wp.getAuthors'            => 'this:wp_getAuthors',
 139              'wp.getCategories'        => 'this:mw_getCategories',        // Alias
 140              'wp.getTags'            => 'this:wp_getTags',
 141              'wp.newCategory'        => 'this:wp_newCategory',
 142              'wp.deleteCategory'        => 'this:wp_deleteCategory',
 143              'wp.suggestCategories'    => 'this:wp_suggestCategories',
 144              'wp.uploadFile'            => 'this:mw_newMediaObject',    // Alias
 145              'wp.getCommentCount'    => 'this:wp_getCommentCount',
 146              'wp.getPostStatusList'    => 'this:wp_getPostStatusList',
 147              'wp.getPageStatusList'    => 'this:wp_getPageStatusList',
 148              'wp.getPageTemplates'    => 'this:wp_getPageTemplates',
 149              'wp.getOptions'            => 'this:wp_getOptions',
 150              'wp.setOptions'            => 'this:wp_setOptions',
 151              'wp.getComment'            => 'this:wp_getComment',
 152              'wp.getComments'        => 'this:wp_getComments',
 153              'wp.deleteComment'        => 'this:wp_deleteComment',
 154              'wp.editComment'        => 'this:wp_editComment',
 155              'wp.newComment'            => 'this:wp_newComment',
 156              'wp.getCommentStatusList' => 'this:wp_getCommentStatusList',
 157  
 158              // Blogger API
 159              'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
 160              'blogger.getUserInfo' => 'this:blogger_getUserInfo',
 161              'blogger.getPost' => 'this:blogger_getPost',
 162              'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
 163              'blogger.getTemplate' => 'this:blogger_getTemplate',
 164              'blogger.setTemplate' => 'this:blogger_setTemplate',
 165              'blogger.newPost' => 'this:blogger_newPost',
 166              'blogger.editPost' => 'this:blogger_editPost',
 167              'blogger.deletePost' => 'this:blogger_deletePost',
 168  
 169              // MetaWeblog API (with MT extensions to structs)
 170              'metaWeblog.newPost' => 'this:mw_newPost',
 171              'metaWeblog.editPost' => 'this:mw_editPost',
 172              'metaWeblog.getPost' => 'this:mw_getPost',
 173              'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
 174              'metaWeblog.getCategories' => 'this:mw_getCategories',
 175              'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',
 176  
 177              // MetaWeblog API aliases for Blogger API
 178              // see http://www.xmlrpc.com/stories/storyReader$2460
 179              'metaWeblog.deletePost' => 'this:blogger_deletePost',
 180              'metaWeblog.getTemplate' => 'this:blogger_getTemplate',
 181              'metaWeblog.setTemplate' => 'this:blogger_setTemplate',
 182              'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',
 183  
 184              // MovableType API
 185              'mt.getCategoryList' => 'this:mt_getCategoryList',
 186              'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
 187              'mt.getPostCategories' => 'this:mt_getPostCategories',
 188              'mt.setPostCategories' => 'this:mt_setPostCategories',
 189              'mt.supportedMethods' => 'this:mt_supportedMethods',
 190              'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
 191              'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
 192              'mt.publishPost' => 'this:mt_publishPost',
 193  
 194              // PingBack
 195              'pingback.ping' => 'this:pingback_ping',
 196              'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
 197  
 198              'demo.sayHello' => 'this:sayHello',
 199              'demo.addTwoNumbers' => 'this:addTwoNumbers'
 200          );
 201  
 202          $this->initialise_blog_option_info( );
 203          $this->methods = apply_filters('xmlrpc_methods', $this->methods);
 204          $this->IXR_Server($this->methods);
 205      }
 206  
 207      /**
 208       * Test XMLRPC API by saying, "Hello!" to client.
 209       *
 210       * @since 1.5.0
 211       *
 212       * @param array $args Method Parameters.
 213       * @return string
 214       */
 215  	function sayHello($args) {
 216          return 'Hello!';
 217      }
 218  
 219      /**
 220       * Test XMLRPC API by adding two numbers for client.
 221       *
 222       * @since 1.5.0
 223       *
 224       * @param array $args Method Parameters.
 225       * @return int
 226       */
 227  	function addTwoNumbers($args) {
 228          $number1 = $args[0];
 229          $number2 = $args[1];
 230          return $number1 + $number2;
 231      }
 232  
 233      /**
 234       * Check user's credentials.
 235       *
 236       * @since 1.5.0
 237       *
 238       * @param string $user_login User's username.
 239       * @param string $user_pass User's password.
 240       * @return bool Whether authentication passed.
 241       */
 242  	function login_pass_ok($user_login, $user_pass) {
 243          if ( !get_option( 'enable_xmlrpc' ) ) {
 244              $this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this blog.  An admin user can enable them at %s'),  admin_url('options-writing.php') ) );
 245              return false;
 246          }
 247  
 248          if (!user_pass_ok($user_login, $user_pass)) {
 249              $this->error = new IXR_Error(403, __('Bad login/pass combination.'));
 250              return false;
 251          }
 252          return true;
 253      }
 254  
 255      /**
 256       * Sanitize string or array of strings for database.
 257       *
 258       * @since 1.5.2
 259       *
 260       * @param string|array $array Sanitize single string or array of strings.
 261       * @return string|array Type matches $array and sanitized for the database.
 262       */
 263  	function escape(&$array) {
 264          global $wpdb;
 265  
 266          if(!is_array($array)) {
 267              return($wpdb->escape($array));
 268          }
 269          else {
 270              foreach ( (array) $array as $k => $v ) {
 271                  if (is_array($v)) {
 272                      $this->escape($array[$k]);
 273                  } else if (is_object($v)) {
 274                      //skip
 275                  } else {
 276                      $array[$k] = $wpdb->escape($v);
 277                  }
 278              }
 279          }
 280      }
 281  
 282      /**
 283       * Retrieve custom fields for post.
 284       *
 285       * @since 2.5.0
 286       *
 287       * @param int $post_id Post ID.
 288       * @return array Custom fields, if exist.
 289       */
 290  	function get_custom_fields($post_id) {
 291          $post_id = (int) $post_id;
 292  
 293          $custom_fields = array();
 294  
 295          foreach ( (array) has_meta($post_id) as $meta ) {
 296              // Don't expose protected fields.
 297              if ( strpos($meta['meta_key'], '_wp_') === 0 ) {
 298                  continue;
 299              }
 300  
 301              $custom_fields[] = array(
 302                  "id"    => $meta['meta_id'],
 303                  "key"   => $meta['meta_key'],
 304                  "value" => $meta['meta_value']
 305              );
 306          }
 307  
 308          return $custom_fields;
 309      }
 310  
 311      /**
 312       * Set custom fields for post.
 313       *
 314       * @since 2.5.0
 315       *
 316       * @param int $post_id Post ID.
 317       * @param array $fields Custom fields.
 318       */
 319  	function set_custom_fields($post_id, $fields) {
 320          $post_id = (int) $post_id;
 321  
 322          foreach ( (array) $fields as $meta ) {
 323              if ( isset($meta['id']) ) {
 324                  $meta['id'] = (int) $meta['id'];
 325  
 326                  if ( isset($meta['key']) ) {
 327                      update_meta($meta['id'], $meta['key'], $meta['value']);
 328                  }
 329                  else {
 330                      delete_meta($meta['id']);
 331                  }
 332              }
 333              else {
 334                  $_POST['metakeyinput'] = $meta['key'];
 335                  $_POST['metavalue'] = $meta['value'];
 336                  add_meta($post_id);
 337              }
 338          }
 339      }
 340  
 341      /**
 342       * Setup blog options property.
 343       *
 344       * Passes property through 'xmlrpc_blog_options' filter.
 345       *
 346       * @since 2.6.0
 347       */
 348  	function initialise_blog_option_info( ) {
 349          global $wp_version;
 350  
 351          $this->blog_options = array(
 352              // Read only options
 353              'software_name'        => array(
 354                  'desc'            => __( 'Software Name' ),
 355                  'readonly'        => true,
 356                  'value'            => 'WordPress'
 357              ),
 358              'software_version'    => array(
 359                  'desc'            => __( 'Software Version' ),
 360                  'readonly'        => true,
 361                  'value'            => $wp_version
 362              ),
 363              'blog_url'            => array(
 364                  'desc'            => __( 'Blog URL' ),
 365                  'readonly'        => true,
 366                  'option'        => 'siteurl'
 367              ),
 368  
 369              // Updatable options
 370              'time_zone'            => array(
 371                  'desc'            => __( 'Time Zone' ),
 372                  'readonly'        => false,
 373                  'option'        => 'gmt_offset'
 374              ),
 375              'blog_title'        => array(
 376                  'desc'            => __( 'Blog Title' ),
 377                  'readonly'        => false,
 378                  'option'            => 'blogname'
 379              ),
 380              'blog_tagline'        => array(
 381                  'desc'            => __( 'Blog Tagline' ),
 382                  'readonly'        => false,
 383                  'option'        => 'blogdescription'
 384              ),
 385              'date_format'        => array(
 386                  'desc'            => __( 'Date Format' ),
 387                  'readonly'        => false,
 388                  'option'        => 'date_format'
 389              ),
 390              'time_format'        => array(
 391                  'desc'            => __( 'Time Format' ),
 392                  'readonly'        => false,
 393                  'option'        => 'time_format'
 394              )
 395          );
 396  
 397          $this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options );
 398      }
 399  
 400      /**
 401       * Retrieve the blogs of the user.
 402       *
 403       * @since 2.6.0
 404       *
 405       * @param array $args Method parameters.
 406       * @return array
 407       */
 408  	function wp_getUsersBlogs( $args ) {
 409          global $current_site;
 410          // If this isn't on WPMU then just use blogger_getUsersBlogs
 411          if( !function_exists( 'is_site_admin' ) ) {
 412              array_unshift( $args, 1 );
 413              return $this->blogger_getUsersBlogs( $args );
 414          }
 415  
 416          $this->escape( $args );
 417  
 418          $username = $args[0];
 419          $password = $args[1];
 420  
 421          if( !$this->login_pass_ok( $username, $password ) )
 422              return $this->error;
 423  
 424          do_action( 'xmlrpc_call', 'wp.getUsersBlogs' );
 425  
 426          $user = set_current_user( 0, $username );
 427  
 428          $blogs = (array) get_blogs_of_user( $user->ID );
 429          $struct = array( );
 430  
 431          foreach( $blogs as $blog ) {
 432              // Don't include blogs that aren't hosted at this site
 433              if( $blog->site_id != $current_site->id )
 434                  continue;
 435  
 436              $blog_id = $blog->userblog_id;
 437              switch_to_blog($blog_id);
 438              $is_admin = current_user_can('level_8');
 439  
 440              $struct[] = array(
 441                  'isAdmin'        => $is_admin,
 442                  'url'            => get_option( 'home' ) . '/',
 443                  'blogid'        => $blog_id,
 444                  'blogName'        => get_option( 'blogname' ),
 445                  'xmlrpc'        => get_option( 'home' ) . '/xmlrpc.php'
 446              );
 447  
 448              restore_current_blog( );
 449          }
 450  
 451          return $struct;
 452      }
 453  
 454      /**
 455       * Retrieve page.
 456       *
 457       * @since 2.2.0
 458       *
 459       * @param array $args Method parameters.
 460       * @return array
 461       */
 462  	function wp_getPage($args) {
 463          $this->escape($args);
 464  
 465          $blog_id    = (int) $args[0];
 466          $page_id    = (int) $args[1];
 467          $username    = $args[2];
 468          $password    = $args[3];
 469  
 470          if(!$this->login_pass_ok($username, $password)) {
 471              return($this->error);
 472          }
 473  
 474          set_current_user( 0, $username );
 475          if( !current_user_can( 'edit_page', $page_id ) )
 476              return new IXR_Error( 401, __( 'Sorry, you can not edit this page.' ) );
 477  
 478          do_action('xmlrpc_call', 'wp.getPage');
 479  
 480          // Lookup page info.
 481          $page = get_page($page_id);
 482  
 483          // If we found the page then format the data.
 484          if($page->ID && ($page->post_type == "page")) {
 485              // Get all of the page content and link.
 486              $full_page = get_extended($page->post_content);
 487              $link = post_permalink($page->ID);
 488  
 489              // Get info the page parent if there is one.
 490              $parent_title = "";
 491              if(!empty($page->post_parent)) {
 492                  $parent = get_page($page->post_parent);
 493                  $parent_title = $parent->post_title;
 494              }
 495  
 496              // Determine comment and ping settings.
 497              $allow_comments = ("open" == $page->comment_status) ? 1 : 0;
 498              $allow_pings = ("open" == $page->ping_status) ? 1 : 0;
 499  
 500              // Format page date.
 501              $page_date = mysql2date("Ymd\TH:i:s", $page->post_date);
 502              $page_date_gmt = mysql2date("Ymd\TH:i:s", $page->post_date_gmt);
 503  
 504              // Pull the categories info together.
 505              $categories = array();
 506              foreach(wp_get_post_categories($page->ID) as $cat_id) {
 507                  $categories[] = get_cat_name($cat_id);
 508              }
 509  
 510              // Get the author info.
 511              $author = get_userdata($page->post_author);
 512  
 513              $page_template = get_post_meta( $page->ID, '_wp_page_template', true );
 514              if( empty( $page_template ) )
 515                  $page_template = 'default';
 516  
 517              $page_struct = array(
 518                  "dateCreated"            => new IXR_Date($page_date),
 519                  "userid"                => $page->post_author,
 520                  "page_id"                => $page->ID,
 521                  "page_status"            => $page->post_status,
 522                  "description"            => $full_page["main"],
 523                  "title"                    => $page->post_title,
 524                  "link"                    => $link,
 525                  "permaLink"                => $link,
 526                  "categories"            => $categories,
 527                  "excerpt"                => $page->post_excerpt,
 528                  "text_more"                => $full_page["extended"],
 529                  "mt_allow_comments"        => $allow_comments,
 530                  "mt_allow_pings"        => $allow_pings,
 531                  "wp_slug"                => $page->post_name,
 532                  "wp_password"            => $page->post_password,
 533                  "wp_author"                => $author->display_name,
 534                  "wp_page_parent_id"        => $page->post_parent,
 535                  "wp_page_parent_title"    => $parent_title,
 536                  "wp_page_order"            => $page->menu_order,
 537                  "wp_author_id"            => $author->ID,
 538                  "wp_author_display_name"    => $author->display_name,
 539                  "date_created_gmt"        => new IXR_Date($page_date_gmt),
 540                  "custom_fields"            => $this->get_custom_fields($page_id),
 541                  "wp_page_template"        => $page_template
 542              );
 543  
 544              return($page_struct);
 545          }
 546          // If the page doesn't exist indicate that.
 547          else {
 548              return(new IXR_Error(404, __("Sorry, no such page.")));
 549          }
 550      }
 551  
 552      /**
 553       * Retrieve Pages.
 554       *
 555       * @since 2.2.0
 556       *
 557       * @param array $args Method parameters.
 558       * @return array
 559       */
 560  	function wp_getPages($args) {
 561          $this->escape($args);
 562  
 563          $blog_id    = (int) $args[0];
 564          $username    = $args[1];
 565          $password    = $args[2];
 566          $num_pages    = (int) $args[3];
 567  
 568          if(!$this->login_pass_ok($username, $password)) {
 569              return($this->error);
 570          }
 571  
 572          set_current_user( 0, $username );
 573          if( !current_user_can( 'edit_pages' ) )
 574              return new IXR_Error( 401, __( 'Sorry, you can not edit pages.' ) );
 575  
 576          do_action('xmlrpc_call', 'wp.getPages');
 577  
 578          $page_limit = 10;
 579          if( isset( $num_pages ) ) {
 580              $page_limit = $num_pages;
 581          }
 582  
 583          $pages = get_posts( "post_type=page&post_status=all&numberposts={$page_limit}" );
 584          $num_pages = count($pages);
 585  
 586          // If we have pages, put together their info.
 587          if($num_pages >= 1) {
 588              $pages_struct = array();
 589  
 590              for($i = 0; $i < $num_pages; $i++) {
 591                  $page = wp_xmlrpc_server::wp_getPage(array(
 592                      $blog_id, $pages[$i]->ID, $username, $password
 593                  ));
 594                  $pages_struct[] = $page;
 595              }
 596  
 597              return($pages_struct);
 598          }
 599          // If no pages were found return an error.
 600          else {
 601              return(array());
 602          }
 603      }
 604  
 605      /**
 606       * Create new page.
 607       *
 608       * @since 2.2.0
 609       *
 610       * @param array $args Method parameters.
 611       * @return unknown
 612       */
 613  	function wp_newPage($args) {
 614          // Items not escaped here will be escaped in newPost.
 615          $username    = $this->escape($args[1]);
 616          $password    = $this->escape($args[2]);
 617          $page        = $args[3];
 618          $publish    = $args[4];
 619  
 620          if(!$this->login_pass_ok($username, $password)) {
 621              return($this->error);
 622          }
 623  
 624          do_action('xmlrpc_call', 'wp.newPage');
 625  
 626          // Set the user context and check if they are allowed
 627          // to add new pages.
 628          $user = set_current_user(0, $username);
 629          if(!current_user_can("publish_pages")) {
 630              return(new IXR_Error(401, __("Sorry, you can not add new pages.")));
 631          }
 632  
 633          // Mark this as content for a page.
 634          $args[3]["post_type"] = "page";
 635  
 636          // Let mw_newPost do all of the heavy lifting.
 637          return($this->mw_newPost($args));
 638      }
 639  
 640      /**
 641       * Delete page.
 642       *
 643       * @since 2.2.0
 644       *
 645       * @param array $args Method parameters.
 646       * @return bool True, if success.
 647       */
 648  	function wp_deletePage($args) {
 649          $this->escape($args);
 650  
 651          $blog_id    = (int) $args[0];
 652          $username    = $args[1];
 653          $password    = $args[2];
 654          $page_id    = (int) $args[3];
 655  
 656          if(!$this->login_pass_ok($username, $password)) {
 657              return($this->error);
 658          }
 659  
 660          do_action('xmlrpc_call', 'wp.deletePage');
 661  
 662          // Get the current page based on the page_id and
 663          // make sure it is a page and not a post.
 664          $actual_page = wp_get_single_post($page_id, ARRAY_A);
 665          if(
 666              !$actual_page
 667              || ($actual_page["post_type"] != "page")
 668          ) {
 669              return(new IXR_Error(404, __("Sorry, no such page.")));
 670          }
 671  
 672          // Set the user context and make sure they can delete pages.
 673          set_current_user(0, $username);
 674          if(!current_user_can("delete_page", $page_id)) {
 675              return(new IXR_Error(401, __("Sorry, you do not have the right to delete this page.")));
 676          }
 677  
 678          // Attempt to delete the page.
 679          $result = wp_delete_post($page_id);
 680          if(!$result) {
 681              return(new IXR_Error(500, __("Failed to delete the page.")));
 682          }
 683  
 684          return(true);
 685      }
 686  
 687      /**
 688       * Edit page.
 689       *
 690       * @since 2.2.0
 691       *
 692       * @param array $args Method parameters.
 693       * @return unknown
 694       */
 695  	function wp_editPage($args) {
 696          // Items not escaped here will be escaped in editPost.
 697          $blog_id    = (int) $args[0];
 698          $page_id    = (int) $this->escape($args[1]);
 699          $username    = $this->escape($args[2]);
 700          $password    = $this->escape($args[3]);
 701          $content    = $args[4];
 702          $publish    = $args[5];
 703  
 704          if(!$this->login_pass_ok($username, $password)) {
 705              return($this->error);
 706          }
 707  
 708          do_action('xmlrpc_call', 'wp.editPage');
 709  
 710          // Get the page data and make sure it is a page.
 711          $actual_page = wp_get_single_post($page_id, ARRAY_A);
 712          if(
 713              !$actual_page
 714              || ($actual_page["post_type"] != "page")
 715          ) {
 716              return(new IXR_Error(404, __("Sorry, no such page.")));
 717          }
 718  
 719          // Set the user context and make sure they are allowed to edit pages.
 720          set_current_user(0, $username);
 721          if(!current_user_can("edit_page", $page_id)) {
 722              return(new IXR_Error(401, __("Sorry, you do not have the right to edit this page.")));
 723          }
 724  
 725          // Mark this as content for a page.
 726          $content["post_type"] = "page";
 727  
 728          // Arrange args in the way mw_editPost understands.
 729          $args = array(
 730              $page_id,
 731              $username,
 732              $password,
 733              $content,
 734              $publish
 735          );
 736  
 737          // Let mw_editPost do all of the heavy lifting.
 738          return($this->mw_editPost($args));
 739      }
 740  
 741      /**
 742       * Retrieve page list.
 743       *
 744       * @since 2.2.0
 745       *
 746       * @param array $args Method parameters.
 747       * @return unknown
 748       */
 749  	function wp_getPageList($args) {
 750          global $wpdb;
 751  
 752          $this->escape($args);
 753  
 754          $blog_id                = (int) $args[0];
 755          $username                = $args[1];
 756          $password                = $args[2];
 757  
 758          if(!$this->login_pass_ok($username, $password)) {
 759              return($this->error);
 760          }
 761  
 762          set_current_user( 0, $username );
 763          if( !current_user_can( 'edit_pages' ) )
 764              return new IXR_Error( 401, __( 'Sorry, you can not edit pages.' ) );
 765  
 766          do_action('xmlrpc_call', 'wp.getPageList');
 767  
 768          // Get list of pages ids and titles
 769          $page_list = $wpdb->get_results("
 770              SELECT ID page_id,
 771                  post_title page_title,
 772                  post_parent page_parent_id,
 773                  post_date_gmt,
 774                  post_date
 775              FROM {$wpdb->posts}
 776              WHERE post_type = 'page'
 777              ORDER BY ID
 778          ");
 779  
 780          // The date needs to be formated properly.
 781          $num_pages = count($page_list);
 782          for($i = 0; $i < $num_pages; $i++) {
 783              $post_date = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date);
 784              $post_date_gmt = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date_gmt);
 785  
 786              $page_list[$i]->dateCreated = new IXR_Date($post_date);
 787              $page_list[$i]->date_created_gmt = new IXR_Date($post_date_gmt);
 788  
 789              unset($page_list[$i]->post_date_gmt);
 790              unset($page_list[$i]->post_date);
 791          }
 792  
 793          return($page_list);
 794      }
 795  
 796      /**
 797       * Retrieve authors list.
 798       *
 799       * @since 2.2.0
 800       *
 801       * @param array $args Method parameters.
 802       * @return array
 803       */
 804  	function wp_getAuthors($args) {
 805  
 806          $this->escape($args);
 807  
 808          $blog_id    = (int) $args[0];
 809          $username    = $args[1];
 810          $password    = $args[2];
 811  
 812          if(!$this->login_pass_ok($username, $password)) {
 813              return($this->error);
 814          }
 815  
 816          set_current_user(0, $username);
 817          if(!current_user_can("edit_posts")) {
 818              return(new IXR_Error(401, __("Sorry, you can not edit posts on this blog.")));
 819          }
 820  
 821          do_action('xmlrpc_call', 'wp.getAuthors');
 822  
 823          $authors = array();
 824          foreach( (array) get_users_of_blog() as $row ) {
 825              $authors[] = array(
 826                  "user_id"       => $row->user_id,
 827                  "user_login"    => $row->user_login,
 828                  "display_name"  => $row->display_name
 829              );
 830          }
 831  
 832          return($authors);
 833      }
 834  
 835      /**
 836       * Get list of all tags
 837       *
 838       * @since 2.7
 839       *
 840       * @param array $args Method parameters.
 841       * @return array
 842       */
 843  	function wp_getTags( $args ) {
 844          $this->escape( $args );
 845  
 846          $blog_id        = (int) $args[0];
 847          $username        = $args[1];
 848          $password        = $args[2];
 849  
 850          if( !$this->login_pass_ok( $username, $password ) ) {
 851              return $this->error;
 852          }
 853  
 854          set_current_user( 0, $username );
 855          if( !current_user_can( 'edit_posts' ) ) {
 856              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view tags.' ) );
 857          }
 858  
 859          do_action( 'xmlrpc_call', 'wp.getKeywords' );
 860  
 861          $tags = array( );
 862  
 863          if( $all_tags = get_tags( ) ) {
 864              foreach( (array) $all_tags as $tag ) {
 865                  $struct['tag_id']            = $tag->term_id;
 866                  $struct['name']                = $tag->name;
 867                  $struct['count']            = $tag->count;
 868                  $struct['slug']                = $tag->slug;
 869                  $struct['html_url']            = wp_specialchars( get_tag_link( $tag->term_id ) );
 870                  $struct['rss_url']            = wp_specialchars( get_tag_feed_link( $tag->term_id ) );
 871  
 872                  $tags[] = $struct;
 873              }
 874          }
 875  
 876          return $tags;
 877      }
 878  
 879      /**
 880       * Create new category.
 881       *
 882       * @since 2.2.0
 883       *
 884       * @param array $args Method parameters.
 885       * @return int Category ID.
 886       */
 887  	function wp_newCategory($args) {
 888          $this->escape($args);
 889  
 890          $blog_id                = (int) $args[0];
 891          $username                = $args[1];
 892          $password                = $args[2];
 893          $category                = $args[3];
 894  
 895          if(!$this->login_pass_ok($username, $password)) {
 896              return($this->error);
 897          }
 898  
 899          do_action('xmlrpc_call', 'wp.newCategory');
 900  
 901          // Set the user context and make sure they are
 902          // allowed to add a category.
 903          set_current_user(0, $username);
 904          if(!current_user_can("manage_categories")) {
 905              return(new IXR_Error(401, __("Sorry, you do not have the right to add a category.")));
 906          }
 907  
 908          // If no slug was provided make it empty so that
 909          // WordPress will generate one.
 910          if(empty($category["slug"])) {
 911              $category["slug"] = "";
 912          }
 913  
 914          // If no parent_id was provided make it empty
 915          // so that it will be a top level page (no parent).
 916          if ( !isset($category["parent_id"]) )
 917              $category["parent_id"] = "";
 918  
 919          // If no description was provided make it empty.
 920          if(empty($category["description"])) {
 921              $category["description"] = "";
 922          }
 923  
 924          $new_category = array(
 925              "cat_name"                => $category["name"],
 926              "category_nicename"        => $category["slug"],
 927              "category_parent"        => $category["parent_id"],
 928              "category_description"    => $category["description"]
 929          );
 930  
 931          $cat_id = wp_insert_category($new_category);
 932          if(!$cat_id) {
 933              return(new IXR_Error(500, __("Sorry, the new category failed.")));
 934          }
 935  
 936          return($cat_id);
 937      }
 938  
 939      /**
 940       * Remove category.
 941       *
 942       * @since 2.5.0
 943       *
 944       * @param array $args Method parameters.
 945       * @return mixed See {@link wp_delete_category()} for return info.
 946       */
 947  	function wp_deleteCategory($args) {
 948          $this->escape($args);
 949  
 950          $blog_id        = (int) $args[0];
 951          $username        = $args[1];
 952          $password        = $args[2];
 953          $category_id    = (int) $args[3];
 954  
 955          if( !$this->login_pass_ok( $username, $password ) ) {
 956              return $this->error;
 957          }
 958  
 959          do_action('xmlrpc_call', 'wp.deleteCategory');
 960  
 961          set_current_user(0, $username);
 962          if( !current_user_can("manage_categories") ) {
 963              return new IXR_Error( 401, __( "Sorry, you do not have the right to delete a category." ) );
 964          }
 965  
 966          return wp_delete_category( $category_id );
 967      }
 968  
 969      /**
 970       * Retrieve category list.
 971       *
 972       * @since 2.2.0
 973       *
 974       * @param array $args Method parameters.
 975       * @return array
 976       */
 977  	function wp_suggestCategories($args) {
 978          $this->escape($args);
 979  
 980          $blog_id                = (int) $args[0];
 981          $username                = $args[1];
 982          $password                = $args[2];
 983          $category                = $args[3];
 984          $max_results            = (int) $args[4];
 985  
 986          if(!$this->login_pass_ok($username, $password)) {
 987              return($this->error);
 988          }
 989  
 990          set_current_user(0, $username);
 991          if( !current_user_can( 'edit_posts' ) )
 992              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts to this blog in order to view categories.' ) );
 993  
 994          do_action('xmlrpc_call', 'wp.suggestCategories');
 995  
 996          $category_suggestions = array();
 997          $args = array('get' => 'all', 'number' => $max_results, 'name__like' => $category);
 998          foreach ( (array) get_categories($args) as $cat ) {
 999              $category_suggestions[] = array(
1000                  "category_id"    => $cat->cat_ID,
1001                  "category_name"    => $cat->cat_name
1002              );
1003          }
1004  
1005          return($category_suggestions);
1006      }
1007  
1008      /**
1009       * Retrieve comment.
1010       *
1011       * @since 2.7.0
1012       *
1013       * @param array $args Method parameters.
1014       * @return array
1015       */
1016  	function wp_getComment($args) {
1017          $this->escape($args);
1018  
1019          $blog_id    = (int) $args[0];
1020          $username    = $args[1];
1021          $password    = $args[2];
1022          $comment_id    = (int) $args[3];
1023  
1024          if ( !$this->login_pass_ok( $username, $password ) )
1025              return $this->error;
1026  
1027          set_current_user( 0, $username );
1028          if ( !current_user_can( 'moderate_comments' ) )
1029              return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1030  
1031          do_action('xmlrpc_call', 'wp.getComment');
1032  
1033          if ( ! $comment = get_comment($comment_id) )
1034              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1035  
1036          // Format page date.
1037          $comment_date = mysql2date("Ymd\TH:i:s", $comment->comment_date);
1038          $comment_date_gmt = mysql2date("Ymd\TH:i:s", $comment->comment_date_gmt);
1039  
1040          if ( 0 == $comment->comment_approved )
1041              $comment_status = 'hold';
1042          else if ( 'spam' == $comment->comment_approved )
1043              $comment_status = 'spam';
1044          else if ( 1 == $comment->comment_approved )
1045              $comment_status = 'approve';
1046          else
1047              $comment_status = $comment->comment_approved;
1048  
1049          $link = get_comment_link($comment);
1050  
1051          $comment_struct = array(
1052              "date_created_gmt"        => new IXR_Date($comment_date_gmt),
1053              "user_id"                => $comment->user_id,
1054              "comment_id"            => $comment->comment_ID,
1055              "parent"                => $comment->comment_parent,
1056              "status"                => $comment_status,
1057              "content"                => $comment->comment_content,
1058              "link"                    => $link,
1059              "post_id"                => $comment->comment_post_ID,
1060              "post_title"            => get_the_title($comment->comment_post_ID),
1061              "author"                => $comment->comment_author,
1062              "author_url"            => $comment->comment_author_url,
1063              "author_email"            => $comment->comment_author_email,
1064              "author_ip"                => $comment->comment_author_IP,
1065              "type"                    => $comment->comment_type,
1066          );
1067  
1068          return $comment_struct;
1069      }
1070  
1071      /**
1072       * Retrieve comments.
1073       *
1074       * @since 2.7.0
1075       *
1076       * @param array $args Method parameters.
1077       * @return array
1078       */
1079  	function wp_getComments($args) {
1080          $this->escape($args);
1081  
1082          $blog_id    = (int) $args[0];
1083          $username    = $args[1];
1084          $password    = $args[2];
1085          $struct        = $args[3];
1086  
1087          if ( !$this->login_pass_ok($username, $password) )
1088              return($this->error);
1089  
1090          set_current_user( 0, $username );
1091          if ( !current_user_can( 'moderate_comments' ) )
1092              return new IXR_Error( 401, __( 'Sorry, you can not edit comments.' ) );
1093  
1094          do_action('xmlrpc_call', 'wp.getComments');
1095  
1096          if ( isset($struct['status']) )
1097              $status = $struct['status'];
1098          else
1099              $status = '';
1100  
1101          $post_id = '';
1102          if ( isset($struct['post_id']) )
1103              $post_id = absint($struct['post_id']);
1104  
1105          $offset = 0;
1106          if ( isset($struct['offset']) )
1107              $offset = absint($struct['offset']);
1108  
1109          $number = 10;
1110          if ( isset($struct['number']) )
1111              $number = absint($struct['number']);
1112  
1113          $comments = get_comments( array('status' => $status, 'post_id' => $post_id, 'offset' => $offset, 'number' => $number ) );
1114          $num_comments = count($comments);
1115  
1116          if ( ! $num_comments )
1117              return array();
1118  
1119          $comments_struct = array();
1120  
1121          for ( $i = 0; $i < $num_comments; $i++ ) {
1122              $comment = wp_xmlrpc_server::wp_getComment(array(
1123                  $blog_id, $username, $password, $comments[$i]->comment_ID,
1124              ));
1125              $comments_struct[] = $comment;
1126          }
1127  
1128          return $comments_struct;
1129      }
1130  
1131      /**
1132       * Remove comment.
1133       *
1134       * @since 2.7.0
1135       *
1136       * @param array $args Method parameters.
1137       * @return mixed {@link wp_delete_comment()}
1138       */
1139  	function wp_deleteComment($args) {
1140          $this->escape($args);
1141  
1142          $blog_id    = (int) $args[0];
1143          $username    = $args[1];
1144          $password    = $args[2];
1145          $comment_ID    = (int) $args[3];
1146  
1147          if ( !$this->login_pass_ok( $username, $password ) )
1148              return $this->error;
1149  
1150          set_current_user( 0, $username );
1151          if ( !current_user_can( 'moderate_comments' ) )
1152              return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1153  
1154          do_action('xmlrpc_call', 'wp.deleteComment');
1155  
1156          if ( ! get_comment($comment_ID) )
1157              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1158  
1159          return wp_delete_comment($comment_ID);
1160      }
1161  
1162      /**
1163       * Edit comment.
1164       *
1165       * @since 2.7.0
1166       *
1167       * @param array $args Method parameters.
1168       * @return bool True, on success.
1169       */
1170  	function wp_editComment($args) {
1171          $this->escape($args);
1172  
1173          $blog_id    = (int) $args[0];
1174          $username    = $args[1];
1175          $password    = $args[2];
1176          $comment_ID    = (int) $args[3];
1177          $content_struct = $args[4];
1178  
1179          if ( !$this->login_pass_ok( $username, $password ) )
1180              return $this->error;
1181  
1182          set_current_user( 0, $username );
1183          if ( !current_user_can( 'moderate_comments' ) )
1184              return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1185  
1186          do_action('xmlrpc_call', 'wp.editComment');
1187  
1188          if ( ! get_comment($comment_ID) )
1189              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1190  
1191          if ( isset($content_struct['status']) ) {
1192              $statuses = get_comment_statuses();
1193              $statuses = array_keys($statuses);
1194  
1195              if ( ! in_array($content_struct['status'], $statuses) )
1196                  return new IXR_Error( 401, __( 'Invalid comment status.' ) );
1197              $comment_approved = $content_struct['status'];
1198          }
1199  
1200          // Do some timestamp voodoo
1201          if ( !empty( $content_struct['date_created_gmt'] ) ) {
1202              $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force
1203              $comment_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1204              $comment_date_gmt = iso8601_to_datetime($dateCreated, GMT);
1205          }
1206  
1207          if ( isset($content_struct['content']) )
1208              $comment_content = $content_struct['content'];
1209  
1210          if ( isset($content_struct['author']) )
1211              $comment_author = $content_struct['author'];
1212  
1213          if ( isset($content_struct['author_url']) )
1214              $comment_author_url = $content_struct['author_url'];
1215  
1216          if ( isset($content_struct['author_email']) )
1217              $comment_author_email = $content_struct['author_email'];
1218  
1219          // We've got all the data -- post it:
1220          $comment = compact('comment_ID', 'comment_content', 'comment_approved', 'comment_date', 'comment_date_gmt', 'comment_author', 'comment_author_email', 'comment_author_url');
1221  
1222          $result = wp_update_comment($comment);
1223          if ( is_wp_error( $result ) )
1224              return new IXR_Error(500, $result->get_error_message());
1225  
1226          if ( !$result )
1227              return new IXR_Error(500, __('Sorry, the comment could not be edited. Something wrong happened.'));
1228  
1229          return true;
1230      }
1231  
1232      /**
1233       * Create new comment.
1234       *
1235       * @since 2.7.0
1236       *
1237       * @param array $args Method parameters.
1238       * @return mixed {@link wp_new_comment()}
1239       */
1240  	function wp_newComment($args) {
1241          global $wpdb;
1242  
1243          $this->escape($args);
1244  
1245          $blog_id    = (int) $args[0];
1246          $username    = $args[1];
1247          $password    = $args[2];
1248          $post        = $args[3];
1249          $content_struct = $args[4];
1250  
1251          $allow_anon = apply_filters('xmlrpc_allow_anonymous_comments', false);
1252  
1253          if ( !$this->login_pass_ok( $username, $password ) ) {
1254              $logged_in = false;
1255              if ( $allow_anon && get_option('comment_registration') )
1256                  return new IXR_Error( 403, __( 'You must be registered to comment' ) );
1257              else if ( !$allow_anon )
1258                  return $this->error;
1259          } else {
1260              $logged_in = true;
1261              set_current_user( 0, $username );
1262              if ( !current_user_can( 'moderate_comments' ) )
1263                  return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1264          }
1265  
1266          if ( is_numeric($post) )
1267              $post_id = absint($post);
1268          else
1269              $post_id = url_to_postid($post);
1270  
1271          if ( ! $post_id )
1272              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1273  
1274          if ( ! get_post($post_id) )
1275              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1276  
1277          $comment['comment_post_ID'] = $post_id;
1278  
1279          if ( $logged_in ) {
1280              $user = wp_get_current_user();
1281              $comment['comment_author'] = $wpdb->escape( $user->display_name );
1282              $comment['comment_author_email'] = $wpdb->escape( $user->user_email );
1283              $comment['comment_author_url'] = $wpdb->escape( $user->user_url );
1284              $comment['user_ID'] = $user->ID;
1285          } else {
1286              $comment['comment_author'] = '';
1287              if ( isset($content_struct['author']) )
1288                  $comment['comment_author'] = $content_struct['author'];
1289              $comment['comment_author_email'] = '';
1290              if ( isset($content_struct['author']) )
1291                  $comment['comment_author_email'] = $content_struct['author_email'];
1292              $comment['comment_author_url'] = '';
1293              if ( isset($content_struct['author']) )
1294                  $comment['comment_author_url'] = $content_struct['author_url'];
1295              $comment['user_ID'] = 0;
1296  
1297              if ( get_option('require_name_email') ) {
1298                  if ( 6 > strlen($comment['comment_author_email']) || '' == $comment['comment_author'] )
1299                      return new IXR_Error( 403, __( 'Comment author name and email are required' ) );
1300                  elseif ( !is_email($comment['comment_author_email']) )
1301                      return new IXR_Error( 403, __( 'A valid email address is required' ) );
1302              }
1303          }
1304  
1305          $comment['comment_parent'] = isset($content_struct['comment_parent']) ? absint($content_struct['comment_parent']) : 0;
1306  
1307          $comment['comment_content'] = $content_struct['content'];
1308  
1309          do_action('xmlrpc_call', 'wp.newComment');
1310  
1311          return wp_new_comment($comment);
1312      }
1313  
1314      /**
1315       * Retrieve all of the comment status.
1316       *
1317       * @since 2.7.0
1318       *
1319       * @param array $args Method parameters.
1320       * @return array
1321       */
1322  	function wp_getCommentStatusList($args) {
1323          $this->escape( $args );
1324  
1325          $blog_id    = (int) $args[0];
1326          $username    = $args[1];
1327          $password    = $args[2];
1328  
1329          if ( !$this->login_pass_ok( $username, $password ) )
1330              return $this->error;
1331  
1332          set_current_user( 0, $username );
1333          if ( !current_user_can( 'moderate_comments' ) )
1334              return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1335  
1336          do_action('xmlrpc_call', 'wp.getCommentStatusList');
1337  
1338          return get_comment_statuses( );
1339      }
1340  
1341      /**
1342       * Retrieve comment count.
1343       *
1344       * @since 2.5.0
1345       *
1346       * @param array $args Method parameters.
1347       * @return array
1348       */
1349  	function wp_getCommentCount( $args ) {
1350          $this->escape($args);
1351  
1352          $blog_id    = (int) $args[0];
1353          $username    = $args[1];
1354          $password    = $args[2];
1355          $post_id    = (int) $args[3];
1356  
1357          if( !$this->login_pass_ok( $username, $password ) ) {
1358              return $this->error;
1359          }
1360  
1361          set_current_user( 0, $username );
1362          if( !current_user_can( 'edit_posts' ) ) {
1363              return new IXR_Error( 403, __( 'You are not allowed access to details about comments.' ) );
1364          }
1365  
1366          do_action('xmlrpc_call', 'wp.getCommentCount');
1367  
1368          $count = wp_count_comments( $post_id );
1369          return array(
1370              "approved" => $count->approved,
1371              "awaiting_moderation" => $count->moderated,
1372              "spam" => $count->spam,
1373              "total_comments" => $count->total_comments
1374          );
1375      }
1376  
1377      /**
1378       * Retrieve post statuses.
1379       *
1380       * @since 2.5.0
1381       *
1382       * @param array $args Method parameters.
1383       * @return array
1384       */
1385  	function wp_getPostStatusList( $args ) {
1386          $this->escape( $args );
1387  
1388          $blog_id    = (int) $args[0];
1389          $username    = $args[1];
1390          $password    = $args[2];
1391  
1392          if( !$this->login_pass_ok( $username, $password ) ) {
1393              return $this->error;
1394          }
1395  
1396          set_current_user( 0, $username );
1397          if( !current_user_can( 'edit_posts' ) ) {
1398              return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1399          }
1400  
1401          do_action('xmlrpc_call', 'wp.getPostStatusList');
1402  
1403          return get_post_statuses( );
1404      }
1405  
1406      /**
1407       * Retrieve page statuses.
1408       *
1409       * @since 2.5.0
1410       *
1411       * @param array $args Method parameters.
1412       * @return array
1413       */
1414  	function wp_getPageStatusList( $args ) {
1415          $this->escape( $args );
1416  
1417          $blog_id    = (int) $args[0];
1418          $username    = $args[1];
1419          $password    = $args[2];
1420  
1421          if( !$this->login_pass_ok( $username, $password ) ) {
1422              return $this->error;
1423          }
1424  
1425          set_current_user( 0, $username );
1426          if( !current_user_can( 'edit_posts' ) ) {
1427              return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1428          }
1429  
1430          do_action('xmlrpc_call', 'wp.getPageStatusList');
1431  
1432          return get_page_statuses( );
1433      }
1434  
1435      /**
1436       * Retrieve page templates.
1437       *
1438       * @since 2.6.0
1439       *
1440       * @param array $args Method parameters.
1441       * @return array
1442       */
1443  	function wp_getPageTemplates( $args ) {
1444          $this->escape( $args );
1445  
1446          $blog_id    = (int) $args[0];
1447          $username    = $args[1];
1448          $password    = $args[2];
1449  
1450          if( !$this->login_pass_ok( $username, $password ) ) {
1451              return $this->error;
1452          }
1453  
1454          set_current_user( 0, $username );
1455          if( !current_user_can( 'edit_pages' ) ) {
1456              return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1457          }
1458  
1459          $templates = get_page_templates( );
1460          $templates['Default'] = 'default';
1461  
1462          return $templates;
1463      }
1464  
1465      /**
1466       * Retrieve blog options.
1467       *
1468       * @since 2.6.0
1469       *
1470       * @param array $args Method parameters.
1471       * @return array
1472       */
1473  	function wp_getOptions( $args ) {
1474          $this->escape( $args );
1475  
1476          $blog_id    = (int) $args[0];
1477          $username    = $args[1];
1478          $password    = $args[2];
1479          $options    = (array) $args[3];
1480  
1481          if( !$this->login_pass_ok( $username, $password ) )
1482              return $this->error;
1483  
1484          $user = set_current_user( 0, $username );
1485  
1486          // If no specific options where asked for, return all of them
1487          if (count( $options ) == 0 ) {
1488              $options = array_keys($this->blog_options);
1489          }
1490  
1491          return $this->_getOptions($options);
1492      }
1493  
1494      /**
1495       * Retrieve blog options value from list.
1496       *
1497       * @since 2.6.0
1498       *
1499       * @param array $options Options to retrieve.
1500       * @return array
1501       */
1502  	function _getOptions($options)
1503      {
1504          $data = array( );
1505          foreach( $options as $option ) {
1506              if( array_key_exists( $option, $this->blog_options ) )
1507              {
1508                  $data[$option] = $this->blog_options[$option];
1509                  //Is the value static or dynamic?
1510                  if( isset( $data[$option]['option'] ) ) {
1511                      $data[$option]['value'] = get_option( $data[$option]['option'] );
1512                      unset($data[$option]['option']);
1513                  }
1514              }
1515          }
1516  
1517          return $data;
1518      }
1519  
1520      /**
1521       * Update blog options.
1522       *
1523       * @since 2.6.0
1524       *
1525       * @param array $args Method parameters.
1526       * @return unknown
1527       */
1528  	function wp_setOptions( $args ) {
1529          $this->escape( $args );
1530  
1531          $blog_id    = (int) $args[0];
1532          $username    = $args[1];
1533          $password    = $args[2];
1534          $options    = (array) $args[3];
1535  
1536          if( !$this->login_pass_ok( $username, $password ) )
1537              return $this->error;
1538  
1539          $user = set_current_user( 0, $username );
1540          if( !current_user_can( 'manage_options' ) )
1541              return new IXR_Error( 403, __( 'You are not allowed to update options.' ) );
1542  
1543          foreach( $options as $o_name => $o_value ) {
1544              $option_names[] = $o_name;
1545              if( empty( $o_value ) )
1546                  continue;
1547  
1548              if( !array_key_exists( $o_name, $this->blog_options ) )
1549                  continue;
1550  
1551              if( $this->blog_options[$o_name]['readonly'] == true )
1552                  continue;
1553  
1554              update_option( $this->blog_options[$o_name]['option'], $o_value );
1555          }
1556  
1557          //Now return the updated values
1558          return $this->_getOptions($option_names);
1559      }
1560  
1561      /* Blogger API functions.
1562       * specs on http://plant.blogger.com/api and http://groups.yahoo.com/group/bloggerDev/
1563       */
1564  
1565      /**
1566       * Retrieve blogs that user owns.
1567       *
1568       * Will make more sense once we support multiple blogs.
1569       *
1570       * @since 1.5.0
1571       *
1572       * @param array $args Method parameters.
1573       * @return array
1574       */
1575  	function blogger_getUsersBlogs($args) {
1576  
1577          $this->escape($args);
1578  
1579          $user_login = $args[1];
1580          $user_pass  = $args[2];
1581  
1582          if (!$this->login_pass_ok($user_login, $user_pass)) {
1583              return $this->error;
1584          }
1585  
1586          do_action('xmlrpc_call', 'blogger.getUsersBlogs');
1587  
1588          set_current_user(0, $user_login);
1589          $is_admin = current_user_can('manage_options');
1590  
1591          $struct = array(
1592              'isAdmin'  => $is_admin,
1593              'url'      => get_option('home') . '/',
1594              'blogid'   => '1',
1595              'blogName' => get_option('blogname'),
1596              'xmlrpc'   => get_option('home') . '/xmlrpc.php',
1597          );
1598  
1599          return array($struct);
1600      }
1601  
1602      /**
1603       * Retrieve user's data.
1604       *
1605       * Gives your client some info about you, so you don't have to.
1606       *
1607       * @since 1.5.0
1608       *
1609       * @param array $args Method parameters.
1610       * @return array
1611       */
1612  	function blogger_getUserInfo($args) {
1613  
1614          $this->escape($args);
1615  
1616          $user_login = $args[1];
1617          $user_pass  = $args[2];
1618  
1619          if (!$this->login_pass_ok($user_login, $user_pass)) {
1620              return $this->error;
1621          }
1622  
1623          set_current_user( 0, $user_login );
1624          if( !current_user_can( 'edit_posts' ) )
1625              return new IXR_Error( 401, __( 'Sorry, you do not have access to user data on this blog.' ) );
1626  
1627          do_action('xmlrpc_call', 'blogger.getUserInfo');
1628  
1629          $user_data = get_userdatabylogin($user_login);
1630  
1631          $struct = array(
1632              'nickname'  => $user_data->nickname,
1633              'userid'    => $user_data->ID,
1634              'url'       => $user_data->user_url,
1635              'lastname'  => $user_data->last_name,
1636              'firstname' => $user_data->first_name
1637          );
1638  
1639          return $struct;
1640      }
1641  
1642      /**
1643       * Retrieve post.
1644       *
1645       * @since 1.5.0
1646       *
1647       * @param array $args Method parameters.
1648       * @return array
1649       */
1650  	function blogger_getPost($args) {
1651  
1652          $this->escape($args);
1653  
1654          $post_ID    = (int) $args[1];
1655          $user_login = $args[2];
1656          $user_pass  = $args[3];
1657  
1658          if (!$this->login_pass_ok($user_login, $user_pass)) {
1659              return $this->error;
1660          }
1661  
1662          set_current_user( 0, $user_login );
1663          if( !current_user_can( 'edit_post', $post_ID ) )
1664              return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
1665  
1666          do_action('xmlrpc_call', 'blogger.getPost');
1667  
1668          $post_data = wp_get_single_post($post_ID, ARRAY_A);
1669  
1670          $categories = implode(',', wp_get_post_categories($post_ID));
1671  
1672          $content  = '<title>'.stripslashes($post_data['post_title']).'</title>';
1673          $content .= '<category>'.$categories.'</category>';
1674          $content .= stripslashes($post_data['post_content']);
1675  
1676          $struct = array(
1677              'userid'    => $post_data['post_author'],
1678              'dateCreated' => new IXR_Date(mysql2date('Ymd\TH:i:s', $post_data['post_date'])),
1679              'content'     => $content,
1680              'postid'  => $post_data['ID']
1681          );
1682  
1683          return $struct;
1684      }
1685  
1686      /**
1687       * Retrieve list of recent posts.
1688       *
1689       * @since 1.5.0
1690       *
1691       * @param array $args Method parameters.
1692       * @return array
1693       */
1694  	function blogger_getRecentPosts($args) {
1695  
1696          $this->escape($args);
1697  
1698          $blog_ID    = (int) $args[1]; /* though we don't use it yet */
1699          $user_login = $args[2];
1700          $user_pass  = $args[3];
1701          $num_posts  = $args[4];
1702  
1703          if (!$this->login_pass_ok($user_login, $user_pass)) {
1704              return $this->error;
1705          }
1706  
1707          do_action('xmlrpc_call', 'blogger.getRecentPosts');
1708  
1709          $posts_list = wp_get_recent_posts($num_posts);
1710  
1711          set_current_user( 0, $user_login );
1712  
1713          if (!$posts_list) {
1714              $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
1715              return $this->error;
1716          }
1717  
1718          foreach ($posts_list as $entry) {
1719              if( !current_user_can( 'edit_post', $entry['ID'] ) )
1720                  continue;
1721  
1722              $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
1723              $categories = implode(',', wp_get_post_categories($entry['ID']));
1724  
1725              $content  = '<title>'.stripslashes($entry['post_title']).'</title>';
1726              $content .= '<category>'.$categories.'</category>';
1727              $content .= stripslashes($entry['post_content']);
1728  
1729              $struct[] = array(
1730                  'userid' => $entry['post_author'],
1731                  'dateCreated' => new IXR_Date($post_date),
1732                  'content' => $content,
1733                  'postid' => $entry['ID'],
1734              );
1735  
1736          }
1737  
1738          $recent_posts = array();
1739          for ($j=0; $j<count($struct); $j++) {
1740              array_push($recent_posts, $struct[$j]);
1741          }
1742  
1743          return $recent_posts;
1744      }
1745  
1746      /**
1747       * Retrieve blog_filename content.
1748       *
1749       * @since 1.5.0
1750       *
1751       * @param array $args Method parameters.
1752       * @return string
1753       */
1754  	function blogger_getTemplate($args) {
1755  
1756          $this->escape($args);
1757  
1758          $blog_ID    = (int) $args[1];
1759          $user_login = $args[2];
1760          $user_pass  = $args[3];
1761          $template   = $args[4]; /* could be 'main' or 'archiveIndex', but we don't use it */
1762  
1763          if (!$this->login_pass_ok($user_login, $user_pass)) {
1764              return $this->error;
1765          }
1766  
1767          do_action('xmlrpc_call', 'blogger.getTemplate');
1768  
1769          set_current_user(0, $user_login);
1770          if ( !current_user_can('edit_themes') ) {
1771              return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
1772          }
1773  
1774          /* warning: here we make the assumption that the blog's URL is on the same server */
1775          $filename = get_option('home') . '/';
1776          $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
1777  
1778          $f = fopen($filename, 'r');
1779          $content = fread($f, filesize($filename));
1780          fclose($f);
1781  
1782          /* so it is actually editable with a windows/mac client */
1783          // FIXME: (or delete me) do we really want to cater to bad clients at the expense of good ones by BEEPing up their line breaks? commented.     $content = str_replace("\n", "\r\n", $content);
1784  
1785          return $content;
1786      }
1787  
1788      /**
1789       * Updates the content of blog_filename.
1790       *
1791       * @since 1.5.0
1792       *
1793       * @param array $args Method parameters.
1794       * @return bool True when done.
1795       */
1796  	function blogger_setTemplate($args) {
1797  
1798          $this->escape($args);
1799  
1800          $blog_ID    = (int) $args[1];
1801          $user_login = $args[2];
1802          $user_pass  = $args[3];
1803          $content    = $args[4];
1804          $template   = $args[5]; /* could be 'main' or 'archiveIndex', but we don't use it */
1805  
1806          if (!$this->login_pass_ok($user_login, $user_pass)) {
1807              return $this->error;
1808          }
1809  
1810          do_action('xmlrpc_call', 'blogger.setTemplate');
1811  
1812          set_current_user(0, $user_login);
1813          if ( !current_user_can('edit_themes') ) {
1814              return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
1815          }
1816  
1817          /* warning: here we make the assumption that the blog's URL is on the same server */
1818          $filename = get_option('home') . '/';
1819          $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
1820  
1821          if ($f = fopen($filename, 'w+')) {
1822              fwrite($f, $content);
1823              fclose($f);
1824          } else {
1825              return new IXR_Error(500, __('Either the file is not writable, or something wrong happened. The file has not been updated.'));
1826          }
1827  
1828          return true;
1829      }
1830  
1831      /**
1832       * Create new post.
1833       *
1834       * @since 1.5.0
1835       *
1836       * @param array $args Method parameters.
1837       * @return int
1838       */
1839  	function blogger_newPost($args) {
1840  
1841          $this->escape($args);
1842  
1843          $blog_ID    = (int) $args[1]; /* though we don't use it yet */
1844          $user_login = $args[2];
1845          $user_pass  = $args[3];
1846          $content    = $args[4];
1847          $publish    = $args[5];
1848  
1849          if (!$this->login_pass_ok($user_login, $user_pass)) {
1850              return $this->error;
1851          }
1852  
1853          do_action('xmlrpc_call', 'blogger.newPost');
1854  
1855          $cap = ($publish) ? 'publish_posts' : 'edit_posts';
1856          $user = set_current_user(0, $user_login);
1857          if ( !current_user_can($cap) )
1858              return new IXR_Error(401, __('Sorry, you are not allowed to post on this blog.'));
1859  
1860          $post_status = ($publish) ? 'publish' : 'draft';
1861  
1862          $post_author = $user->ID;
1863  
1864          $post_title = xmlrpc_getposttitle($content);
1865          $post_category = xmlrpc_getpostcategory($content);
1866          $post_content = xmlrpc_removepostdata($content);
1867  
1868          $post_date = current_time('mysql');
1869          $post_date_gmt = current_time('mysql', 1);
1870  
1871          $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status');
1872  
1873          $post_ID = wp_insert_post($post_data);
1874          if ( is_wp_error( $post_ID ) )
1875              return new IXR_Error(500, $post_ID->get_error_message());
1876  
1877          if (!$post_ID)
1878              return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
1879  
1880          $this->attach_uploads( $post_ID, $post_content );
1881  
1882          logIO('O', "Posted ! ID: $post_ID");
1883  
1884          return $post_ID;
1885      }
1886  
1887      /**
1888       * Edit a post.
1889       *
1890       * @since 1.5.0
1891       *
1892       * @param array $args Method parameters.
1893       * @return bool true when done.
1894       */
1895  	function blogger_editPost($args) {
1896  
1897          $this->escape($args);
1898  
1899          $post_ID     = (int) $args[1];
1900          $user_login  = $args[2];
1901          $user_pass   = $args[3];
1902          $content     = $args[4];
1903          $publish     = $args[5];
1904  
1905          if (!$this->login_pass_ok($user_login, $user_pass)) {
1906              return $this->error;
1907          }
1908  
1909          do_action('xmlrpc_call', 'blogger.editPost');
1910  
1911          $actual_post = wp_get_single_post($post_ID,ARRAY_A);
1912  
1913          if (!$actual_post || $actual_post['post_type'] != 'post') {
1914              return new IXR_Error(404, __('Sorry, no such post.'));
1915          }
1916  
1917          $this->escape($actual_post);
1918  
1919          set_current_user(0, $user_login);
1920          if ( !current_user_can('edit_post', $post_ID) )
1921              return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.'));
1922  
1923          extract($actual_post, EXTR_SKIP);
1924  
1925          if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
1926              return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
1927  
1928          $post_title = xmlrpc_getposttitle($content);
1929          $post_category = xmlrpc_getpostcategory($content);
1930          $post_content = xmlrpc_removepostdata($content);
1931  
1932          $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
1933  
1934          $result = wp_update_post($postdata);
1935  
1936          if (!$result) {
1937              return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be edited.'));
1938          }
1939          $this->attach_uploads( $ID, $post_content );
1940  
1941          return true;
1942      }
1943  
1944      /**
1945       * Remove a post.
1946       *
1947       * @since 1.5.0
1948       *
1949       * @param array $args Method parameters.
1950       * @return bool True when post is deleted.
1951       */
1952  	function blogger_deletePost($args) {
1953          $this->escape($args);
1954  
1955          $post_ID     = (int) $args[1];
1956          $user_login  = $args[2];
1957          $user_pass   = $args[3];
1958          $publish     = $args[4];
1959  
1960          if (!$this->login_pass_ok($user_login, $user_pass)) {
1961              return $this->error;
1962          }
1963  
1964          do_action('xmlrpc_call', 'blogger.deletePost');
1965  
1966          $actual_post = wp_get_single_post($post_ID,ARRAY_A);
1967  
1968          if (!$actual_post || $actual_post['post_type'] != 'post') {
1969              return new IXR_Error(404, __('Sorry, no such post.'));
1970          }
1971  
1972          set_current_user(0, $user_login);
1973          if ( !current_user_can('edit_post', $post_ID) )
1974              return new IXR_Error(401, __('Sorry, you do not have the right to delete this post.'));
1975  
1976          $result = wp_delete_post($post_ID);
1977  
1978          if (!$result) {
1979              return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be deleted.'));
1980          }
1981  
1982          return true;
1983      }
1984  
1985      /* MetaWeblog API functions
1986       * specs on wherever Dave Winer wants them to be
1987       */
1988  
1989      /**
1990       * Create a new post.
1991       *
1992       * @since 1.5.0
1993       *
1994       * @param array $args Method parameters.
1995       * @return int
1996       */
1997  	function mw_newPost($args) {
1998          $this->escape($args);
1999  
2000          $blog_ID     = (int) $args[0]; // we will support this in the near future
2001          $user_login  = $args[1];
2002          $user_pass   = $args[2];
2003          $content_struct = $args[3];
2004          $publish     = $args[4];
2005  
2006          if (!$this->login_pass_ok($user_login, $user_pass)) {
2007              return $this->error;
2008          }
2009          $user = set_current_user(0, $user_login);
2010  
2011          do_action('xmlrpc_call', 'metaWeblog.newPost');
2012  
2013          $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
2014          $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' );
2015          $post_type = 'post';
2016          $page_template = '';
2017          if( !empty( $content_struct['post_type'] ) ) {
2018              if( $content_struct['post_type'] == 'page' ) {
2019                  $cap = ( $publish ) ? 'publish_pages' : 'edit_pages';
2020                  $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' );
2021                  $post_type = 'page';
2022                  if( !empty( $content_struct['wp_page_template'] ) )
2023                      $page_template = $content_struct['wp_page_template'];
2024              }
2025              elseif( $content_struct['post_type'] == 'post' ) {
2026                  // This is the default, no changes needed
2027              }
2028              else {
2029                  // No other post_type values are allowed here
2030                  return new IXR_Error( 401, __( 'Invalid post type.' ) );
2031              }
2032          }
2033  
2034          if( !current_user_can( $cap ) ) {
2035              return new IXR_Error( 401, $error_message );
2036          }
2037  
2038          // Let WordPress generate the post_name (slug) unless
2039          // one has been provided.
2040          $post_name = "";
2041          if(isset($content_struct["wp_slug"])) {
2042              $post_name = $content_struct["wp_slug"];
2043          }
2044  
2045          // Only use a password if one was given.
2046          if(isset($content_struct["wp_password"])) {
2047              $post_password = $content_struct["wp_password"];
2048          }
2049  
2050          // Only set a post parent if one was provided.
2051          if(isset($content_struct["wp_page_parent_id"])) {
2052              $post_parent = $content_struct["wp_page_parent_id"];
2053          }
2054  
2055          // Only set the menu_order if it was provided.
2056          if(isset($content_struct["wp_page_order"])) {
2057              $menu_order = $content_struct["wp_page_order"];
2058          }
2059  
2060          $post_author = $user->ID;
2061  
2062          // If an author id was provided then use it instead.
2063          if(
2064              isset($content_struct["wp_author_id"])
2065              && ($user->ID != $content_struct["wp_author_id"])
2066          ) {
2067              switch($post_type) {
2068                  case "post":
2069                      if(!current_user_can("edit_others_posts")) {
2070                          return(new IXR_Error(401, __("You are not allowed to post as this user")));
2071                      }
2072                      break;
2073                  case "page":
2074                      if(!current_user_can("edit_others_pages")) {
2075                          return(new IXR_Error(401, __("You are not allowed to create pages as this user")));
2076                      }
2077                      break;
2078                  default:
2079                      return(new IXR_Error(401, __("Invalid post type.")));
2080                      break;
2081              }
2082              $post_author = $content_struct["wp_author_id"];
2083          }
2084  
2085          $post_title = $content_struct['title'];
2086          $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
2087  
2088          $post_status = $publish ? 'publish' : 'draft';
2089  
2090          if( isset( $content_struct["{$post_type}_status"] ) ) {
2091              switch( $content_struct["{$post_type}_status"] ) {
2092                  case 'draft':
2093                  case 'private':
2094                  case 'publish':
2095                      $post_status = $content_struct["{$post_type}_status"];
2096                      break;
2097                  case 'pending':
2098                      // Pending is only valid for posts, not pages.
2099                      if( $post_type === 'post' ) {
2100                          $post_status = $content_struct["{$post_type}_status"];
2101                      }
2102                      break;
2103                  default:
2104                      $post_status = $publish ? 'publish' : 'draft';
2105                      break;
2106              }
2107          }
2108  
2109          $post_excerpt = $content_struct['mt_excerpt'];
2110          $post_more = $content_struct['mt_text_more'];
2111  
2112          $tags_input = $content_struct['mt_keywords'];
2113  
2114          if(isset($content_struct["mt_allow_comments"])) {
2115              if(!is_numeric($content_struct["mt_allow_comments"])) {
2116                  switch($content_struct["mt_allow_comments"]) {
2117                      case "closed":
2118                          $comment_status = "closed";
2119                          break;
2120                      case "open":
2121                          $comment_status = "open";
2122                          break;
2123                      default:
2124                          $comment_status = get_option("default_comment_status");
2125                          break;
2126                  }
2127              }
2128              else {
2129                  switch((int) $content_struct["mt_allow_comments"]) {
2130                      case 0:
2131                      case 2:
2132                          $comment_status = "closed";
2133                          break;
2134                      case 1:
2135                          $comment_status = "open";
2136                          break;
2137                      default:
2138                          $comment_status = get_option("default_comment_status");
2139                          break;
2140                  }
2141              }
2142          }
2143          else {
2144              $comment_status = get_option("default_comment_status");
2145          }
2146  
2147          if(isset($content_struct["mt_allow_pings"])) {
2148              if(!is_numeric($content_struct["mt_allow_pings"])) {
2149                  switch($content_struct['mt_allow_pings']) {
2150                      case "closed":
2151                          $ping_status = "closed";
2152                          break;
2153                      case "open":
2154                          $ping_status = "open";
2155                          break;
2156                      default:
2157                          $ping_status = get_option("default_ping_status");
2158                          break;
2159                  }
2160              }
2161              else {
2162                  switch((int) $content_struct["mt_allow_pings"]) {
2163                      case 0:
2164                          $ping_status = "closed";
2165                          break;
2166                      case 1:
2167                          $ping_status = "open";
2168                          break;
2169                      default:
2170                          $ping_status = get_option("default_ping_status");
2171                          break;
2172                  }
2173              }
2174          }
2175          else {
2176              $ping_status = get_option("default_ping_status");
2177          }
2178  
2179          if ($post_more) {
2180              $post_content = $post_content . "<!--more-->" . $post_more;
2181          }
2182  
2183          $to_ping = $content_struct['mt_tb_ping_urls'];
2184          if ( is_array($to_ping) )
2185              $to_ping = implode(' ', $to_ping);
2186  
2187          // Do some timestamp voodoo
2188          if ( !empty( $content_struct['date_created_gmt'] ) )
2189              $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force
2190          elseif ( !empty( $content_struct['dateCreated']) )
2191              $dateCreated = $content_struct['dateCreated']->getIso();
2192  
2193          if ( !empty( $dateCreated ) ) {
2194              $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
2195              $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
2196          } else {
2197              $post_date = current_time('mysql');
2198              $post_date_gmt = current_time('mysql', 1);
2199          }
2200  
2201          $catnames = $content_struct['categories'];
2202          logIO('O', 'Post cats: ' . var_export($catnames,true));
2203          $post_category = array();
2204  
2205          if (is_array($catnames)) {
2206              foreach ($catnames as $cat) {
2207                  $post_category[] = get_cat_ID($cat);
2208              }
2209          }
2210  
2211          // We've got all the data -- post it:
2212          $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping', 'post_type', 'post_name', 'post_password', 'post_parent', 'menu_order', 'tags_input', 'page_template');
2213  
2214          $post_ID = wp_insert_post($postdata, true);
2215          if ( is_wp_error( $post_ID ) )
2216              return new IXR_Error(500, $post_ID->get_error_message());
2217  
2218          if (!$post_ID) {
2219              return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
2220          }
2221  
2222          if ( isset($content_struct['custom_fields']) ) {
2223              $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
2224          }
2225  
2226          // Handle enclosures
2227          $enclosure = $content_struct['enclosure'];
2228          if( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
2229              add_post_meta( $post_ID, 'enclosure', $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'] );
2230          }
2231  
2232          $this->attach_uploads( $post_ID, $post_content );
2233  
2234          logIO('O', "Posted ! ID: $post_ID");
2235  
2236          return strval($post_ID);
2237      }
2238  
2239      /**
2240       * Attach upload to a post.
2241       *
2242       * @since 2.1.0
2243       *
2244       * @param int $post_ID Post ID.
2245       * @param string $post_content Post Content for attachment.
2246       */
2247  	function attach_uploads( $post_ID, $post_content ) {
2248          global $wpdb;
2249  
2250          // find any unattached files
2251          $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '-1' AND post_type = 'attachment'" );
2252          if( is_array( $attachments ) ) {
2253              foreach( $attachments as $file ) {
2254                  if( strpos( $post_content, $file->guid ) !== false ) {
2255                      $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_parent = %d WHERE ID = %d", $post_ID, $file->ID) );
2256                  }
2257              }
2258          }
2259      }
2260  
2261      /**
2262       * Edit a post.
2263       *
2264       * @since 1.5.0
2265       *
2266       * @param array $args Method parameters.
2267       * @return bool True on success.
2268       */
2269  	function mw_editPost($args) {
2270  
2271          $this->escape($args);
2272  
2273          $post_ID     = (int) $args[0];
2274          $user_login  = $args[1];
2275          $user_pass   = $args[2];
2276          $content_struct = $args[3];
2277          $publish     = $args[4];
2278  
2279          if (!$this->login_pass_ok($user_login, $user_pass)) {
2280              return $this->error;
2281          }
2282          $user = set_current_user(0, $user_login);
2283  
2284          do_action('xmlrpc_call', 'metaWeblog.editPost');
2285  
2286          $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
2287          $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' );
2288          $post_type = 'post';
2289          $page_template = '';
2290          if( !empty( $content_struct['post_type'] ) ) {
2291              if( $content_struct['post_type'] == 'page' ) {
2292                  $cap = ( $publish ) ? 'publish_pages' : 'edit_pages';
2293                  $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' );
2294                  $post_type = 'page';
2295                  if( !empty( $content_struct['wp_page_template'] ) )
2296                      $page_template = $content_struct['wp_page_template'];
2297              }
2298              elseif( $content_struct['post_type'] == 'post' ) {
2299                  // This is the default, no changes needed
2300              }
2301              else {
2302                  // No other post_type values are allowed here
2303                  return new IXR_Error( 401, __( 'Invalid post type.' ) );
2304              }
2305          }
2306  
2307          if( !current_user_can( $cap ) ) {
2308              return new IXR_Error( 401, $error_message );
2309          }
2310  
2311          $postdata = wp_get_single_post($post_ID, ARRAY_A);
2312  
2313          // If there is no post data for the give post id, stop
2314          // now and return an error.  Other wise a new post will be
2315          // created (which was the old behavior).
2316          if(empty($postdata["ID"])) {
2317              return(new IXR_Error(404, __("Invalid post id.")));
2318          }
2319  
2320          $this->escape($postdata);
2321          extract($postdata, EXTR_SKIP);
2322  
2323          // Let WordPress manage slug if none was provided.
2324          $post_name = "";
2325          if(isset($content_struct["wp_slug"])) {
2326              $post_name = $content_struct["wp_slug"];
2327          }
2328  
2329          // Only use a password if one was given.
2330          if(isset($content_struct["wp_password"])) {
2331              $post_password = $content_struct["wp_password"];
2332          }
2333  
2334          // Only set a post parent if one was given.
2335          if(isset($content_struct["wp_page_parent_id"])) {
2336              $post_parent = $content_struct["wp_page_parent_id"];
2337          }
2338  
2339          // Only set the menu_order if it was given.
2340          if(isset($content_struct["wp_page_order"])) {
2341              $menu_order = $content_struct["wp_page_order"];
2342          }
2343  
2344          $post_author = $postdata["post_author"];
2345  
2346          // Only set the post_author if one is set.
2347          if(
2348              isset($content_struct["wp_author_id"])
2349              && ($user->ID != $content_struct["wp_author_id"])
2350          ) {
2351              switch($post_type) {
2352                  case "post":
2353                      if(!current_user_can("edit_others_posts")) {
2354                          return(new IXR_Error(401, __("You are not allowed to change the post author as this user.")));
2355                      }
2356                      break;
2357                  case "page":
2358                      if(!current_user_can("edit_others_pages")) {
2359                          return(new IXR_Error(401, __("You are not allowed to change the page author as this user.")));
2360                      }
2361                      break;
2362                  default:
2363                      return(new IXR_Error(401, __("Invalid post type.")));
2364                      break;
2365              }
2366              $post_author = $content_struct["wp_author_id"];
2367          }
2368  
2369          if(isset($content_struct["mt_allow_comments"])) {
2370              if(!is_numeric($content_struct["mt_allow_comments"])) {
2371                  switch($content_struct["mt_allow_comments"]) {
2372                      case "closed":
2373                          $comment_status = "closed";
2374                          break;
2375                      case "open":
2376                          $comment_status = "open";
2377                          break;
2378                      default:
2379                          $comment_status = get_option("default_comment_status");
2380                          break;
2381                  }
2382              }
2383              else {
2384                  switch((int) $content_struct["mt_allow_comments"]) {
2385                      case 0:
2386                      case 2:
2387                          $comment_status = "closed";
2388                          break;
2389                      case 1:
2390                          $comment_status = "open";
2391                          break;
2392                      default:
2393                          $comment_status = get_option("default_comment_status");
2394                          break;
2395                  }
2396              }
2397          }
2398  
2399          if(isset($content_struct["mt_allow_pings"])) {
2400              if(!is_numeric($content_struct["mt_allow_pings"])) {
2401                  switch($content_struct["mt_allow_pings"]) {
2402                      case "closed":
2403                          $ping_status = "closed";
2404                          break;
2405                      case "open":
2406                          $ping_status = "open";
2407                          break;
2408                      default:
2409                          $ping_status = get_option("default_ping_status");
2410                          break;
2411                  }
2412              }
2413              else {
2414                  switch((int) $content_struct["mt_allow_pings"]) {
2415                      case 0:
2416                          $ping_status = "closed";
2417                          break;
2418                      case 1:
2419                          $ping_status = "open";
2420                          break;
2421                      default:
2422                          $ping_status = get_option("default_ping_status");
2423                          break;
2424                  }
2425              }
2426          }
2427  
2428          $post_title = $content_struct['title'];
2429          $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
2430          $catnames = $content_struct['categories'];
2431  
2432          $post_category = array();
2433  
2434          if (is_array($catnames)) {
2435              foreach ($catnames as $cat) {
2436                   $post_category[] = get_cat_ID($cat);
2437              }
2438          }
2439  
2440          $post_excerpt = $content_struct['mt_excerpt'];
2441          $post_more = $content_struct['mt_text_more'];
2442  
2443          $post_status = $publish ? 'publish' : 'draft';
2444          if( isset( $content_struct["{$post_type}_status"] ) ) {
2445              switch( $content_struct["{$post_type}_status"] ) {
2446                  case 'draft':
2447                  case 'private':
2448                  case 'publish':
2449                      $post_status = $content_struct["{$post_type}_status"];
2450                      break;
2451                  case 'pending':
2452                      // Pending is only valid for posts, not pages.
2453                      if( $post_type === 'post' ) {
2454                          $post_status = $content_struct["{$post_type}_status"];
2455                      }
2456                      break;
2457                  default:
2458                      $post_status = $publish ? 'publish' : 'draft';
2459                      break;
2460              }
2461          }
2462  
2463          $tags_input = $content_struct['mt_keywords'];
2464  
2465          if ( ('publish' == $post_status) ) {
2466              if ( ( 'page' == $post_type ) && !current_user_can('publish_pages') )
2467                  return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.'));
2468              else if ( !current_user_can('publish_posts') )
2469                  return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
2470          }
2471  
2472          if ($post_more) {
2473              $post_content = $post_content . "<!--more-->" . $post_more;
2474          }
2475  
2476          $to_ping = $content_struct['mt_tb_ping_urls'];
2477          if ( is_array($to_ping) )
2478              $to_ping = implode(' ', $to_ping);
2479  
2480          // Do some timestamp voodoo
2481          if ( !empty( $content_struct['date_created_gmt'] ) )
2482              $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force
2483          elseif ( !empty( $content_struct['dateCreated']) )
2484              $dateCreated = $content_struct['dateCreated']->getIso();
2485  
2486          if ( !empty( $dateCreated ) ) {
2487              $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
2488              $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
2489          } else {
2490              $post_date     = $postdata['post_date'];
2491              $post_date_gmt = $postdata['post_date_gmt'];
2492          }
2493  
2494          // We've got all the data -- post it:
2495          $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template');
2496  
2497          $result = wp_update_post($newpost, true);
2498          if ( is_wp_error( $result ) )
2499              return new IXR_Error(500, $result->get_error_message());
2500  
2501          if (!$result) {
2502              return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.'));
2503          }
2504  
2505          if ( isset($content_struct['custom_fields']) ) {
2506              $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
2507          }
2508  
2509          // Handle enclosures
2510          $enclosure = $content_struct['enclosure'];
2511          if( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
2512              add_post_meta( $post_ID, 'enclosure', $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'] );
2513          }
2514  
2515          $this->attach_uploads( $ID, $post_content );
2516  
2517          logIO('O',"(MW) Edited ! ID: $post_ID");
2518  
2519          return true;
2520      }
2521  
2522      /**
2523       * Retrieve post.
2524       *
2525       * @since 1.5.0
2526       *
2527       * @param array $args Method parameters.
2528       * @return array
2529       */
2530  	function mw_getPost($args) {
2531  
2532          $this->escape($args);
2533  
2534          $post_ID     = (int) $args[0];
2535          $user_login  = $args[1];
2536          $user_pass   = $args[2];
2537  
2538          if (!$this->login_pass_ok($user_login, $user_pass)) {
2539              return $this->error;
2540          }
2541  
2542          set_current_user( 0, $user_login );
2543          if( !current_user_can( 'edit_post', $post_ID ) )
2544              return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
2545  
2546          do_action('xmlrpc_call', 'metaWeblog.getPost');
2547  
2548          $postdata = wp_get_single_post($post_ID, ARRAY_A);
2549  
2550          if ($postdata['post_date'] != '') {
2551              $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date']);
2552              $post_date_gmt = mysql2date('Ymd\TH:i:s', $postdata['post_date_gmt']);
2553  
2554              $categories = array();
2555              $catids = wp_get_post_categories($post_ID);
2556              foreach($catids as $catid)
2557                  $categories[] = get_cat_name($catid);
2558  
2559              $tagnames = array();
2560              $tags = wp_get_post_tags( $post_ID );
2561              if ( !empty( $tags ) ) {
2562                  foreach ( $tags as $tag )
2563                      $tagnames[] = $tag->name;
2564                  $tagnames = implode( ', ', $tagnames );
2565              } else {
2566                  $tagnames = '';
2567              }
2568  
2569              $post = get_extended($postdata['post_content']);
2570              $link = post_permalink($postdata['ID']);
2571  
2572              // Get the author info.
2573              $author = get_userdata($postdata['post_author']);
2574  
2575              $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
2576              $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0;
2577  
2578              // Consider future posts as published
2579              if( $postdata['post_status'] === 'future' ) {
2580                  $postdata['post_status'] = 'publish';
2581              }
2582  
2583              $enclosure = array();
2584              foreach ( (array) get_post_custom($post_ID) as $key => $val) {
2585                  if ($key == 'enclosure') {
2586                      foreach ( (array) $val as $enc ) {
2587                          $encdata = split("\n", $enc);
2588                          $enclosure['url'] = trim(htmlspecialchars($encdata[0]));
2589                          $enclosure['length'] = trim($encdata[1]);
2590                          $enclosure['type'] = trim($encdata[2]);
2591                          break 2;
2592                      }
2593                  }
2594              }
2595  
2596              $resp = array(
2597                  'dateCreated' => new IXR_Date($post_date),
2598                  'userid' => $postdata['post_author'],
2599                  'postid' => $postdata['ID'],
2600                  'description' => $post['main'],
2601                  'title' => $postdata['post_title'],
2602                  'link' => $link,
2603                  'permaLink' => $link,
2604                  // commented out because no other tool seems to use this
2605                  //          'content' => $entry['post_content'],
2606                  'categories' => $categories,
2607                  'mt_excerpt' => $postdata['post_excerpt'],
2608                  'mt_text_more' => $post['extended'],
2609                  'mt_allow_comments' => $allow_comments,
2610                  'mt_allow_pings' => $allow_pings,
2611                  'mt_keywords' => $tagnames,
2612                  'wp_slug' => $postdata['post_name'],
2613                  'wp_password' => $postdata['post_password'],
2614                  'wp_author_id' => $author->ID,
2615                  'wp_author_display_name'    => $author->display_name,
2616                  'date_created_gmt' => new IXR_Date($post_date_gmt),
2617                  'post_status' => $postdata['post_status'],
2618                  'custom_fields' => $this->get_custom_fields($post_ID)
2619              );
2620  
2621              if (!empty($enclosure)) $resp['enclosure'] = $enclosure;
2622  
2623              return $resp;
2624          } else {
2625              return new IXR_Error(404, __('Sorry, no such post.'));
2626          }
2627      }
2628  
2629      /**
2630       * Retrieve list of recent posts.
2631       *
2632       * @since 1.5.0
2633       *
2634       * @param array $args Method parameters.
2635       * @return array
2636       */
2637  	function mw_getRecentPosts($args) {
2638  
2639          $this->escape($args);
2640  
2641          $blog_ID     = (int) $args[0];
2642          $user_login  = $args[1];
2643          $user_pass   = $args[2];
2644          $num_posts   = (int) $args[3];
2645  
2646          if (!$this->login_pass_ok($user_login, $user_pass)) {
2647              return $this->error;
2648          }
2649  
2650          do_action('xmlrpc_call', 'metaWeblog.getRecentPosts');
2651  
2652          $posts_list = wp_get_recent_posts($num_posts);
2653  
2654          if (!$posts_list) {
2655              return array( );
2656          }
2657  
2658          set_current_user( 0, $user_login );
2659  
2660          foreach ($posts_list as $entry) {
2661              if( !current_user_can( 'edit_post', $entry['ID'] ) )
2662                  continue;
2663  
2664              $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
2665              $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
2666  
2667              $categories = array();
2668              $catids = wp_get_post_categories($entry['ID']);
2669              foreach($catids as $catid) {
2670                  $categories[] = get_cat_name($catid);
2671              }
2672  
2673              $tagnames = array();
2674              $tags = wp_get_post_tags( $entry['ID'] );
2675              if ( !empty( $tags ) ) {
2676                  foreach ( $tags as $tag ) {
2677                      $tagnames[] = $tag->name;
2678                  }
2679                  $tagnames = implode( ', ', $tagnames );
2680              } else {
2681                  $tagnames = '';
2682              }
2683  
2684              $post = get_extended($entry['post_content']);
2685              $link = post_permalink($entry['ID']);
2686  
2687              // Get the post author info.
2688              $author = get_userdata($entry['post_author']);
2689  
2690              $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
2691              $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0;
2692  
2693              // Consider future posts as published
2694              if( $entry['post_status'] === 'future' ) {
2695                  $entry['post_status'] = 'publish';
2696              }
2697  
2698              $struct[] = array(
2699                  'dateCreated' => new IXR_Date($post_date),
2700                  'userid' => $entry['post_author'],
2701                  'postid' => $entry['ID'],
2702                  'description' => $post['main'],
2703                  'title' => $entry['post_title'],
2704                  'link' => $link,
2705                  'permaLink' => $link,
2706                  // commented out because no other tool seems to use this
2707                  // 'content' => $entry['post_content'],
2708                  'categories' => $categories,
2709                  'mt_excerpt' => $entry['post_excerpt'],
2710                  'mt_text_more' => $post['extended'],
2711                  'mt_allow_comments' => $allow_comments,
2712                  'mt_allow_pings' => $allow_pings,
2713                  'mt_keywords' => $tagnames,
2714                  'wp_slug' => $entry['post_name'],
2715                  'wp_password' => $entry['post_password'],
2716                  'wp_author_id' => $author->ID,
2717                  'wp_author_display_name' => $author->display_name,
2718                  'date_created_gmt' => new IXR_Date($post_date_gmt),
2719                  'post_status' => $entry['post_status'],
2720                  'custom_fields' => $this->get_custom_fields($entry['ID'])
2721              );
2722  
2723          }
2724  
2725          $recent_posts = array();
2726          for ($j=0; $j<count($struct); $j++) {
2727              array_push($recent_posts, $struct[$j]);
2728          }
2729  
2730          return $recent_posts;
2731      }
2732  
2733      /**
2734       * Retrieve the list of categories on a given blog.
2735       *
2736       * @since 1.5.0
2737       *
2738       * @param array $args Method parameters.
2739       * @return array
2740       */
2741  	function mw_getCategories($args) {
2742  
2743          $this->escape($args);
2744  
2745          $blog_ID     = (int) $args[0];
2746          $user_login  = $args[1];
2747          $user_pass   = $args[2];
2748  
2749          if (!$this->login_pass_ok($user_login, $user_pass)) {
2750              return $this->error;
2751          }
2752  
2753          set_current_user( 0, $user_login );
2754          if( !current_user_can( 'edit_posts' ) )
2755              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
2756  
2757          do_action('xmlrpc_call', 'metaWeblog.getCategories');
2758  
2759          $categories_struct = array();
2760  
2761          if ( $cats = get_categories('get=all') ) {
2762              foreach ( $cats as $cat ) {
2763                  $struct['categoryId'] = $cat->term_id;
2764                  $struct['parentId'] = $cat->parent;
2765                  $struct['description'] = $cat->description;
2766                  $struct['categoryName'] = $cat->name;
2767                  $struct['htmlUrl'] = wp_specialchars(get_category_link($cat->term_id));
2768                  $struct['rssUrl'] = wp_specialchars(get_category_feed_link($cat->term_id, 'rss2'));
2769  
2770                  $categories_struct[] = $struct;
2771              }
2772          }
2773  
2774          return $categories_struct;
2775      }
2776  
2777      /**
2778       * Uploads a file, following your settings.
2779       *
2780       * Adapted from a patch by Johann Richard.
2781       *
2782       * @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
2783       *
2784       * @since 1.5.0
2785       *
2786       * @param array $args Method parameters.
2787       * @return array
2788       */
2789  	function mw_newMediaObject($args) {
2790          global $wpdb;
2791  
2792          $blog_ID     = (int) $args[0];
2793          $user_login  = $wpdb->escape($args[1]);
2794          $user_pass   = $wpdb->escape($args[2]);
2795          $data        = $args[3];
2796  
2797          $name = sanitize_file_name( $data['name'] );
2798          $type = $data['type'];
2799          $bits = $data['bits'];
2800  
2801          logIO('O', '(MW) Received '.strlen($bits).' bytes');
2802  
2803          if ( !$this->login_pass_ok($user_login, $user_pass) )
2804              return $this->error;
2805  
2806          do_action('xmlrpc_call', 'metaWeblog.newMediaObject');
2807  
2808          set_current_user(0, $user_login);
2809          if ( !current_user_can('upload_files') ) {
2810              logIO('O', '(MW) User does not have upload_files capability');
2811              $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
2812              return $this->error;
2813          }
2814  
2815          if ( $upload_err = apply_filters( "pre_upload_error", false ) )
2816              return new IXR_Error(500, $upload_err);
2817  
2818          if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
2819              // Get postmeta info on the object.
2820              $old_file = $wpdb->get_row("
2821                  SELECT ID
2822                  FROM {$wpdb->posts}
2823                  WHERE post_title = '{$name}'
2824                      AND post_type = 'attachment'
2825              ");
2826  
2827              // Delete previous file.
2828              wp_delete_attachment($old_file->ID);
2829  
2830              // Make sure the new name is different by pre-pending the
2831              // previous post id.
2832              $filename = preg_replace("/^wpid\d+-/", "", $name);
2833              $name = "wpid{$old_file->ID}-{$filename}";
2834          }
2835  
2836          $upload = wp_upload_bits($name, $type, $bits);
2837          if ( ! empty($upload['error']) ) {
2838              $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']);
2839              logIO('O', '(MW) ' . $errorString);
2840              return new IXR_Error(500, $errorString);
2841          }
2842          // Construct the attachment array
2843          // attach to post_id -1
2844          $post_id = -1;
2845          $attachment = array(
2846              'post_title' => $name,
2847              'post_content' => '',
2848              'post_type' => 'attachment',
2849              'post_parent' => $post_id,
2850              'post_mime_type' => $type,
2851              'guid' => $upload[ 'url' ]
2852          );
2853  
2854          // Save the data
2855          $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
2856          wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
2857  
2858          return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
2859      }
2860  
2861      /* MovableType API functions
2862       * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
2863       */
2864  
2865      /**
2866       * Retrieve the post titles of recent posts.
2867       *
2868       * @since 1.5.0
2869       *
2870       * @param array $args Method parameters.
2871       * @return array
2872       */
2873  	function mt_getRecentPostTitles($args) {
2874  
2875          $this->escape($args);
2876  
2877          $blog_ID     = (int) $args[0];
2878          $user_login  = $args[1];
2879          $user_pass   = $args[2];
2880          $num_posts   = (int) $args[3];
2881  
2882          if (!$this->login_pass_ok($user_login, $user_pass)) {
2883              return $this->error;
2884          }
2885  
2886          do_action('xmlrpc_call', 'mt.getRecentPostTitles');
2887  
2888          $posts_list = wp_get_recent_posts($num_posts);
2889  
2890          if (!$posts_list) {
2891              $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
2892              return $this->error;
2893          }
2894  
2895          set_current_user( 0, $user_login );
2896  
2897          foreach ($posts_list as $entry) {
2898              if( !current_user_can( 'edit_post', $entry['ID'] ) )
2899                  continue;
2900  
2901              $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
2902              $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
2903  
2904              $struct[] = array(
2905                  'dateCreated' => new IXR_Date($post_date),
2906                  'userid' => $entry['post_author'],
2907                  'postid' => $entry['ID'],
2908                  'title' => $entry['post_title'],
2909                  'date_created_gmt' => new IXR_Date($post_date_gmt)
2910              );
2911  
2912          }
2913  
2914          $recent_posts = array();
2915          for ($j=0; $j<count($struct); $j++) {
2916              array_push($recent_posts, $struct[$j]);
2917          }
2918  
2919          return $recent_posts;
2920      }
2921  
2922      /**
2923       * Retrieve list of all categories on blog.
2924       *
2925       * @since 1.5.0
2926       *
2927       * @param array $args Method parameters.
2928       * @return array
2929       */
2930  	function mt_getCategoryList($args) {
2931  
2932          $this->escape($args);
2933  
2934          $blog_ID     = (int) $args[0];
2935          $user_login  = $args[1];
2936          $user_pass   = $args[2];
2937  
2938          if (!$this->login_pass_ok($user_login, $user_pass)) {
2939              return $this->error;
2940          }
2941  
2942          set_current_user( 0, $user_login );
2943          if( !current_user_can( 'edit_posts' ) )
2944              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
2945  
2946          do_action('xmlrpc_call', 'mt.getCategoryList');
2947  
2948          $categories_struct = array();
2949  
2950          if ( $cats = get_categories('hide_empty=0&hierarchical=0') ) {
2951              foreach ($cats as $cat) {
2952                  $struct['categoryId'] = $cat->term_id;
2953                  $struct['categoryName'] = $cat->name;
2954  
2955                  $categories_struct[] = $struct;
2956              }
2957          }
2958  
2959          return $categories_struct;
2960      }
2961  
2962      /**
2963       * Retrieve post categories.
2964       *
2965       * @since 1.5.0
2966       *
2967       * @param array $args Method parameters.
2968       * @return array
2969       */
2970  	function mt_getPostCategories($args) {
2971  
2972          $this->escape($args);
2973  
2974          $post_ID     = (int) $args[0];
2975          $user_login  = $args[1];
2976          $user_pass   = $args[2];
2977  
2978          if (!$this->login_pass_ok($user_login, $user_pass)) {
2979              return $this->error;
2980          }
2981  
2982          set_current_user( 0, $user_login );
2983          if( !current_user_can( 'edit_post', $post_ID ) )
2984              return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
2985  
2986          do_action('xmlrpc_call', 'mt.getPostCategories');
2987  
2988          $categories = array();
2989          $catids = wp_get_post_categories(intval($post_ID));
2990          // first listed category will be the primary category
2991          $isPrimary = true;
2992          foreach($catids as $catid) {
2993              $categories[] = array(
2994                  'categoryName' => get_cat_name($catid),
2995                  'categoryId' => (string) $catid,
2996                  'isPrimary' => $isPrimary
2997              );
2998              $isPrimary = false;
2999          }
3000  
3001          return $categories;
3002      }
3003  
3004      /**
3005       * Sets categories for a post.
3006       *
3007       * @since 1.5.0
3008       *
3009       * @param array $args Method parameters.
3010       * @return bool True on success.
3011       */
3012  	function mt_setPostCategories($args) {
3013  
3014          $this->escape($args);
3015  
3016          $post_ID     = (int) $args[0];
3017          $user_login  = $args[1];
3018          $user_pass   = $args[2];
3019          $categories  = $args[3];
3020  
3021          if (!$this->login_pass_ok($user_login, $user_pass)) {
3022              return $this->error;
3023          }
3024  
3025          do_action('xmlrpc_call', 'mt.setPostCategories');
3026  
3027          set_current_user(0, $user_login);
3028          if ( !current_user_can('edit_post', $post_ID) )
3029              return new IXR_Error(401, __('Sorry, you can not edit this post.'));
3030  
3031          foreach($categories as $cat) {
3032              $catids[] = $cat['categoryId'];
3033          }
3034  
3035          wp_set_post_categories($post_ID, $catids);
3036  
3037          return true;
3038      }
3039  
3040      /**
3041       * Retrieve an array of methods supported by this server.
3042       *
3043       * @since 1.5.0
3044       *
3045       * @param array $args Method parameters.
3046       * @return array
3047       */
3048  	function mt_supportedMethods($args) {
3049  
3050          do_action('xmlrpc_call', 'mt.supportedMethods');
3051  
3052          $supported_methods = array();
3053          foreach($this->methods as $key=>$value) {
3054              $supported_methods[] = $key;
3055          }
3056  
3057          return $supported_methods;
3058      }
3059  
3060      /**
3061       * Retrieve an empty array because we don't support per-post text filters.
3062       *
3063       * @since 1.5.0
3064       *
3065       * @param array $args Method parameters.
3066       */
3067  	function mt_supportedTextFilters($args) {
3068          do_action('xmlrpc_call', 'mt.supportedTextFilters');
3069          return apply_filters('xmlrpc_text_filters', array());
3070      }
3071  
3072      /**
3073       * Retrieve trackbacks sent to a given post.
3074       *
3075       * @since 1.5.0
3076       *
3077       * @param array $args Method parameters.
3078       * @return mixed
3079       */
3080  	function mt_getTrackbackPings($args) {
3081  
3082          global $wpdb;
3083  
3084          $post_ID = intval($args);
3085  
3086          do_action('xmlrpc_call', 'mt.getTrackbackPings');
3087  
3088          $actual_post = wp_get_single_post($post_ID, ARRAY_A);
3089  
3090          if (!$actual_post) {
3091              return new IXR_Error(404, __('Sorry, no such post.'));
3092          }
3093  
3094          $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) );
3095  
3096          if (!$comments) {
3097              return array();
3098          }
3099  
3100          $trackback_pings = array();
3101          foreach($comments as $comment) {
3102              if ( 'trackback' == $comment->comment_type ) {
3103                  $content = $comment->comment_content;
3104                  $title = substr($content, 8, (strpos($content, '</strong>') - 8));
3105                  $trackback_pings[] = array(
3106                      'pingTitle' => $title,
3107                      'pingURL'   => $comment->comment_author_url,
3108                      'pingIP'    => $comment->comment_author_IP
3109                  );
3110          }
3111          }
3112  
3113          return $trackback_pings;
3114      }
3115  
3116      /**
3117       * Sets a post's publish status to 'publish'.
3118       *
3119       * @since 1.5.0
3120       *
3121       * @param array $args Method parameters.
3122       * @return int
3123       */
3124  	function mt_publishPost($args) {
3125  
3126          $this->escape($args);
3127  
3128          $post_ID     = (int) $args[0];
3129          $user_login  = $args[1];
3130          $user_pass   = $args[2];
3131  
3132          if (!$this->login_pass_ok($user_login, $user_pass)) {
3133              return $this->error;
3134          }
3135  
3136          do_action('xmlrpc_call', 'mt.publishPost');
3137  
3138          set_current_user(0, $user_login);
3139          if ( !current_user_can('edit_post', $post_ID) )
3140              return new IXR_Error(401, __('Sorry, you can not edit this post.'));
3141  
3142          $postdata = wp_get_single_post($post_ID,ARRAY_A);
3143  
3144          $postdata['post_status'] = 'publish';
3145  
3146          // retain old cats
3147          $cats = wp_get_post_categories($post_ID);
3148          $postdata['post_category'] = $cats;
3149          $this->escape($postdata);
3150  
3151          $result = wp_update_post($postdata);
3152  
3153          return $result;
3154      }
3155  
3156      /* PingBack functions
3157       * specs on www.hixie.ch/specs/pingback/pingback
3158       */
3159  
3160      /**
3161       * Retrieves a pingback and registers it.
3162       *
3163       * @since 1.5.0
3164       *
3165       * @param array $args Method parameters.
3166       * @return array
3167       */
3168  	function pingback_ping($args) {
3169          global $wpdb;
3170  
3171          do_action('xmlrpc_call', 'pingback.ping');
3172  
3173          $this->escape($args);
3174  
3175          $pagelinkedfrom = $args[0];
3176          $pagelinkedto   = $args[1];
3177  
3178          $title = '';
3179  
3180          $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
3181          $pagelinkedto = str_replace('&amp;', '&', $pagelinkedto);
3182          $pagelinkedto = str_replace('&', '&amp;', $pagelinkedto);
3183  
3184          // Check if the page linked to is in our site
3185          $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
3186          if( !$pos1 )
3187              return new IXR_Error(0, __('Is there no link to us?'));
3188  
3189          // let's find which post is linked to
3190          // FIXME: does url_to_postid() cover all these cases already?
3191          //        if so, then let's use it and drop the old code.
3192          $urltest = parse_url($pagelinkedto);
3193          if ($post_ID = url_to_postid($pagelinkedto)) {
3194              $way = 'url_to_postid()';
3195          } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
3196              // the path defines the post_ID (archives/p/XXXX)
3197              $blah = explode('/', $match[0]);
3198              $post_ID = (int) $blah[1];
3199              $way = 'from the path';
3200          } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
3201              // the querystring defines the post_ID (?p=XXXX)
3202              $blah = explode('=', $match[0]);
3203              $post_ID = (int) $blah[1];
3204              $way = 'from the querystring';
3205          } elseif (isset($urltest['fragment'])) {
3206              // an #anchor is there, it's either...
3207              if (intval($urltest['fragment'])) {
3208                  // ...an integer #XXXX (simpliest case)
3209                  $post_ID = (int) $urltest['fragment'];
3210                  $way = 'from the fragment (numeric)';
3211              } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) {
3212                  // ...a post id in the form 'post-###'
3213                  $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
3214                  $way = 'from the fragment (post-###)';
3215              } elseif (is_string($urltest['fragment'])) {
3216                  // ...or a string #title, a little more complicated
3217                  $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
3218                  $sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title);
3219                  if (! ($post_ID = $wpdb->get_var($sql)) ) {
3220                      // returning unknown error '0' is better than die()ing
3221                        return new IXR_Error(0, '');
3222                  }
3223                  $way = 'from the fragment (title)';
3224              }
3225          } else {
3226              // TODO: Attempt to extract a post ID from the given URL
3227                return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
3228          }
3229          $post_ID = (int) $post_ID;
3230  
3231  
3232          logIO("O","(PB) URL='$pagelinkedto' ID='$post_ID' Found='$way'");
3233  
3234          $post = get_post($post_ID);
3235  
3236          if ( !$post ) // Post_ID not found
3237                return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
3238  
3239          if ( $post_ID == url_to_postid($pagelinkedfrom) )
3240              return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.'));
3241  
3242          // Check if pings are on
3243          if ( !pings_open($post) )
3244                return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
3245  
3246          // Let's check that the remote site didn't already pingback this entry
3247          $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom) );
3248  
3249          if ( $wpdb->num_rows ) // We already have a Pingback from this URL
3250                return new IXR_Error(48, __('The pingback has already been registered.'));
3251  
3252          // very stupid, but gives time to the 'from' server to publish !
3253          sleep(1);
3254  
3255          // Let's check the remote site
3256          $linea = wp_remote_fopen( $pagelinkedfrom );
3257          if ( !$linea )
3258                return new IXR_Error(16, __('The source URL does not exist.'));
3259  
3260          $linea = apply_filters('pre_remote_source', $linea, $pagelinkedto);
3261  
3262          // Work around bug in strip_tags():
3263          $linea = str_replace('<!DOC', '<DOC', $linea);
3264          $linea = preg_replace( '/[\s\r\n\t]+/', ' ', $linea ); // normalize spaces
3265          $linea = preg_replace( "/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea );
3266  
3267          preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
3268          $title = $matchtitle[1];
3269          if ( empty( $title ) )
3270              return new IXR_Error(32, __('We cannot find a title on that page.'));
3271  
3272          $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
3273  
3274          $p = explode( "\n\n", $linea );
3275  
3276          $preg_target = preg_quote($pagelinkedto);
3277  
3278          foreach ( $p as $para ) {
3279              if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link?
3280                  preg_match("|<a[^>]+?".$preg_target."[^>]*>([^>]+?)</a>|", $para, $context);
3281  
3282                  // If the URL isn't in a link context, keep looking
3283                  if ( empty($context) )
3284                      continue;
3285  
3286                  // We're going to use this fake tag to mark the context in a bit
3287                  // the marker is needed in case the link text appears more than once in the paragraph
3288                  $excerpt = preg_replace('|\</?wpcontext\>|', '', $para);
3289  
3290                  // prevent really long link text
3291                  if ( strlen($context[1]) > 100 )
3292                      $context[1] = substr($context[1], 0, 100) . '...';
3293  
3294                  $marker = '<wpcontext>'.$context[1].'</wpcontext>';    // set up our marker
3295                  $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
3296                  $excerpt = strip_tags($excerpt, '<wpcontext>');        // strip all tags but our context marker
3297                  $excerpt = trim($excerpt);
3298                  $preg_marker = preg_quote($marker);
3299                  $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
3300                  $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
3301                  break;
3302              }
3303          }
3304  
3305          if ( empty($context) ) // Link to target not found
3306              return new IXR_Error(17, __('The source URL does not contain a link to the target URL, and so cannot be used as a source.'));
3307  
3308          $pagelinkedfrom = str_replace('&', '&amp;', $pagelinkedfrom);
3309  
3310          $context = '[...] ' . wp_specialchars( $excerpt ) . ' [...]';
3311          $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom );
3312  
3313          $comment_post_ID = (int) $post_ID;
3314          $comment_author = $title;
3315          $this->escape($comment_author);
3316          $comment_author_url = $pagelinkedfrom;
3317          $comment_content = $context;
3318          $this->escape($comment_content);
3319          $comment_type = 'pingback';
3320  
3321          $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type');
3322  
3323          $comment_ID = wp_new_comment($commentdata);
3324          do_action('pingback_post', $comment_ID);
3325  
3326          return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto);
3327      }
3328  
3329      /**
3330       * Retrieve array of URLs that pingbacked the given URL.
3331       *
3332       * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
3333       *
3334       * @since 1.5.0
3335       *
3336       * @param array $args Method parameters.
3337       * @return array
3338       */
3339  	function pingback_extensions_getPingbacks($args) {
3340  
3341          global $wpdb;
3342  
3343          do_action('xmlrpc_call', 'pingback.extensions.getPingsbacks');
3344  
3345          $this->escape($args);
3346  
3347          $url = $args;
3348  
3349          $post_ID = url_to_postid($url);
3350          if (!$post_ID) {
3351              // We aren't sure that the resource is available and/or pingback enabled
3352                return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
3353          }
3354  
3355          $actual_post = wp_get_single_post($post_ID, ARRAY_A);
3356  
3357          if (!$actual_post) {
3358              // No such post = resource not found
3359                return new IXR_Error(32, __('The specified target URL does not exist.'));
3360          }
3361  
3362          $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) );
3363  
3364          if (!$comments) {
3365              return array();
3366          }
3367  
3368          $pingbacks = array();
3369          foreach($comments as $comment) {
3370              if ( 'pingback' == $comment->comment_type )
3371                  $pingbacks[] = $comment->comment_author_url;
3372          }
3373  
3374          return $pingbacks;
3375      }
3376  }
3377  
3378  $wp_xmlrpc_server = new wp_xmlrpc_server();
3379  
3380  ?>


Generated: Thu Mar 5 12:05:07 2009 Cross-referenced by PHPXref 0.7