[ Index ]

PHP Cross Reference of WordPress 2.7.1

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          // If this isn't on WPMU then just use blogger_getUsersBlogs
 410          if( !function_exists( 'is_site_admin' ) ) {
 411              array_unshift( $args, 1 );
 412              return $this->blogger_getUsersBlogs( $args );
 413          }
 414  
 415          $this->escape( $args );
 416  
 417          $username = $args[0];
 418          $password = $args[1];
 419  
 420          if( !$this->login_pass_ok( $username, $password ) )
 421              return $this->error;
 422  
 423          do_action( 'xmlrpc_call', 'wp.getUsersBlogs' );
 424  
 425          $user = set_current_user( 0, $username );
 426  
 427          $blogs = (array) get_blogs_of_user( $user->ID );
 428          $struct = array( );
 429  
 430          foreach( $blogs as $blog ) {
 431              // Don't include blogs that aren't hosted at this site
 432              if( $blog->site_id != $current_site->id )
 433                  continue;
 434  
 435              $blog_id = $blog->userblog_id;
 436              switch_to_blog($blog_id);
 437              $is_admin = current_user_can('level_8');
 438  
 439              $struct[] = array(
 440                  'isAdmin'        => $is_admin,
 441                  'url'            => get_option( 'home' ) . '/',
 442                  'blogid'        => $blog_id,
 443                  'blogName'        => get_option( 'blogname' ),
 444                  'xmlrpc'        => get_option( 'home' ) . '/xmlrpc.php'
 445              );
 446  
 447              restore_current_blog( );
 448          }
 449  
 450          return $struct;
 451      }
 452  
 453      /**
 454       * Retrieve page.
 455       *
 456       * @since 2.2.0
 457       *
 458       * @param array $args Method parameters.
 459       * @return array
 460       */
 461  	function wp_getPage($args) {
 462          $this->escape($args);
 463  
 464          $blog_id    = (int) $args[0];
 465          $page_id    = (int) $args[1];
 466          $username    = $args[2];
 467          $password    = $args[3];
 468  
 469          if(!$this->login_pass_ok($username, $password)) {
 470              return($this->error);
 471          }
 472  
 473          set_current_user( 0, $username );
 474          if( !current_user_can( 'edit_page', $page_id ) )
 475              return new IXR_Error( 401, __( 'Sorry, you can not edit this page.' ) );
 476  
 477          do_action('xmlrpc_call', 'wp.getPage');
 478  
 479          // Lookup page info.
 480          $page = get_page($page_id);
 481  
 482          // If we found the page then format the data.
 483          if($page->ID && ($page->post_type == "page")) {
 484              // Get all of the page content and link.
 485              $full_page = get_extended($page->post_content);
 486              $link = post_permalink($page->ID);
 487  
 488              // Get info the page parent if there is one.
 489              $parent_title = "";
 490              if(!empty($page->post_parent)) {
 491                  $parent = get_page($page->post_parent);
 492                  $parent_title = $parent->post_title;
 493              }
 494  
 495              // Determine comment and ping settings.
 496              $allow_comments = ("open" == $page->comment_status) ? 1 : 0;
 497              $allow_pings = ("open" == $page->ping_status) ? 1 : 0;
 498  
 499              // Format page date.
 500              $page_date = mysql2date("Ymd\TH:i:s", $page->post_date);
 501              $page_date_gmt = mysql2date("Ymd\TH:i:s", $page->post_date_gmt);
 502  
 503              // Pull the categories info together.
 504              $categories = array();
 505              foreach(wp_get_post_categories($page->ID) as $cat_id) {
 506                  $categories[] = get_cat_name($cat_id);
 507              }
 508  
 509              // Get the author info.
 510              $author = get_userdata($page->post_author);
 511  
 512              $page_template = get_post_meta( $page->ID, '_wp_page_template', true );
 513              if( empty( $page_template ) )
 514                  $page_template = 'default';
 515  
 516              $page_struct = array(
 517                  "dateCreated"            => new IXR_Date($page_date),
 518                  "userid"                => $page->post_author,
 519                  "page_id"                => $page->ID,
 520                  "page_status"            => $page->post_status,
 521                  "description"            => $full_page["main"],
 522                  "title"                    => $page->post_title,
 523                  "link"                    => $link,
 524                  "permaLink"                => $link,
 525                  "categories"            => $categories,
 526                  "excerpt"                => $page->post_excerpt,
 527                  "text_more"                => $full_page["extended"],
 528                  "mt_allow_comments"        => $allow_comments,
 529                  "mt_allow_pings"        => $allow_pings,
 530                  "wp_slug"                => $page->post_name,
 531                  "wp_password"            => $page->post_password,
 532                  "wp_author"                => $author->display_name,
 533                  "wp_page_parent_id"        => $page->post_parent,
 534                  "wp_page_parent_title"    => $parent_title,
 535                  "wp_page_order"            => $page->menu_order,
 536                  "wp_author_id"            => $author->ID,
 537                  "wp_author_display_name"    => $author->display_name,
 538                  "date_created_gmt"        => new IXR_Date($page_date_gmt),
 539                  "custom_fields"            => $this->get_custom_fields($page_id),
 540                  "wp_page_template"        => $page_template
 541              );
 542  
 543              return($page_struct);
 544          }
 545          // If the page doesn't exist indicate that.
 546          else {
 547              return(new IXR_Error(404, __("Sorry, no such page.")));
 548          }
 549      }
 550  
 551      /**
 552       * Retrieve Pages.
 553       *
 554       * @since 2.2.0
 555       *
 556       * @param array $args Method parameters.
 557       * @return array
 558       */
 559  	function wp_getPages($args) {
 560          $this->escape($args);
 561  
 562          $blog_id    = (int) $args[0];
 563          $username    = $args[1];
 564          $password    = $args[2];
 565          $num_pages    = (int) $args[3];
 566  
 567          if(!$this->login_pass_ok($username, $password)) {
 568              return($this->error);
 569          }
 570  
 571          set_current_user( 0, $username );
 572          if( !current_user_can( 'edit_pages' ) )
 573              return new IXR_Error( 401, __( 'Sorry, you can not edit pages.' ) );
 574  
 575          do_action('xmlrpc_call', 'wp.getPages');
 576  
 577          $page_limit = 10;
 578          if( isset( $num_pages ) ) {
 579              $page_limit = $num_pages;
 580          }
 581  
 582          $pages = get_posts( "post_type=page&post_status=all&numberposts={$page_limit}" );
 583          $num_pages = count($pages);
 584  
 585          // If we have pages, put together their info.
 586          if($num_pages >= 1) {
 587              $pages_struct = array();
 588  
 589              for($i = 0; $i < $num_pages; $i++) {
 590                  $page = wp_xmlrpc_server::wp_getPage(array(
 591                      $blog_id, $pages[$i]->ID, $username, $password
 592                  ));
 593                  $pages_struct[] = $page;
 594              }
 595  
 596              return($pages_struct);
 597          }
 598          // If no pages were found return an error.
 599          else {
 600              return(array());
 601          }
 602      }
 603  
 604      /**
 605       * Create new page.
 606       *
 607       * @since 2.2.0
 608       *
 609       * @param array $args Method parameters.
 610       * @return unknown
 611       */
 612  	function wp_newPage($args) {
 613          // Items not escaped here will be escaped in newPost.
 614          $username    = $this->escape($args[1]);
 615          $password    = $this->escape($args[2]);
 616          $page        = $args[3];
 617          $publish    = $args[4];
 618  
 619          if(!$this->login_pass_ok($username, $password)) {
 620              return($this->error);
 621          }
 622  
 623          do_action('xmlrpc_call', 'wp.newPage');
 624  
 625          // Set the user context and check if they are allowed
 626          // to add new pages.
 627          $user = set_current_user(0, $username);
 628          if(!current_user_can("publish_pages")) {
 629              return(new IXR_Error(401, __("Sorry, you can not add new pages.")));
 630          }
 631  
 632          // Mark this as content for a page.
 633          $args[3]["post_type"] = "page";
 634  
 635          // Let mw_newPost do all of the heavy lifting.
 636          return($this->mw_newPost($args));
 637      }
 638  
 639      /**
 640       * Delete page.
 641       *
 642       * @since 2.2.0
 643       *
 644       * @param array $args Method parameters.
 645       * @return bool True, if success.
 646       */
 647  	function wp_deletePage($args) {
 648          $this->escape($args);
 649  
 650          $blog_id    = (int) $args[0];
 651          $username    = $args[1];
 652          $password    = $args[2];
 653          $page_id    = (int) $args[3];
 654  
 655          if(!$this->login_pass_ok($username, $password)) {
 656              return($this->error);
 657          }
 658  
 659          do_action('xmlrpc_call', 'wp.deletePage');
 660  
 661          // Get the current page based on the page_id and
 662          // make sure it is a page and not a post.
 663          $actual_page = wp_get_single_post($page_id, ARRAY_A);
 664          if(
 665              !$actual_page
 666              || ($actual_page["post_type"] != "page")
 667          ) {
 668              return(new IXR_Error(404, __("Sorry, no such page.")));
 669          }
 670  
 671          // Set the user context and make sure they can delete pages.
 672          set_current_user(0, $username);
 673          if(!current_user_can("delete_page", $page_id)) {
 674              return(new IXR_Error(401, __("Sorry, you do not have the right to delete this page.")));
 675          }
 676  
 677          // Attempt to delete the page.
 678          $result = wp_delete_post($page_id);
 679          if(!$result) {
 680              return(new IXR_Error(500, __("Failed to delete the page.")));
 681          }
 682  
 683          return(true);
 684      }
 685  
 686      /**
 687       * Edit page.
 688       *
 689       * @since 2.2.0
 690       *
 691       * @param array $args Method parameters.
 692       * @return unknown
 693       */
 694  	function wp_editPage($args) {
 695          // Items not escaped here will be escaped in editPost.
 696          $blog_id    = (int) $args[0];
 697          $page_id    = (int) $this->escape($args[1]);
 698          $username    = $this->escape($args[2]);
 699          $password    = $this->escape($args[3]);
 700          $content    = $args[4];
 701          $publish    = $args[5];
 702  
 703          if(!$this->login_pass_ok($username, $password)) {
 704              return($this->error);
 705          }
 706  
 707          do_action('xmlrpc_call', 'wp.editPage');
 708  
 709          // Get the page data and make sure it is a page.
 710          $actual_page = wp_get_single_post($page_id, ARRAY_A);
 711          if(
 712              !$actual_page
 713              || ($actual_page["post_type"] != "page")
 714          ) {
 715              return(new IXR_Error(404, __("Sorry, no such page.")));
 716          }
 717  
 718          // Set the user context and make sure they are allowed to edit pages.
 719          set_current_user(0, $username);
 720          if(!current_user_can("edit_page", $page_id)) {
 721              return(new IXR_Error(401, __("Sorry, you do not have the right to edit this page.")));
 722          }
 723  
 724          // Mark this as content for a page.
 725          $content["post_type"] = "page";
 726  
 727          // Arrange args in the way mw_editPost understands.
 728          $args = array(
 729              $page_id,
 730              $username,
 731              $password,
 732              $content,
 733              $publish
 734          );
 735  
 736          // Let mw_editPost do all of the heavy lifting.
 737          return($this->mw_editPost($args));
 738      }
 739  
 740      /**
 741       * Retrieve page list.
 742       *
 743       * @since 2.2.0
 744       *
 745       * @param array $args Method parameters.
 746       * @return unknown
 747       */
 748  	function wp_getPageList($args) {
 749          global $wpdb;
 750  
 751          $this->escape($args);
 752  
 753          $blog_id                = (int) $args[0];
 754          $username                = $args[1];
 755          $password                = $args[2];
 756  
 757          if(!$this->login_pass_ok($username, $password)) {
 758              return($this->error);
 759          }
 760  
 761          set_current_user( 0, $username );
 762          if( !current_user_can( 'edit_pages' ) )
 763              return new IXR_Error( 401, __( 'Sorry, you can not edit pages.' ) );
 764  
 765          do_action('xmlrpc_call', 'wp.getPageList');
 766  
 767          // Get list of pages ids and titles
 768          $page_list = $wpdb->get_results("
 769              SELECT ID page_id,
 770                  post_title page_title,
 771                  post_parent page_parent_id,
 772                  post_date_gmt,
 773                  post_date
 774              FROM {$wpdb->posts}
 775              WHERE post_type = 'page'
 776              ORDER BY ID
 777          ");
 778  
 779          // The date needs to be formated properly.
 780          $num_pages = count($page_list);
 781          for($i = 0; $i < $num_pages; $i++) {
 782              $post_date = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date);
 783              $post_date_gmt = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date_gmt);
 784  
 785              $page_list[$i]->dateCreated = new IXR_Date($post_date);
 786              $page_list[$i]->date_created_gmt = new IXR_Date($post_date_gmt);
 787  
 788              unset($page_list[$i]->post_date_gmt);
 789              unset($page_list[$i]->post_date);
 790          }
 791  
 792          return($page_list);
 793      }
 794  
 795      /**
 796       * Retrieve authors list.
 797       *
 798       * @since 2.2.0
 799       *
 800       * @param array $args Method parameters.
 801       * @return array
 802       */
 803  	function wp_getAuthors($args) {
 804  
 805          $this->escape($args);
 806  
 807          $blog_id    = (int) $args[0];
 808          $username    = $args[1];
 809          $password    = $args[2];
 810  
 811          if(!$this->login_pass_ok($username, $password)) {
 812              return($this->error);
 813          }
 814  
 815          set_current_user(0, $username);
 816          if(!current_user_can("edit_posts")) {
 817              return(new IXR_Error(401, __("Sorry, you can not edit posts on this blog.")));
 818          }
 819  
 820          do_action('xmlrpc_call', 'wp.getAuthors');
 821  
 822          $authors = array();
 823          foreach( (array) get_users_of_blog() as $row ) {
 824              $authors[] = array(
 825                  "user_id"       => $row->user_id,
 826                  "user_login"    => $row->user_login,
 827                  "display_name"  => $row->display_name
 828              );
 829          }
 830  
 831          return($authors);
 832      }
 833  
 834      /**
 835       * Get list of all tags
 836       *
 837       * @since 2.7
 838       *
 839       * @param array $args Method parameters.
 840       * @return array
 841       */
 842  	function wp_getTags( $args ) {
 843          $this->escape( $args );
 844  
 845          $blog_id        = (int) $args[0];
 846          $username        = $args[1];
 847          $password        = $args[2];
 848  
 849          if( !$this->login_pass_ok( $username, $password ) ) {
 850              return $this->error;
 851          }
 852  
 853          set_current_user( 0, $username );
 854          if( !current_user_can( 'edit_posts' ) ) {
 855              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view tags.' ) );
 856          }
 857  
 858          do_action( 'xmlrpc_call', 'wp.getKeywords' );
 859  
 860          $tags = array( );
 861  
 862          if( $all_tags = get_tags( ) ) {
 863              foreach( (array) $all_tags as $tag ) {
 864                  $struct['tag_id']            = $tag->term_id;
 865                  $struct['name']                = $tag->name;
 866                  $struct['count']            = $tag->count;
 867                  $struct['slug']                = $tag->slug;
 868                  $struct['html_url']            = wp_specialchars( get_tag_link( $tag->term_id ) );
 869                  $struct['rss_url']            = wp_specialchars( get_tag_feed_link( $tag->term_id ) );
 870  
 871                  $tags[] = $struct;
 872              }
 873          }
 874  
 875          return $tags;
 876      }
 877  
 878      /**
 879       * Create new category.
 880       *
 881       * @since 2.2.0
 882       *
 883       * @param array $args Method parameters.
 884       * @return int Category ID.
 885       */
 886  	function wp_newCategory($args) {
 887          $this->escape($args);
 888  
 889          $blog_id                = (int) $args[0];
 890          $username                = $args[1];
 891          $password                = $args[2];
 892          $category                = $args[3];
 893  
 894          if(!$this->login_pass_ok($username, $password)) {
 895              return($this->error);
 896          }
 897  
 898          do_action('xmlrpc_call', 'wp.newCategory');
 899  
 900          // Set the user context and make sure they are
 901          // allowed to add a category.
 902          set_current_user(0, $username);
 903          if(!current_user_can("manage_categories")) {
 904              return(new IXR_Error(401, __("Sorry, you do not have the right to add a category.")));
 905          }
 906  
 907          // If no slug was provided make it empty so that
 908          // WordPress will generate one.
 909          if(empty($category["slug"])) {
 910              $category["slug"] = "";
 911          }
 912  
 913          // If no parent_id was provided make it empty
 914          // so that it will be a top level page (no parent).
 915          if ( !isset($category["parent_id"]) )
 916              $category["parent_id"] = "";
 917  
 918          // If no description was provided make it empty.
 919          if(empty($category["description"])) {
 920              $category["description"] = "";
 921          }
 922  
 923          $new_category = array(
 924              "cat_name"                => $category["name"],
 925              "category_nicename"        => $category["slug"],
 926              "category_parent"        => $category["parent_id"],
 927              "category_description"    => $category["description"]
 928          );
 929  
 930          $cat_id = wp_insert_category($new_category);
 931          if(!$cat_id) {
 932              return(new IXR_Error(500, __("Sorry, the new category failed.")));
 933          }
 934  
 935          return($cat_id);
 936      }
 937  
 938      /**
 939       * Remove category.
 940       *
 941       * @since 2.5.0
 942       *
 943       * @param array $args Method parameters.
 944       * @return mixed See {@link wp_delete_category()} for return info.
 945       */
 946  	function wp_deleteCategory($args) {
 947          $this->escape($args);
 948  
 949          $blog_id        = (int) $args[0];
 950          $username        = $args[1];
 951          $password        = $args[2];
 952          $category_id    = (int) $args[3];
 953  
 954          if( !$this->login_pass_ok( $username, $password ) ) {
 955              return $this->error;
 956          }
 957  
 958          do_action('xmlrpc_call', 'wp.deleteCategory');
 959  
 960          set_current_user(0, $username);
 961          if( !current_user_can("manage_categories") ) {
 962              return new IXR_Error( 401, __( "Sorry, you do not have the right to delete a category." ) );
 963          }
 964  
 965          return wp_delete_category( $category_id );
 966      }
 967  
 968      /**
 969       * Retrieve category list.
 970       *
 971       * @since 2.2.0
 972       *
 973       * @param array $args Method parameters.
 974       * @return array
 975       */
 976  	function wp_suggestCategories($args) {
 977          $this->escape($args);
 978  
 979          $blog_id                = (int) $args[0];
 980          $username                = $args[1];
 981          $password                = $args[2];
 982          $category                = $args[3];
 983          $max_results            = (int) $args[4];
 984  
 985          if(!$this->login_pass_ok($username, $password)) {
 986              return($this->error);
 987          }
 988  
 989          set_current_user(0, $username);
 990          if( !current_user_can( 'edit_posts' ) )
 991              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts to this blog in order to view categories.' ) );
 992  
 993          do_action('xmlrpc_call', 'wp.suggestCategories');
 994  
 995          $category_suggestions = array();
 996          $args = array('get' => 'all', 'number' => $max_results, 'name__like' => $category);
 997          foreach ( (array) get_categories($args) as $cat ) {
 998              $category_suggestions[] = array(
 999                  "category_id"    => $cat->cat_ID,
1000                  "category_name"    => $cat->cat_name
1001              );
1002          }
1003  
1004          return($category_suggestions);
1005      }
1006  
1007      /**
1008       * Retrieve comment.
1009       *
1010       * @since 2.7.0
1011       *
1012       * @param array $args Method parameters.
1013       * @return array
1014       */
1015  	function wp_getComment($args) {
1016          $this->escape($args);
1017  
1018          $blog_id    = (int) $args[0];
1019          $username    = $args[1];
1020          $password    = $args[2];
1021          $comment_id    = (int) $args[3];
1022  
1023          if ( !$this->login_pass_ok( $username, $password ) )
1024              return $this->error;
1025  
1026          set_current_user( 0, $username );
1027          if ( !current_user_can( 'moderate_comments' ) )
1028              return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1029  
1030          do_action('xmlrpc_call', 'wp.getComment');
1031  
1032          if ( ! $comment = get_comment($comment_id) )
1033              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1034  
1035          // Format page date.
1036          $comment_date = mysql2date("Ymd\TH:i:s", $comment->comment_date);
1037          $comment_date_gmt = mysql2date("Ymd\TH:i:s", $comment->comment_date_gmt);
1038  
1039          if ( 0 == $comment->comment_approved )
1040              $comment_status = 'hold';
1041          else if ( 'spam' == $comment->comment_approved )
1042              $comment_status = 'spam';
1043          else if ( 1 == $comment->comment_approved )
1044              $comment_status = 'approve';
1045          else
1046              $comment_status = $comment->comment_approved;
1047  
1048          $link = get_comment_link($comment);
1049  
1050          $comment_struct = array(
1051              "date_created_gmt"        => new IXR_Date($comment_date_gmt),
1052              "user_id"                => $comment->user_id,
1053              "comment_id"            => $comment->comment_ID,
1054              "parent"                => $comment->comment_parent,
1055              "status"                => $comment_status,
1056              "content"                => $comment->comment_content,
1057              "link"                    => $link,
1058              "post_id"                => $comment->comment_post_ID,
1059              "post_title"            => get_the_title($comment->comment_post_ID),
1060              "author"                => $comment->comment_author,
1061              "author_url"            => $comment->comment_author_url,
1062              "author_email"            => $comment->comment_author_email,
1063              "author_ip"                => $comment->comment_author_IP,
1064              "type"                    => $comment->comment_type,
1065          );
1066  
1067          return $comment_struct;
1068      }
1069  
1070      /**
1071       * Retrieve comments.
1072       *
1073       * @since 2.7.0
1074       *
1075       * @param array $args Method parameters.
1076       * @return array
1077       */
1078  	function wp_getComments($args) {
1079          $this->escape($args);
1080  
1081          $blog_id    = (int) $args[0];
1082          $username    = $args[1];
1083          $password    = $args[2];
1084          $struct        = $args[3];
1085  
1086          if ( !$this->login_pass_ok($username, $password) )
1087              return($this->error);
1088  
1089          set_current_user( 0, $username );
1090          if ( !current_user_can( 'moderate_comments' ) )
1091              return new IXR_Error( 401, __( 'Sorry, you can not edit comments.' ) );
1092  
1093          do_action('xmlrpc_call', 'wp.getComments');
1094  
1095          if ( isset($struct['status']) )
1096              $status = $struct['status'];
1097          else
1098              $status = '';
1099  
1100          $post_id = '';
1101          if ( isset($struct['post_id']) )
1102              $post_id = absint($struct['post_id']);
1103  
1104          $offset = 0;
1105          if ( isset($struct['offset']) )
1106              $offset = absint($struct['offset']);
1107  
1108          $number = 10;
1109          if ( isset($struct['number']) )
1110              $number = absint($struct['number']);
1111  
1112          $comments = get_comments( array('status' => $status, 'post_id' => $post_id, 'offset' => $offset, 'number' => $number ) );
1113          $num_comments = count($comments);
1114  
1115          if ( ! $num_comments )
1116              return array();
1117  
1118          $comments_struct = array();
1119  
1120          for ( $i = 0; $i < $num_comments; $i++ ) {
1121              $comment = wp_xmlrpc_server::wp_getComment(array(
1122                  $blog_id, $username, $password, $comments[$i]->comment_ID,
1123              ));
1124              $comments_struct[] = $comment;
1125          }
1126  
1127          return $comments_struct;
1128      }
1129  
1130      /**
1131       * Remove comment.
1132       *
1133       * @since 2.7.0
1134       *
1135       * @param array $args Method parameters.
1136       * @return mixed {@link wp_delete_comment()}
1137       */
1138  	function wp_deleteComment($args) {
1139          $this->escape($args);
1140  
1141          $blog_id    = (int) $args[0];
1142          $username    = $args[1];
1143          $password    = $args[2];
1144          $comment_ID    = (int) $args[3];
1145  
1146          if ( !$this->login_pass_ok( $username, $password ) )
1147              return $this->error;
1148  
1149          set_current_user( 0, $username );
1150          if ( !current_user_can( 'moderate_comments' ) )
1151              return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1152  
1153          do_action('xmlrpc_call', 'wp.deleteComment');
1154  
1155          if ( ! get_comment($comment_ID) )
1156              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1157  
1158          return wp_delete_comment($comment_ID);
1159      }
1160  
1161      /**
1162       * Edit comment.
1163       *
1164       * @since 2.7.0
1165       *
1166       * @param array $args Method parameters.
1167       * @return bool True, on success.
1168       */
1169  	function wp_editComment($args) {
1170          $this->escape($args);
1171  
1172          $blog_id    = (int) $args[0];
1173          $username    = $args[1];
1174          $password    = $args[2];
1175          $comment_ID    = (int) $args[3];
1176          $content_struct = $args[4];
1177  
1178          if ( !$this->login_pass_ok( $username, $password ) )
1179              return $this->error;
1180  
1181          set_current_user( 0, $username );
1182          if ( !current_user_can( 'moderate_comments' ) )
1183              return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1184  
1185          do_action('xmlrpc_call', 'wp.editComment');
1186  
1187          if ( ! get_comment($comment_ID) )
1188              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1189  
1190          if ( isset($content_struct['status']) ) {
1191              $statuses = get_comment_statuses();
1192              $statuses = array_keys($statuses);
1193  
1194              if ( ! in_array($content_struct['status'], $statuses) )
1195                  return new IXR_Error( 401, __( 'Invalid comment status.' ) );
1196              $comment_approved = $content_struct['status'];
1197          }
1198  
1199          // Do some timestamp voodoo
1200          if ( !empty( $content_struct['date_created_gmt'] ) ) {
1201              $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
1202              $comment_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1203              $comment_date_gmt = iso8601_to_datetime($dateCreated, GMT);
1204          }
1205  
1206          if ( isset($content_struct['content']) )
1207              $comment_content = $content_struct['content'];
1208  
1209          if ( isset($content_struct['author']) )
1210              $comment_author = $content_struct['author'];
1211  
1212          if ( isset($content_struct['author_url']) )
1213              $comment_author_url = $content_struct['author_url'];
1214  
1215          if ( isset($content_struct['author_email']) )
1216              $comment_author_email = $content_struct['author_email'];
1217  
1218          // We've got all the data -- post it:
1219          $comment = compact('comment_ID', 'comment_content', 'comment_approved', 'comment_date', 'comment_date_gmt', 'comment_author', 'comment_author_email', 'comment_author_url');
1220  
1221          $result = wp_update_comment($comment);
1222          if ( is_wp_error( $result ) )
1223              return new IXR_Error(500, $result->get_error_message());
1224  
1225          if ( !$result )
1226              return new IXR_Error(500, __('Sorry, the comment could not be edited. Something wrong happened.'));
1227  
1228          return true;
1229      }
1230  
1231      /**
1232       * Create new comment.
1233       *
1234       * @since 2.7.0
1235       *
1236       * @param array $args Method parameters.
1237       * @return mixed {@link wp_new_comment()}
1238       */
1239  	function wp_newComment($args) {
1240          global $wpdb;
1241  
1242          $this->escape($args);
1243  
1244          $blog_id    = (int) $args[0];
1245          $username    = $args[1];
1246          $password    = $args[2];
1247          $post        = $args[3];
1248          $content_struct = $args[4];
1249  
1250          $allow_anon = apply_filters('xmlrpc_allow_anonymous_comments', false);
1251  
1252          if ( !$this->login_pass_ok( $username, $password ) ) {
1253              $logged_in = false;
1254              if ( $allow_anon && get_option('comment_registration') )
1255                  return new IXR_Error( 403, __( 'You must be registered to comment' ) );
1256              else if ( !$allow_anon )
1257                  return $this->error;
1258          } else {
1259              $logged_in = true;
1260              set_current_user( 0, $username );
1261          }
1262  
1263          if ( is_numeric($post) )
1264              $post_id = absint($post);
1265          else
1266              $post_id = url_to_postid($post);
1267  
1268          if ( ! $post_id )
1269              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1270  
1271          if ( ! get_post($post_id) )
1272              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1273  
1274          $comment['comment_post_ID'] = $post_id;
1275  
1276          if ( $logged_in ) {
1277              $user = wp_get_current_user();
1278              $comment['comment_author'] = $wpdb->escape( $user->display_name );
1279              $comment['comment_author_email'] = $wpdb->escape( $user->user_email );
1280              $comment['comment_author_url'] = $wpdb->escape( $user->user_url );
1281              $comment['user_ID'] = $user->ID;
1282          } else {
1283              $comment['comment_author'] = '';
1284              if ( isset($content_struct['author']) )
1285                  $comment['comment_author'] = $content_struct['author'];
1286  
1287              $comment['comment_author_email'] = '';
1288              if ( isset($content_struct['author_email']) )
1289                  $comment['comment_author_email'] = $content_struct['author_email'];
1290  
1291              $comment['comment_author_url'] = '';
1292              if ( isset($content_struct['author_url']) )
1293                  $comment['comment_author_url'] = $content_struct['author_url'];
1294  
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->name;
2766                  $struct['categoryDescription'] = $cat->description;
2767                  $struct['categoryName'] = $cat->name;
2768                  $struct['htmlUrl'] = wp_specialchars(get_category_link($cat->term_id));
2769                  $struct['rssUrl'] = wp_specialchars(get_category_feed_link($cat->term_id, 'rss2'));
2770  
2771                  $categories_struct[] = $struct;
2772              }
2773          }
2774  
2775          return $categories_struct;
2776      }
2777  
2778      /**
2779       * Uploads a file, following your settings.
2780       *
2781       * Adapted from a patch by Johann Richard.
2782       *
2783       * @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
2784       *
2785       * @since 1.5.0
2786       *
2787       * @param array $args Method parameters.
2788       * @return array
2789       */
2790  	function mw_newMediaObject($args) {
2791          global $wpdb;
2792  
2793          $blog_ID     = (int) $args[0];
2794          $user_login  = $wpdb->escape($args[1]);
2795          $user_pass   = $wpdb->escape($args[2]);
2796          $data        = $args[3];
2797  
2798          $name = sanitize_file_name( $data['name'] );
2799          $type = $data['type'];
2800          $bits = $data['bits'];
2801  
2802          logIO('O', '(MW) Received '.strlen($bits).' bytes');
2803  
2804          if ( !$this->login_pass_ok($user_login, $user_pass) )
2805              return $this->error;
2806  
2807          do_action('xmlrpc_call', 'metaWeblog.newMediaObject');
2808  
2809          set_current_user(0, $user_login);
2810          if ( !current_user_can('upload_files') ) {
2811              logIO('O', '(MW) User does not have upload_files capability');
2812              $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
2813              return $this->error;
2814          }
2815  
2816          if ( $upload_err = apply_filters( "pre_upload_error", false ) )
2817              return new IXR_Error(500, $upload_err);
2818  
2819          if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
2820              // Get postmeta info on the object.
2821              $old_file = $wpdb->get_row("
2822                  SELECT ID
2823                  FROM {$wpdb->posts}
2824                  WHERE post_title = '{$name}'
2825                      AND post_type = 'attachment'
2826              ");
2827  
2828              // Delete previous file.
2829              wp_delete_attachment($old_file->ID);
2830  
2831              // Make sure the new name is different by pre-pending the
2832              // previous post id.
2833              $filename = preg_replace("/^wpid\d+-/", "", $name);
2834              $name = "wpid{$old_file->ID}-{$filename}";
2835          }
2836  
2837          $upload = wp_upload_bits($name, $type, $bits);
2838          if ( ! empty($upload['error']) ) {
2839              $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']);
2840              logIO('O', '(MW) ' . $errorString);
2841              return new IXR_Error(500, $errorString);
2842          }
2843          // Construct the attachment array
2844          // attach to post_id -1
2845          $post_id = -1;
2846          $attachment = array(
2847              'post_title' => $name,
2848              'post_content' => '',
2849              'post_type' => 'attachment',
2850              'post_parent' => $post_id,
2851              'post_mime_type' => $type,
2852              'guid' => $upload[ 'url' ]
2853          );
2854  
2855          // Save the data
2856          $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
2857          wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
2858  
2859          return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
2860      }
2861  
2862      /* MovableType API functions
2863       * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
2864       */
2865  
2866      /**
2867       * Retrieve the post titles of recent posts.
2868       *
2869       * @since 1.5.0
2870       *
2871       * @param array $args Method parameters.
2872       * @return array
2873       */
2874  	function mt_getRecentPostTitles($args) {
2875  
2876          $this->escape($args);
2877  
2878          $blog_ID     = (int) $args[0];
2879          $user_login  = $args[1];
2880          $user_pass   = $args[2];
2881          $num_posts   = (int) $args[3];
2882  
2883          if (!$this->login_pass_ok($user_login, $user_pass)) {
2884              return $this->error;
2885          }
2886  
2887          do_action('xmlrpc_call', 'mt.getRecentPostTitles');
2888  
2889          $posts_list = wp_get_recent_posts($num_posts);
2890  
2891          if (!$posts_list) {
2892              $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
2893              return $this->error;
2894          }
2895  
2896          set_current_user( 0, $user_login );
2897  
2898          foreach ($posts_list as $entry) {
2899              if( !current_user_can( 'edit_post', $entry['ID'] ) )
2900                  continue;
2901  
2902              $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
2903              $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
2904  
2905              $struct[] = array(
2906                  'dateCreated' => new IXR_Date($post_date),
2907                  'userid' => $entry['post_author'],
2908                  'postid' => $entry['ID'],
2909                  'title' => $entry['post_title'],
2910                  'date_created_gmt' => new IXR_Date($post_date_gmt)
2911              );
2912  
2913          }
2914  
2915          $recent_posts = array();
2916          for ($j=0; $j<count($struct); $j++) {
2917              array_push($recent_posts, $struct[$j]);
2918          }
2919  
2920          return $recent_posts;
2921      }
2922  
2923      /**
2924       * Retrieve list of all categories on blog.
2925       *
2926       * @since 1.5.0
2927       *
2928       * @param array $args Method parameters.
2929       * @return array
2930       */
2931  	function mt_getCategoryList($args) {
2932  
2933          $this->escape($args);
2934  
2935          $blog_ID     = (int) $args[0];
2936          $user_login  = $args[1];
2937          $user_pass   = $args[2];
2938  
2939          if (!$this->login_pass_ok($user_login, $user_pass)) {
2940              return $this->error;
2941          }
2942  
2943          set_current_user( 0, $user_login );
2944          if( !current_user_can( 'edit_posts' ) )
2945              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
2946  
2947          do_action('xmlrpc_call', 'mt.getCategoryList');
2948  
2949          $categories_struct = array();
2950  
2951          if ( $cats = get_categories('hide_empty=0&hierarchical=0') ) {
2952              foreach ($cats as $cat) {
2953                  $struct['categoryId'] = $cat->term_id;
2954                  $struct['categoryName'] = $cat->name;
2955  
2956                  $categories_struct[] = $struct;
2957              }
2958          }
2959  
2960          return $categories_struct;
2961      }
2962  
2963      /**
2964       * Retrieve post categories.
2965       *
2966       * @since 1.5.0
2967       *
2968       * @param array $args Method parameters.
2969       * @return array
2970       */
2971  	function mt_getPostCategories($args) {
2972  
2973          $this->escape($args);
2974  
2975          $post_ID     = (int) $args[0];
2976          $user_login  = $args[1];
2977          $user_pass   = $args[2];
2978  
2979          if (!$this->login_pass_ok($user_login, $user_pass)) {
2980              return $this->error;
2981          }
2982  
2983          set_current_user( 0, $user_login );
2984          if( !current_user_can( 'edit_post', $post_ID ) )
2985              return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
2986  
2987          do_action('xmlrpc_call', 'mt.getPostCategories');
2988  
2989          $categories = array();
2990          $catids = wp_get_post_categories(intval($post_ID));
2991          // first listed category will be the primary category
2992          $isPrimary = true;
2993          foreach($catids as $catid) {
2994              $categories[] = array(
2995                  'categoryName' => get_cat_name($catid),
2996                  'categoryId' => (string) $catid,
2997                  'isPrimary' => $isPrimary
2998              );
2999              $isPrimary = false;
3000          }
3001  
3002          return $categories;
3003      }
3004  
3005      /**
3006       * Sets categories for a post.
3007       *
3008       * @since 1.5.0
3009       *
3010       * @param array $args Method parameters.
3011       * @return bool True on success.
3012       */
3013  	function mt_setPostCategories($args) {
3014  
3015          $this->escape($args);
3016  
3017          $post_ID     = (int) $args[0];
3018          $user_login  = $args[1];
3019          $user_pass   = $args[2];
3020          $categories  = $args[3];
3021  
3022          if (!$this->login_pass_ok($user_login, $user_pass)) {
3023              return $this->error;
3024          }
3025  
3026          do_action('xmlrpc_call', 'mt.setPostCategories');
3027  
3028          set_current_user(0, $user_login);
3029          if ( !current_user_can('edit_post', $post_ID) )
3030              return new IXR_Error(401, __('Sorry, you can not edit this post.'));
3031  
3032          foreach($categories as $cat) {
3033              $catids[] = $cat['categoryId'];
3034          }
3035  
3036          wp_set_post_categories($post_ID, $catids);
3037  
3038          return true;
3039      }
3040  
3041      /**
3042       * Retrieve an array of methods supported by this server.
3043       *
3044       * @since 1.5.0
3045       *
3046       * @param array $args Method parameters.
3047       * @return array
3048       */
3049  	function mt_supportedMethods($args) {
3050  
3051          do_action('xmlrpc_call', 'mt.supportedMethods');
3052  
3053          $supported_methods = array();
3054          foreach($this->methods as $key=>$value) {
3055              $supported_methods[] = $key;
3056          }
3057  
3058          return $supported_methods;
3059      }
3060  
3061      /**
3062       * Retrieve an empty array because we don't support per-post text filters.
3063       *
3064       * @since 1.5.0
3065       *
3066       * @param array $args Method parameters.
3067       */
3068  	function mt_supportedTextFilters($args) {
3069          do_action('xmlrpc_call', 'mt.supportedTextFilters');
3070          return apply_filters('xmlrpc_text_filters', array());
3071      }
3072  
3073      /**
3074       * Retrieve trackbacks sent to a given post.
3075       *
3076       * @since 1.5.0
3077       *
3078       * @param array $args Method parameters.
3079       * @return mixed
3080       */
3081  	function mt_getTrackbackPings($args) {
3082  
3083          global $wpdb;
3084  
3085          $post_ID = intval($args);
3086  
3087          do_action('xmlrpc_call', 'mt.getTrackbackPings');
3088  
3089          $actual_post = wp_get_single_post($post_ID, ARRAY_A);
3090  
3091          if (!$actual_post) {
3092              return new IXR_Error(404, __('Sorry, no such post.'));
3093          }
3094  
3095          $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) );
3096  
3097          if (!$comments) {
3098              return array();
3099          }
3100  
3101          $trackback_pings = array();
3102          foreach($comments as $comment) {
3103              if ( 'trackback' == $comment->comment_type ) {
3104                  $content = $comment->comment_content;
3105                  $title = substr($content, 8, (strpos($content, '</strong>') - 8));
3106                  $trackback_pings[] = array(
3107                      'pingTitle' => $title,
3108                      'pingURL'   => $comment->comment_author_url,
3109                      'pingIP'    => $comment->comment_author_IP
3110                  );
3111          }
3112          }
3113  
3114          return $trackback_pings;
3115      }
3116  
3117      /**
3118       * Sets a post's publish status to 'publish'.
3119       *
3120       * @since 1.5.0
3121       *
3122       * @param array $args Method parameters.
3123       * @return int
3124       */
3125  	function mt_publishPost($args) {
3126  
3127          $this->escape($args);
3128  
3129          $post_ID     = (int) $args[0];
3130          $user_login  = $args[1];
3131          $user_pass   = $args[2];
3132  
3133          if (!$this->login_pass_ok($user_login, $user_pass)) {
3134              return $this->error;
3135          }
3136  
3137          do_action('xmlrpc_call', 'mt.publishPost');
3138  
3139          set_current_user(0, $user_login);
3140          if ( !current_user_can('edit_post', $post_ID) )
3141              return new IXR_Error(401, __('Sorry, you can not edit this post.'));
3142  
3143          $postdata = wp_get_single_post($post_ID,ARRAY_A);
3144  
3145          $postdata['post_status'] = 'publish';
3146  
3147          // retain old cats
3148          $cats = wp_get_post_categories($post_ID);
3149          $postdata['post_category'] = $cats;
3150          $this->escape($postdata);
3151  
3152          $result = wp_update_post($postdata);
3153  
3154          return $result;
3155      }
3156  
3157      /* PingBack functions
3158       * specs on www.hixie.ch/specs/pingback/pingback
3159       */
3160  
3161      /**
3162       * Retrieves a pingback and registers it.
3163       *
3164       * @since 1.5.0
3165       *
3166       * @param array $args Method parameters.
3167       * @return array
3168       */
3169  	function pingback_ping($args) {
3170          global $wpdb;
3171  
3172          do_action('xmlrpc_call', 'pingback.ping');
3173  
3174          $this->escape($args);
3175  
3176          $pagelinkedfrom = $args[0];
3177          $pagelinkedto   = $args[1];
3178  
3179          $title = '';
3180  
3181          $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
3182          $pagelinkedto = str_replace('&amp;', '&', $pagelinkedto);
3183          $pagelinkedto = str_replace('&', '&amp;', $pagelinkedto);
3184  
3185          // Check if the page linked to is in our site
3186          $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
3187          if( !$pos1 )
3188              return new IXR_Error(0, __('Is there no link to us?'));
3189  
3190          // let's find which post is linked to
3191          // FIXME: does url_to_postid() cover all these cases already?
3192          //        if so, then let's use it and drop the old code.
3193          $urltest = parse_url($pagelinkedto);
3194          if ($post_ID = url_to_postid($pagelinkedto)) {
3195              $way = 'url_to_postid()';
3196          } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
3197              // the path defines the post_ID (archives/p/XXXX)
3198              $blah = explode('/', $match[0]);
3199              $post_ID = (int) $blah[1];
3200              $way = 'from the path';
3201          } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
3202              // the querystring defines the post_ID (?p=XXXX)
3203              $blah = explode('=', $match[0]);
3204              $post_ID = (int) $blah[1];
3205              $way = 'from the querystring';
3206          } elseif (isset($urltest['fragment'])) {
3207              // an #anchor is there, it's either...
3208              if (intval($urltest['fragment'])) {
3209                  // ...an integer #XXXX (simpliest case)
3210                  $post_ID = (int) $urltest['fragment'];
3211                  $way = 'from the fragment (numeric)';
3212              } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) {
3213                  // ...a post id in the form 'post-###'
3214                  $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
3215                  $way = 'from the fragment (post-###)';
3216              } elseif (is_string($urltest['fragment'])) {
3217                  // ...or a string #title, a little more complicated
3218                  $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
3219                  $sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title);
3220                  if (! ($post_ID = $wpdb->get_var($sql)) ) {
3221                      // returning unknown error '0' is better than die()ing
3222                        return new IXR_Error(0, '');
3223                  }
3224                  $way = 'from the fragment (title)';
3225              }
3226          } else {
3227              // TODO: Attempt to extract a post ID from the given URL
3228                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.'));
3229          }
3230          $post_ID = (int) $post_ID;
3231  
3232  
3233          logIO("O","(PB) URL='$pagelinkedto' ID='$post_ID' Found='$way'");
3234  
3235          $post = get_post($post_ID);
3236  
3237          if ( !$post ) // Post_ID not found
3238                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.'));
3239  
3240          if ( $post_ID == url_to_postid($pagelinkedfrom) )
3241              return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.'));
3242  
3243          // Check if pings are on
3244          if ( !pings_open($post) )
3245                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.'));
3246  
3247          // Let's check that the remote site didn't already pingback this entry
3248          $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom) );
3249  
3250          if ( $wpdb->num_rows ) // We already have a Pingback from this URL
3251                return new IXR_Error(48, __('The pingback has already been registered.'));
3252  
3253          // very stupid, but gives time to the 'from' server to publish !
3254          sleep(1);
3255  
3256          // Let's check the remote site
3257          $linea = wp_remote_fopen( $pagelinkedfrom );
3258          if ( !$linea )
3259                return new IXR_Error(16, __('The source URL does not exist.'));
3260  
3261          $linea = apply_filters('pre_remote_source', $linea, $pagelinkedto);
3262  
3263          // Work around bug in strip_tags():
3264          $linea = str_replace('<!DOC', '<DOC', $linea);
3265          $linea = preg_replace( '/[\s\r\n\t]+/', ' ', $linea ); // normalize spaces
3266          $linea = preg_replace( "/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea );
3267  
3268          preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
3269          $title = $matchtitle[1];
3270          if ( empty( $title ) )
3271              return new IXR_Error(32, __('We cannot find a title on that page.'));
3272  
3273          $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
3274  
3275          $p = explode( "\n\n", $linea );
3276  
3277          $preg_target = preg_quote($pagelinkedto);
3278  
3279          foreach ( $p as $para ) {
3280              if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link?
3281                  preg_match("|<a[^>]+?".$preg_target."[^>]*>([^>]+?)</a>|", $para, $context);
3282  
3283                  // If the URL isn't in a link context, keep looking
3284                  if ( empty($context) )
3285                      continue;
3286  
3287                  // We're going to use this fake tag to mark the context in a bit
3288                  // the marker is needed in case the link text appears more than once in the paragraph
3289                  $excerpt = preg_replace('|\</?wpcontext\>|', '', $para);
3290  
3291                  // prevent really long link text
3292                  if ( strlen($context[1]) > 100 )
3293                      $context[1] = substr($context[1], 0, 100) . '...';
3294  
3295                  $marker = '<wpcontext>'.$context[1].'</wpcontext>';    // set up our marker
3296                  $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
3297                  $excerpt = strip_tags($excerpt, '<wpcontext>');        // strip all tags but our context marker
3298                  $excerpt = trim($excerpt);
3299                  $preg_marker = preg_quote($marker);
3300                  $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
3301                  $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
3302                  break;
3303              }
3304          }
3305  
3306          if ( empty($context) ) // Link to target not found
3307              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.'));
3308  
3309          $pagelinkedfrom = str_replace('&', '&amp;', $pagelinkedfrom);
3310  
3311          $context = '[...] ' . wp_specialchars( $excerpt ) . ' [...]';
3312          $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom );
3313  
3314          $comment_post_ID = (int) $post_ID;
3315          $comment_author = $title;
3316          $this->escape($comment_author);
3317          $comment_author_url = $pagelinkedfrom;
3318          $comment_content = $context;
3319          $this->escape($comment_content);
3320          $comment_type = 'pingback';
3321  
3322          $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type');
3323  
3324          $comment_ID = wp_new_comment($commentdata);
3325          do_action('pingback_post', $comment_ID);
3326  
3327          return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto);
3328      }
3329  
3330      /**
3331       * Retrieve array of URLs that pingbacked the given URL.
3332       *
3333       * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
3334       *
3335       * @since 1.5.0
3336       *
3337       * @param array $args Method parameters.
3338       * @return array
3339       */
3340  	function pingback_extensions_getPingbacks($args) {
3341  
3342          global $wpdb;
3343  
3344          do_action('xmlrpc_call', 'pingback.extensions.getPingsbacks');
3345  
3346          $this->escape($args);
3347  
3348          $url = $args;
3349  
3350          $post_ID = url_to_postid($url);
3351          if (!$post_ID) {
3352              // We aren't sure that the resource is available and/or pingback enabled
3353                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.'));
3354          }
3355  
3356          $actual_post = wp_get_single_post($post_ID, ARRAY_A);
3357  
3358          if (!$actual_post) {
3359              // No such post = resource not found
3360                return new IXR_Error(32, __('The specified target URL does not exist.'));
3361          }
3362  
3363          $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) );
3364  
3365          if (!$comments) {
3366              return array();
3367          }
3368  
3369          $pingbacks = array();
3370          foreach($comments as $comment) {
3371              if ( 'pingback' == $comment->comment_type )
3372                  $pingbacks[] = $comment->comment_author_url;
3373          }
3374  
3375          return $pingbacks;
3376      }
3377  }
3378  
3379  $wp_xmlrpc_server = new wp_xmlrpc_server();
3380  
3381  ?>


Generated: Tue Mar 17 22:41:04 2009 Cross-referenced by PHPXref 0.7