[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-xmlrpc-server.php (source)

   1  <?php
   2  /**
   3   * XML-RPC protocol support for WordPress.
   4   *
   5   * @package WordPress
   6   * @subpackage Publishing
   7   */
   8  
   9  /**
  10   * WordPress XMLRPC server implementation.
  11   *
  12   * Implements compatibility for Blogger API, MetaWeblog API, MovableType, and
  13   * pingback. Additional WordPress API for managing comments, pages, posts,
  14   * options, etc.
  15   *
  16   * As of WordPress 3.5.0, XML-RPC is enabled by default. It can be disabled
  17   * via the {@see 'xmlrpc_enabled'} filter found in wp_xmlrpc_server::set_is_enabled().
  18   *
  19   * @since 1.5.0
  20   *
  21   * @see IXR_Server
  22   */
  23  #[AllowDynamicProperties]
  24  class wp_xmlrpc_server extends IXR_Server {
  25      /**
  26       * Methods.
  27       *
  28       * @var array
  29       */
  30      public $methods;
  31  
  32      /**
  33       * Blog options.
  34       *
  35       * @var array
  36       */
  37      public $blog_options;
  38  
  39      /**
  40       * IXR_Error instance.
  41       *
  42       * @var IXR_Error
  43       */
  44      public $error;
  45  
  46      /**
  47       * Flags that the user authentication has failed in this instance of wp_xmlrpc_server.
  48       *
  49       * @var bool
  50       */
  51      protected $auth_failed = false;
  52  
  53      /**
  54       * Flags that a pingback has already been processed in this instance of wp_xmlrpc_server.
  55       *
  56       * Prevents a single `system.multicall` request from processing an unbounded number of pingbacks.
  57       *
  58       * @since 7.1.5
  59       *
  60       * @var bool
  61       */
  62      protected $pingback_processed = false;
  63  
  64      /**
  65       * Flags that XML-RPC is enabled
  66       *
  67       * @var bool
  68       */
  69      private $is_enabled;
  70  
  71      /**
  72       * Registers all of the XMLRPC methods that XMLRPC server understands.
  73       *
  74       * Sets up server and method property. Passes XMLRPC methods through the
  75       * {@see 'xmlrpc_methods'} filter to allow plugins to extend or replace
  76       * XML-RPC methods.
  77       *
  78       * @since 1.5.0
  79       */
  80  	public function __construct() {
  81          $this->methods = array(
  82              // WordPress API.
  83              'wp.getUsersBlogs'                 => 'this:wp_getUsersBlogs',
  84              'wp.newPost'                       => 'this:wp_newPost',
  85              'wp.editPost'                      => 'this:wp_editPost',
  86              'wp.deletePost'                    => 'this:wp_deletePost',
  87              'wp.getPost'                       => 'this:wp_getPost',
  88              'wp.getPosts'                      => 'this:wp_getPosts',
  89              'wp.newTerm'                       => 'this:wp_newTerm',
  90              'wp.editTerm'                      => 'this:wp_editTerm',
  91              'wp.deleteTerm'                    => 'this:wp_deleteTerm',
  92              'wp.getTerm'                       => 'this:wp_getTerm',
  93              'wp.getTerms'                      => 'this:wp_getTerms',
  94              'wp.getTaxonomy'                   => 'this:wp_getTaxonomy',
  95              'wp.getTaxonomies'                 => 'this:wp_getTaxonomies',
  96              'wp.getUser'                       => 'this:wp_getUser',
  97              'wp.getUsers'                      => 'this:wp_getUsers',
  98              'wp.getProfile'                    => 'this:wp_getProfile',
  99              'wp.editProfile'                   => 'this:wp_editProfile',
 100              'wp.getPage'                       => 'this:wp_getPage',
 101              'wp.getPages'                      => 'this:wp_getPages',
 102              'wp.newPage'                       => 'this:wp_newPage',
 103              'wp.deletePage'                    => 'this:wp_deletePage',
 104              'wp.editPage'                      => 'this:wp_editPage',
 105              'wp.getPageList'                   => 'this:wp_getPageList',
 106              'wp.getAuthors'                    => 'this:wp_getAuthors',
 107              'wp.getCategories'                 => 'this:mw_getCategories',     // Alias.
 108              'wp.getTags'                       => 'this:wp_getTags',
 109              'wp.newCategory'                   => 'this:wp_newCategory',
 110              'wp.deleteCategory'                => 'this:wp_deleteCategory',
 111              'wp.suggestCategories'             => 'this:wp_suggestCategories',
 112              'wp.uploadFile'                    => 'this:mw_newMediaObject',    // Alias.
 113              'wp.deleteFile'                    => 'this:wp_deletePost',        // Alias.
 114              'wp.getCommentCount'               => 'this:wp_getCommentCount',
 115              'wp.getPostStatusList'             => 'this:wp_getPostStatusList',
 116              'wp.getPageStatusList'             => 'this:wp_getPageStatusList',
 117              'wp.getPageTemplates'              => 'this:wp_getPageTemplates',
 118              'wp.getOptions'                    => 'this:wp_getOptions',
 119              'wp.setOptions'                    => 'this:wp_setOptions',
 120              'wp.getComment'                    => 'this:wp_getComment',
 121              'wp.getComments'                   => 'this:wp_getComments',
 122              'wp.deleteComment'                 => 'this:wp_deleteComment',
 123              'wp.editComment'                   => 'this:wp_editComment',
 124              'wp.newComment'                    => 'this:wp_newComment',
 125              'wp.getCommentStatusList'          => 'this:wp_getCommentStatusList',
 126              'wp.getMediaItem'                  => 'this:wp_getMediaItem',
 127              'wp.getMediaLibrary'               => 'this:wp_getMediaLibrary',
 128              'wp.getPostFormats'                => 'this:wp_getPostFormats',
 129              'wp.getPostType'                   => 'this:wp_getPostType',
 130              'wp.getPostTypes'                  => 'this:wp_getPostTypes',
 131              'wp.getRevisions'                  => 'this:wp_getRevisions',
 132              'wp.restoreRevision'               => 'this:wp_restoreRevision',
 133  
 134              // Blogger API.
 135              'blogger.getUsersBlogs'            => 'this:blogger_getUsersBlogs',
 136              'blogger.getUserInfo'              => 'this:blogger_getUserInfo',
 137              'blogger.getPost'                  => 'this:blogger_getPost',
 138              'blogger.getRecentPosts'           => 'this:blogger_getRecentPosts',
 139              'blogger.newPost'                  => 'this:blogger_newPost',
 140              'blogger.editPost'                 => 'this:blogger_editPost',
 141              'blogger.deletePost'               => 'this:blogger_deletePost',
 142  
 143              // MetaWeblog API (with MT extensions to structs).
 144              'metaWeblog.newPost'               => 'this:mw_newPost',
 145              'metaWeblog.editPost'              => 'this:mw_editPost',
 146              'metaWeblog.getPost'               => 'this:mw_getPost',
 147              'metaWeblog.getRecentPosts'        => 'this:mw_getRecentPosts',
 148              'metaWeblog.getCategories'         => 'this:mw_getCategories',
 149              'metaWeblog.newMediaObject'        => 'this:mw_newMediaObject',
 150  
 151              /*
 152               * MetaWeblog API aliases for Blogger API.
 153               * See http://www.xmlrpc.com/stories/storyReader$2460
 154               */
 155              'metaWeblog.deletePost'            => 'this:blogger_deletePost',
 156              'metaWeblog.getUsersBlogs'         => 'this:blogger_getUsersBlogs',
 157  
 158              // MovableType API.
 159              'mt.getCategoryList'               => 'this:mt_getCategoryList',
 160              'mt.getRecentPostTitles'           => 'this:mt_getRecentPostTitles',
 161              'mt.getPostCategories'             => 'this:mt_getPostCategories',
 162              'mt.setPostCategories'             => 'this:mt_setPostCategories',
 163              'mt.supportedMethods'              => 'this:mt_supportedMethods',
 164              'mt.supportedTextFilters'          => 'this:mt_supportedTextFilters',
 165              'mt.getTrackbackPings'             => 'this:mt_getTrackbackPings',
 166              'mt.publishPost'                   => 'this:mt_publishPost',
 167  
 168              // Pingback.
 169              'pingback.ping'                    => 'this:pingback_ping',
 170              'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
 171  
 172              'demo.sayHello'                    => 'this:sayHello',
 173              'demo.addTwoNumbers'               => 'this:addTwoNumbers',
 174          );
 175  
 176          $this->initialise_blog_option_info();
 177  
 178          /**
 179           * Filters the methods exposed by the XML-RPC server.
 180           *
 181           * This filter can be used to add new methods, and remove built-in methods.
 182           *
 183           * @since 1.5.0
 184           *
 185           * @param string[] $methods An array of XML-RPC methods, keyed by their methodName.
 186           */
 187          $this->methods = apply_filters( 'xmlrpc_methods', $this->methods );
 188  
 189          $this->set_is_enabled();
 190      }
 191  
 192      /**
 193       * Sets wp_xmlrpc_server::$is_enabled property.
 194       *
 195       * Determines whether the xmlrpc server is enabled on this WordPress install
 196       * and set the is_enabled property accordingly.
 197       *
 198       * @since 5.7.3
 199       */
 200  	private function set_is_enabled() {
 201          /*
 202           * Respect old get_option() filters left for back-compat when the 'enable_xmlrpc'
 203           * option was deprecated in 3.5.0. Use the {@see 'xmlrpc_enabled'} hook instead.
 204           */
 205          /** This filter is documented in wp-includes/option.php */
 206          $is_enabled = apply_filters( 'pre_option_enable_xmlrpc', false, 'enable_xmlrpc', false );
 207          if ( false === $is_enabled ) {
 208              /** This filter is documented in wp-includes/option.php */
 209              $is_enabled = apply_filters( 'option_enable_xmlrpc', true, 'enable_xmlrpc' );
 210          }
 211  
 212          /**
 213           * Filters whether XML-RPC methods requiring authentication are enabled.
 214           *
 215           * Contrary to the way it's named, this filter does not control whether XML-RPC is *fully*
 216           * enabled, rather, it only controls whether XML-RPC methods requiring authentication -
 217           * such as for publishing purposes - are enabled.
 218           *
 219           * Further, the filter does not control whether pingbacks or other custom endpoints that don't
 220           * require authentication are enabled. This behavior is expected, and due to how parity was matched
 221           * with the `enable_xmlrpc` UI option the filter replaced when it was introduced in 3.5.
 222           *
 223           * To disable XML-RPC methods that require authentication, use:
 224           *
 225           *     add_filter( 'xmlrpc_enabled', '__return_false' );
 226           *
 227           * For more granular control over all XML-RPC methods and requests, see the {@see 'xmlrpc_methods'}
 228           * and {@see 'xmlrpc_element_limit'} hooks.
 229           *
 230           * @since 3.5.0
 231           *
 232           * @param bool $is_enabled Whether XML-RPC is enabled. Default true.
 233           */
 234          $this->is_enabled = apply_filters( 'xmlrpc_enabled', $is_enabled );
 235      }
 236  
 237      /**
 238       * Makes private/protected methods readable for backward compatibility.
 239       *
 240       * @since 4.0.0
 241       *
 242       * @param string $name      Method to call.
 243       * @param array  $arguments Arguments to pass when calling.
 244       * @return array|IXR_Error|false Return value of the callback, false otherwise.
 245       */
 246  	public function __call( $name, $arguments ) {
 247          if ( '_multisite_getUsersBlogs' === $name ) {
 248              return $this->_multisite_getUsersBlogs( ...$arguments );
 249          }
 250          return false;
 251      }
 252  
 253      /**
 254       * Serves the XML-RPC request.
 255       *
 256       * @since 2.9.0
 257       */
 258  	public function serve_request() {
 259          $this->IXR_Server( $this->methods );
 260      }
 261  
 262      /**
 263       * Tests XMLRPC API by saying, "Hello!" to client.
 264       *
 265       * @since 1.5.0
 266       *
 267       * @return string Hello string response.
 268       */
 269  	public function sayHello() {
 270          return 'Hello!';
 271      }
 272  
 273      /**
 274       * Tests XMLRPC API by adding two numbers for client.
 275       *
 276       * @since 1.5.0
 277       *
 278       * @param int[] $args {
 279       *     Method arguments. Note: arguments must be ordered as documented.
 280       *
 281       *     @type int $0 A number to add.
 282       *     @type int $1 A second number to add.
 283       * }
 284       * @return int|IXR_Error Sum of the two given numbers.
 285       */
 286  	public function addTwoNumbers( $args ) {
 287          if ( ! is_array( $args ) || count( $args ) !== 2 || ! is_int( $args[0] ) || ! is_int( $args[1] ) ) {
 288              $this->error = new IXR_Error( 400, __( 'Invalid arguments passed to this XML-RPC method. Requires two integers.' ) );
 289              return $this->error;
 290          }
 291  
 292          $number1 = $args[0];
 293          $number2 = $args[1];
 294          return $number1 + $number2;
 295      }
 296  
 297      /**
 298       * Logs user in.
 299       *
 300       * @since 2.8.0
 301       * @since 7.2.0 Returns an error if the `$username` or `$password` argument is not a scalar.
 302       *
 303       * @param mixed $username User's username.
 304       * @param mixed $password User's password.
 305       * @return WP_User|false WP_User object if authentication passed, false otherwise.
 306       *
 307       * @phpstan-assert-if-true =scalar $username
 308       * @phpstan-assert-if-true =scalar $password
 309       */
 310  	public function login(
 311          $username,
 312          #[\SensitiveParameter]
 313          $password
 314      ) {
 315          if ( ! $this->is_enabled ) {
 316              $this->error = new IXR_Error( 405, __( 'XML-RPC services are disabled on this site.' ) );
 317              return false;
 318          }
 319  
 320          /*
 321           * Arrays and objects sent by the client would cause a fatal error in
 322           * wp_authenticate(). Other scalar types are tolerated and cast to
 323           * strings, which preserves backward compatibility.
 324           */
 325          if ( ! is_scalar( $username ) || ! is_scalar( $password ) ) {
 326              $this->error = new IXR_Error( 400, __( 'The username and password arguments should be strings.' ) );
 327              return false;
 328          }
 329  
 330          if ( $this->auth_failed ) {
 331              $user = new WP_Error( 'login_prevented' );
 332          } else {
 333              $user = wp_authenticate( (string) $username, (string) $password );
 334          }
 335  
 336          if ( is_wp_error( $user ) ) {
 337              $this->error = new IXR_Error( 403, __( 'Incorrect username or password.' ) );
 338  
 339              // Flag that authentication has failed once on this wp_xmlrpc_server instance.
 340              $this->auth_failed = true;
 341  
 342              /**
 343               * Filters the XML-RPC user login error message.
 344               *
 345               * @since 3.5.0
 346               *
 347               * @param IXR_Error $error The XML-RPC error message.
 348               * @param WP_Error  $user  WP_Error object.
 349               */
 350              $this->error = apply_filters( 'xmlrpc_login_error', $this->error, $user );
 351              return false;
 352          }
 353  
 354          wp_set_current_user( $user->ID );
 355          return $user;
 356      }
 357  
 358      /**
 359       * Checks user's credentials. Deprecated.
 360       *
 361       * @since 1.5.0
 362       * @deprecated 2.8.0 Use wp_xmlrpc_server::login()
 363       * @see wp_xmlrpc_server::login()
 364       *
 365       * @param mixed $username User's username.
 366       * @param mixed $password User's password.
 367       * @return bool Whether authentication passed.
 368       *
 369       * @phpstan-assert-if-true =scalar $username
 370       * @phpstan-assert-if-true =scalar $password
 371       */
 372  	public function login_pass_ok(
 373          $username,
 374          #[\SensitiveParameter]
 375          $password
 376      ) {
 377          return (bool) $this->login( $username, $password );
 378      }
 379  
 380      /**
 381       * Escapes string or array of strings for database.
 382       *
 383       * @since 1.5.2
 384       *
 385       * @param string|array $data Escape single string or array of strings.
 386       * @return string|null Returns with string if passed, alters by-reference
 387       *                     when array is passed.
 388       */
 389  	public function escape( &$data ) {
 390          if ( ! is_array( $data ) ) {
 391              return wp_slash( $data );
 392          }
 393  
 394          foreach ( $data as &$v ) {
 395              if ( is_array( $v ) ) {
 396                  $this->escape( $v );
 397              } elseif ( ! is_object( $v ) ) {
 398                  $v = wp_slash( $v );
 399              }
 400          }
 401          return null;
 402      }
 403  
 404      /**
 405       * Sends error response to client.
 406       *
 407       * Sends an XML error response to the client. If the endpoint is enabled
 408       * an HTTP 200 response is always sent per the XML-RPC specification.
 409       *
 410       * @since 5.7.3
 411       *
 412       * @param IXR_Error|int $error   Error code or an error object.
 413       * @param string|false  $message Error message. Optional. Default false.
 414       */
 415  	public function error( $error, $message = false ) {
 416          // Accepts either an error object or an error code and message
 417          if ( $message && ! is_object( $error ) ) {
 418              $error = new IXR_Error( $error, $message );
 419          }
 420  
 421          if ( ! $this->is_enabled ) {
 422              status_header( $error->code );
 423          }
 424  
 425          $this->output( $error->getXml() );
 426      }
 427  
 428      /**
 429       * Retrieves custom fields for post.
 430       *
 431       * @since 2.5.0
 432       *
 433       * @param int $post_id Post ID.
 434       * @return array Custom fields, if exist.
 435       */
 436  	public function get_custom_fields( $post_id ) {
 437          $post_id = (int) $post_id;
 438  
 439          $custom_fields = array();
 440  
 441          foreach ( (array) has_meta( $post_id ) as $meta ) {
 442              // Don't expose protected fields.
 443              if ( ! current_user_can( 'edit_post_meta', $post_id, $meta['meta_key'] ) ) {
 444                  continue;
 445              }
 446  
 447              $custom_fields[] = array(
 448                  'id'    => $meta['meta_id'],
 449                  'key'   => $meta['meta_key'],
 450                  'value' => $meta['meta_value'],
 451              );
 452          }
 453  
 454          return $custom_fields;
 455      }
 456  
 457      /**
 458       * Sets custom fields for post.
 459       *
 460       * @since 2.5.0
 461       *
 462       * @param int   $post_id Post ID.
 463       * @param array $fields  Custom fields.
 464       */
 465  	public function set_custom_fields( $post_id, $fields ) {
 466          $post_id = (int) $post_id;
 467  
 468          foreach ( (array) $fields as $meta ) {
 469              if ( isset( $meta['id'] ) ) {
 470                  $meta['id'] = (int) $meta['id'];
 471                  $pmeta      = get_metadata_by_mid( 'post', $meta['id'] );
 472  
 473                  if ( ! $pmeta || (int) $pmeta->post_id !== $post_id ) {
 474                      continue;
 475                  }
 476  
 477                  if ( isset( $meta['key'] ) ) {
 478                      $meta['key'] = wp_unslash( $meta['key'] );
 479                      if ( $meta['key'] !== $pmeta->meta_key ) {
 480                          continue;
 481                      }
 482                      $meta['value'] = wp_unslash( $meta['value'] );
 483                      if ( current_user_can( 'edit_post_meta', $post_id, $meta['key'] ) ) {
 484                          update_metadata_by_mid( 'post', $meta['id'], $meta['value'] );
 485                      }
 486                  } elseif ( current_user_can( 'delete_post_meta', $post_id, $pmeta->meta_key ) ) {
 487                      delete_metadata_by_mid( 'post', $meta['id'] );
 488                  }
 489              } elseif ( current_user_can( 'add_post_meta', $post_id, wp_unslash( $meta['key'] ) ) ) {
 490                  add_post_meta( $post_id, $meta['key'], $meta['value'] );
 491              }
 492          }
 493      }
 494  
 495      /**
 496       * Retrieves custom fields for a term.
 497       *
 498       * @since 4.9.0
 499       *
 500       * @param int $term_id Term ID.
 501       * @return array Array of custom fields, if they exist.
 502       */
 503  	public function get_term_custom_fields( $term_id ) {
 504          $term_id = (int) $term_id;
 505  
 506          $custom_fields = array();
 507  
 508          foreach ( (array) has_term_meta( $term_id ) as $meta ) {
 509  
 510              if ( ! current_user_can( 'edit_term_meta', $term_id ) ) {
 511                  continue;
 512              }
 513  
 514              $custom_fields[] = array(
 515                  'id'    => $meta['meta_id'],
 516                  'key'   => $meta['meta_key'],
 517                  'value' => $meta['meta_value'],
 518              );
 519          }
 520  
 521          return $custom_fields;
 522      }
 523  
 524      /**
 525       * Sets custom fields for a term.
 526       *
 527       * @since 4.9.0
 528       *
 529       * @param int   $term_id Term ID.
 530       * @param array $fields  Custom fields.
 531       */
 532  	public function set_term_custom_fields( $term_id, $fields ) {
 533          $term_id = (int) $term_id;
 534  
 535          foreach ( (array) $fields as $meta ) {
 536              if ( isset( $meta['id'] ) ) {
 537                  $meta['id'] = (int) $meta['id'];
 538                  $pmeta      = get_metadata_by_mid( 'term', $meta['id'] );
 539                  if ( isset( $meta['key'] ) ) {
 540                      $meta['key'] = wp_unslash( $meta['key'] );
 541                      if ( $meta['key'] !== $pmeta->meta_key ) {
 542                          continue;
 543                      }
 544                      $meta['value'] = wp_unslash( $meta['value'] );
 545                      if ( current_user_can( 'edit_term_meta', $term_id ) ) {
 546                          update_metadata_by_mid( 'term', $meta['id'], $meta['value'] );
 547                      }
 548                  } elseif ( current_user_can( 'delete_term_meta', $term_id ) ) {
 549                      delete_metadata_by_mid( 'term', $meta['id'] );
 550                  }
 551              } elseif ( current_user_can( 'add_term_meta', $term_id ) ) {
 552                  add_term_meta( $term_id, $meta['key'], $meta['value'] );
 553              }
 554          }
 555      }
 556  
 557      /**
 558       * Sets up blog options property.
 559       *
 560       * Passes property through {@see 'xmlrpc_blog_options'} filter.
 561       *
 562       * @since 2.6.0
 563       */
 564  	public function initialise_blog_option_info() {
 565          $this->blog_options = array(
 566              // Read-only options.
 567              'software_name'           => array(
 568                  'desc'     => __( 'Software Name' ),
 569                  'readonly' => true,
 570                  'value'    => 'WordPress',
 571              ),
 572              'software_version'        => array(
 573                  'desc'     => __( 'Software Version' ),
 574                  'readonly' => true,
 575                  'value'    => get_bloginfo( 'version' ),
 576              ),
 577              'blog_url'                => array(
 578                  'desc'     => __( 'WordPress Address (URL)' ),
 579                  'readonly' => true,
 580                  'option'   => 'siteurl',
 581              ),
 582              'home_url'                => array(
 583                  'desc'     => __( 'Site Address (URL)' ),
 584                  'readonly' => true,
 585                  'option'   => 'home',
 586              ),
 587              'login_url'               => array(
 588                  'desc'     => __( 'Login Address (URL)' ),
 589                  'readonly' => true,
 590                  'value'    => wp_login_url(),
 591              ),
 592              'admin_url'               => array(
 593                  'desc'     => __( 'The URL to the admin area' ),
 594                  'readonly' => true,
 595                  'value'    => get_admin_url(),
 596              ),
 597              'image_default_link_type' => array(
 598                  'desc'     => __( 'Image default link type' ),
 599                  'readonly' => true,
 600                  'option'   => 'image_default_link_type',
 601              ),
 602              'image_default_size'      => array(
 603                  'desc'     => __( 'Image default size' ),
 604                  'readonly' => true,
 605                  'option'   => 'image_default_size',
 606              ),
 607              'image_default_align'     => array(
 608                  'desc'     => __( 'Image default align' ),
 609                  'readonly' => true,
 610                  'option'   => 'image_default_align',
 611              ),
 612              'template'                => array(
 613                  'desc'     => __( 'Template' ),
 614                  'readonly' => true,
 615                  'option'   => 'template',
 616              ),
 617              'stylesheet'              => array(
 618                  'desc'     => __( 'Stylesheet' ),
 619                  'readonly' => true,
 620                  'option'   => 'stylesheet',
 621              ),
 622              'post_thumbnail'          => array(
 623                  'desc'     => __( 'Post Thumbnail' ),
 624                  'readonly' => true,
 625                  'value'    => current_theme_supports( 'post-thumbnails' ),
 626              ),
 627  
 628              // Updatable options.
 629              'time_zone'               => array(
 630                  'desc'     => __( 'Time Zone' ),
 631                  'readonly' => false,
 632                  'option'   => 'gmt_offset',
 633              ),
 634              'blog_title'              => array(
 635                  'desc'     => __( 'Site Title' ),
 636                  'readonly' => false,
 637                  'option'   => 'blogname',
 638              ),
 639              'blog_tagline'            => array(
 640                  'desc'     => __( 'Site Tagline' ),
 641                  'readonly' => false,
 642                  'option'   => 'blogdescription',
 643              ),
 644              'date_format'             => array(
 645                  'desc'     => __( 'Date Format' ),
 646                  'readonly' => false,
 647                  'option'   => 'date_format',
 648              ),
 649              'time_format'             => array(
 650                  'desc'     => __( 'Time Format' ),
 651                  'readonly' => false,
 652                  'option'   => 'time_format',
 653              ),
 654              'users_can_register'      => array(
 655                  'desc'     => __( 'Allow new users to sign up' ),
 656                  'readonly' => false,
 657                  'option'   => 'users_can_register',
 658              ),
 659              'thumbnail_size_w'        => array(
 660                  'desc'     => __( 'Thumbnail Width' ),
 661                  'readonly' => false,
 662                  'option'   => 'thumbnail_size_w',
 663              ),
 664              'thumbnail_size_h'        => array(
 665                  'desc'     => __( 'Thumbnail Height' ),
 666                  'readonly' => false,
 667                  'option'   => 'thumbnail_size_h',
 668              ),
 669              'thumbnail_crop'          => array(
 670                  'desc'     => __( 'Crop thumbnail to exact dimensions' ),
 671                  'readonly' => false,
 672                  'option'   => 'thumbnail_crop',
 673              ),
 674              'medium_size_w'           => array(
 675                  'desc'     => __( 'Medium size image width' ),
 676                  'readonly' => false,
 677                  'option'   => 'medium_size_w',
 678              ),
 679              'medium_size_h'           => array(
 680                  'desc'     => __( 'Medium size image height' ),
 681                  'readonly' => false,
 682                  'option'   => 'medium_size_h',
 683              ),
 684              'medium_large_size_w'     => array(
 685                  'desc'     => __( 'Medium-Large size image width' ),
 686                  'readonly' => false,
 687                  'option'   => 'medium_large_size_w',
 688              ),
 689              'medium_large_size_h'     => array(
 690                  'desc'     => __( 'Medium-Large size image height' ),
 691                  'readonly' => false,
 692                  'option'   => 'medium_large_size_h',
 693              ),
 694              'large_size_w'            => array(
 695                  'desc'     => __( 'Large size image width' ),
 696                  'readonly' => false,
 697                  'option'   => 'large_size_w',
 698              ),
 699              'large_size_h'            => array(
 700                  'desc'     => __( 'Large size image height' ),
 701                  'readonly' => false,
 702                  'option'   => 'large_size_h',
 703              ),
 704              'default_comment_status'  => array(
 705                  'desc'     => __( 'Allow people to submit comments on new posts.' ),
 706                  'readonly' => false,
 707                  'option'   => 'default_comment_status',
 708              ),
 709              'default_ping_status'     => array(
 710                  'desc'     => __( 'Allow link notifications from other blogs (pingbacks and trackbacks) on new posts.' ),
 711                  'readonly' => false,
 712                  'option'   => 'default_ping_status',
 713              ),
 714          );
 715  
 716          /**
 717           * Filters the XML-RPC blog options property.
 718           *
 719           * @since 2.6.0
 720           *
 721           * @param array $blog_options An array of XML-RPC blog options.
 722           */
 723          $this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options );
 724      }
 725  
 726      /**
 727       * Retrieves the blogs of the user.
 728       *
 729       * @since 2.6.0
 730       *
 731       * @param array $args {
 732       *     Method arguments. Note: arguments must be ordered as documented.
 733       *
 734       *     @type string $0 Username.
 735       *     @type string $1 Password.
 736       * }
 737       * @return array|IXR_Error Array contains:
 738       *  - 'isAdmin'
 739       *  - 'isPrimary' - whether the blog is the user's primary blog
 740       *  - 'url'
 741       *  - 'blogid'
 742       *  - 'blogName'
 743       *  - 'xmlrpc' - url of xmlrpc endpoint
 744       */
 745  	public function wp_getUsersBlogs( $args ) {
 746          if ( ! $this->minimum_args( $args, 2 ) ) {
 747              return $this->error;
 748          }
 749  
 750          // If this isn't on WPMU then just use blogger_getUsersBlogs().
 751          if ( ! is_multisite() ) {
 752              array_unshift( $args, 1 );
 753              return $this->blogger_getUsersBlogs( $args );
 754          }
 755  
 756          $this->escape( $args );
 757  
 758          $username = $args[0];
 759          $password = $args[1];
 760  
 761          $user = $this->login( $username, $password );
 762          if ( ! $user ) {
 763              return $this->error;
 764          }
 765  
 766          /**
 767           * Fires after the XML-RPC user has been authenticated but before the rest of
 768           * the method logic begins.
 769           *
 770           * All built-in XML-RPC methods use the action xmlrpc_call, with a parameter
 771           * equal to the method's name, e.g., wp.getUsersBlogs, wp.newPost, etc.
 772           *
 773           * @since 2.5.0
 774           * @since 5.7.0 Added the `$args` and `$server` parameters.
 775           *
 776           * @param string           $name   The method name.
 777           * @param array|string     $args   The escaped arguments passed to the method.
 778           * @param wp_xmlrpc_server $server The XML-RPC server instance.
 779           */
 780          do_action( 'xmlrpc_call', 'wp.getUsersBlogs', $args, $this );
 781  
 782          $blogs  = (array) get_blogs_of_user( $user->ID );
 783          $struct = array();
 784  
 785          $primary_blog_id = 0;
 786          $active_blog     = get_active_blog_for_user( $user->ID );
 787          if ( $active_blog ) {
 788              $primary_blog_id = (int) $active_blog->blog_id;
 789          }
 790  
 791          $current_network_id = get_current_network_id();
 792  
 793          foreach ( $blogs as $blog ) {
 794              // Don't include blogs that aren't hosted at this site.
 795              if ( $blog->site_id !== $current_network_id ) {
 796                  continue;
 797              }
 798  
 799              $blog_id = $blog->userblog_id;
 800  
 801              switch_to_blog( $blog_id );
 802  
 803              $is_admin   = current_user_can( 'manage_options' );
 804              $is_primary = ( (int) $blog_id === $primary_blog_id );
 805  
 806              $struct[] = array(
 807                  'isAdmin'   => $is_admin,
 808                  'isPrimary' => $is_primary,
 809                  'url'       => home_url( '/' ),
 810                  'blogid'    => (string) $blog_id,
 811                  'blogName'  => get_option( 'blogname' ),
 812                  'xmlrpc'    => site_url( 'xmlrpc.php', 'rpc' ),
 813              );
 814  
 815              restore_current_blog();
 816          }
 817  
 818          return $struct;
 819      }
 820  
 821      /**
 822       * Checks if the method received at least the minimum number of arguments.
 823       *
 824       * @since 3.4.0
 825       *
 826       * @param array $args  An array of arguments to check.
 827       * @param int   $count Minimum number of arguments.
 828       * @return bool True if `$args` contains at least `$count` arguments, false otherwise.
 829       */
 830  	protected function minimum_args( $args, $count ) {
 831          if ( ! is_array( $args ) || count( $args ) < $count ) {
 832              $this->error = new IXR_Error( 400, __( 'Insufficient arguments passed to this XML-RPC method.' ) );
 833              return false;
 834          }
 835  
 836          return true;
 837      }
 838  
 839      /**
 840       * Checks that the `$fields` argument received from a client is an array.
 841       *
 842       * @since 7.2.0
 843       *
 844       * @param mixed $fields The `$fields` argument to check.
 845       * @return bool True if `$fields` is an array, false otherwise.
 846       *
 847       * @phpstan-assert-if-true array $fields
 848       */
 849  	protected function _is_fields_array( $fields ): bool {
 850          if ( ! is_array( $fields ) ) {
 851              $this->error = new IXR_Error( 400, __( 'The fields argument must be an array.' ) );
 852              return false;
 853          }
 854  
 855          return true;
 856      }
 857  
 858      /**
 859       * Prepares taxonomy data for return in an XML-RPC object.
 860       *
 861       * @param WP_Taxonomy $taxonomy The unprepared taxonomy data.
 862       * @param array       $fields   The subset of taxonomy fields to return.
 863       * @return array The prepared taxonomy data.
 864       */
 865  	protected function _prepare_taxonomy( $taxonomy, $fields ) {
 866          $_taxonomy = array(
 867              'name'         => $taxonomy->name,
 868              'label'        => $taxonomy->label,
 869              'hierarchical' => (bool) $taxonomy->hierarchical,
 870              'public'       => (bool) $taxonomy->public,
 871              'show_ui'      => (bool) $taxonomy->show_ui,
 872              '_builtin'     => (bool) $taxonomy->_builtin,
 873          );
 874  
 875          if ( in_array( 'labels', $fields, true ) ) {
 876              $_taxonomy['labels'] = (array) $taxonomy->labels;
 877          }
 878  
 879          if ( in_array( 'cap', $fields, true ) ) {
 880              $_taxonomy['cap'] = (array) $taxonomy->cap;
 881          }
 882  
 883          if ( in_array( 'menu', $fields, true ) ) {
 884              $_taxonomy['show_in_menu'] = (bool) $taxonomy->show_in_menu;
 885          }
 886  
 887          if ( in_array( 'object_type', $fields, true ) ) {
 888              $_taxonomy['object_type'] = array_unique( (array) $taxonomy->object_type );
 889          }
 890  
 891          /**
 892           * Filters XML-RPC-prepared data for the given taxonomy.
 893           *
 894           * @since 3.4.0
 895           *
 896           * @param array       $_taxonomy An array of taxonomy data.
 897           * @param WP_Taxonomy $taxonomy  Taxonomy object.
 898           * @param array       $fields    The subset of taxonomy fields to return.
 899           */
 900          return apply_filters( 'xmlrpc_prepare_taxonomy', $_taxonomy, $taxonomy, $fields );
 901      }
 902  
 903      /**
 904       * Prepares term data for return in an XML-RPC object.
 905       *
 906       * @param array|object $term The unprepared term data.
 907       * @return array The prepared term data.
 908       */
 909  	protected function _prepare_term( $term ) {
 910          $_term = $term;
 911          if ( ! is_array( $_term ) ) {
 912              $_term = get_object_vars( $_term );
 913          }
 914  
 915          // For integers which may be larger than XML-RPC supports ensure we return strings.
 916          $_term['term_id']          = (string) $_term['term_id'];
 917          $_term['term_group']       = (string) $_term['term_group'];
 918          $_term['term_taxonomy_id'] = (string) $_term['term_taxonomy_id'];
 919          $_term['parent']           = (string) $_term['parent'];
 920  
 921          // Count we are happy to return as an integer because people really shouldn't use terms that much.
 922          $_term['count'] = (int) $_term['count'];
 923  
 924          // Get term meta.
 925          $_term['custom_fields'] = $this->get_term_custom_fields( $_term['term_id'] );
 926  
 927          /**
 928           * Filters XML-RPC-prepared data for the given term.
 929           *
 930           * @since 3.4.0
 931           *
 932           * @param array        $_term An array of term data.
 933           * @param array|object $term  Term object or array.
 934           */
 935          return apply_filters( 'xmlrpc_prepare_term', $_term, $term );
 936      }
 937  
 938      /**
 939       * Converts a WordPress date string to an IXR_Date object.
 940       *
 941       * @param string $date Date string to convert.
 942       * @return IXR_Date IXR_Date object.
 943       */
 944  	protected function _convert_date( $date ) {
 945          if ( '0000-00-00 00:00:00' === $date ) {
 946              return new IXR_Date( '00000000T00:00:00Z' );
 947          }
 948          return new IXR_Date( mysql2date( 'Ymd\TH:i:s', $date, false ) );
 949      }
 950  
 951      /**
 952       * Converts a WordPress GMT date string to an IXR_Date object.
 953       *
 954       * @param string $date_gmt WordPress GMT date string.
 955       * @param string $date     Date string.
 956       * @return IXR_Date IXR_Date object.
 957       */
 958  	protected function _convert_date_gmt( $date_gmt, $date ) {
 959          if ( '0000-00-00 00:00:00' !== $date && '0000-00-00 00:00:00' === $date_gmt ) {
 960              return new IXR_Date( get_gmt_from_date( mysql2date( 'Y-m-d H:i:s', $date, false ), 'Ymd\TH:i:s' ) );
 961          }
 962          return $this->_convert_date( $date_gmt );
 963      }
 964  
 965      /**
 966       * Prepares post data for return in an XML-RPC object.
 967       *
 968       * @param array $post   The unprepared post data.
 969       * @param array $fields The subset of post type fields to return.
 970       * @return array The prepared post data.
 971       */
 972  	protected function _prepare_post( $post, $fields ) {
 973          // Holds the data for this post. built up based on $fields.
 974          $_post = array( 'post_id' => (string) $post['ID'] );
 975  
 976          // Prepare common post fields.
 977          $post_fields = array(
 978              'post_title'        => $post['post_title'],
 979              'post_date'         => $this->_convert_date( $post['post_date'] ),
 980              'post_date_gmt'     => $this->_convert_date_gmt( $post['post_date_gmt'], $post['post_date'] ),
 981              'post_modified'     => $this->_convert_date( $post['post_modified'] ),
 982              'post_modified_gmt' => $this->_convert_date_gmt( $post['post_modified_gmt'], $post['post_modified'] ),
 983              'post_status'       => $post['post_status'],
 984              'post_type'         => $post['post_type'],
 985              'post_name'         => $post['post_name'],
 986              'post_author'       => $post['post_author'],
 987              'post_password'     => $post['post_password'],
 988              'post_excerpt'      => $post['post_excerpt'],
 989              'post_content'      => $post['post_content'],
 990              'post_parent'       => (string) $post['post_parent'],
 991              'post_mime_type'    => $post['post_mime_type'],
 992              'link'              => get_permalink( $post['ID'] ),
 993              'guid'              => $post['guid'],
 994              'menu_order'        => (int) $post['menu_order'],
 995              'comment_status'    => $post['comment_status'],
 996              'ping_status'       => $post['ping_status'],
 997              'sticky'            => ( 'post' === $post['post_type'] && is_sticky( $post['ID'] ) ),
 998          );
 999  
1000          // Thumbnail.
1001          $post_fields['post_thumbnail'] = array();
1002          $thumbnail_id                  = get_post_thumbnail_id( $post['ID'] );
1003          if ( $thumbnail_id ) {
1004              $thumbnail_size                = current_theme_supports( 'post-thumbnail' ) ? 'post-thumbnail' : 'thumbnail';
1005              $post_fields['post_thumbnail'] = $this->_prepare_media_item( get_post( $thumbnail_id ), $thumbnail_size );
1006          }
1007  
1008          // Consider future posts as published.
1009          if ( 'future' === $post_fields['post_status'] ) {
1010              $post_fields['post_status'] = 'publish';
1011          }
1012  
1013          // Fill in blank post format.
1014          $post_fields['post_format'] = get_post_format( $post['ID'] );
1015          if ( empty( $post_fields['post_format'] ) ) {
1016              $post_fields['post_format'] = 'standard';
1017          }
1018  
1019          // Merge requested $post_fields fields into $_post.
1020          if ( in_array( 'post', $fields, true ) ) {
1021              $_post = array_merge( $_post, $post_fields );
1022          } else {
1023              $requested_fields = array_intersect_key( $post_fields, array_flip( $fields ) );
1024              $_post            = array_merge( $_post, $requested_fields );
1025          }
1026  
1027          $all_taxonomy_fields = in_array( 'taxonomies', $fields, true );
1028  
1029          if ( $all_taxonomy_fields || in_array( 'terms', $fields, true ) ) {
1030              $post_type_taxonomies = get_object_taxonomies( $post['post_type'], 'names' );
1031              $terms                = wp_get_object_terms( $post['ID'], $post_type_taxonomies );
1032              $_post['terms']       = array();
1033              foreach ( $terms as $term ) {
1034                  $_post['terms'][] = $this->_prepare_term( $term );
1035              }
1036          }
1037  
1038          if ( in_array( 'custom_fields', $fields, true ) ) {
1039              $_post['custom_fields'] = $this->get_custom_fields( $post['ID'] );
1040          }
1041  
1042          if ( in_array( 'enclosure', $fields, true ) ) {
1043              $_post['enclosure'] = array();
1044              $enclosures         = (array) get_post_meta( $post['ID'], 'enclosure' );
1045              if ( ! empty( $enclosures ) ) {
1046                  $encdata                      = explode( "\n", $enclosures[0] );
1047                  $_post['enclosure']['url']    = trim( htmlspecialchars( $encdata[0] ) );
1048                  $_post['enclosure']['length'] = (int) trim( $encdata[1] );
1049                  $_post['enclosure']['type']   = trim( $encdata[2] );
1050              }
1051          }
1052  
1053          /**
1054           * Filters XML-RPC-prepared date for the given post.
1055           *
1056           * @since 3.4.0
1057           *
1058           * @param array $_post  An array of modified post data.
1059           * @param array $post   An array of post data.
1060           * @param array $fields An array of post fields.
1061           */
1062          return apply_filters( 'xmlrpc_prepare_post', $_post, $post, $fields );
1063      }
1064  
1065      /**
1066       * Prepares post data for return in an XML-RPC object.
1067       *
1068       * @since 3.4.0
1069       * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1070       *
1071       * @param WP_Post_Type $post_type Post type object.
1072       * @param array        $fields    The subset of post fields to return.
1073       * @return array The prepared post type data.
1074       */
1075  	protected function _prepare_post_type( $post_type, $fields ) {
1076          $_post_type = array(
1077              'name'         => $post_type->name,
1078              'label'        => $post_type->label,
1079              'hierarchical' => (bool) $post_type->hierarchical,
1080              'public'       => (bool) $post_type->public,
1081              'show_ui'      => (bool) $post_type->show_ui,
1082              '_builtin'     => (bool) $post_type->_builtin,
1083              'has_archive'  => (bool) $post_type->has_archive,
1084              'supports'     => get_all_post_type_supports( $post_type->name ),
1085          );
1086  
1087          if ( in_array( 'labels', $fields, true ) ) {
1088              $_post_type['labels'] = (array) $post_type->labels;
1089          }
1090  
1091          if ( in_array( 'cap', $fields, true ) ) {
1092              $_post_type['cap']          = (array) $post_type->cap;
1093              $_post_type['map_meta_cap'] = (bool) $post_type->map_meta_cap;
1094          }
1095  
1096          if ( in_array( 'menu', $fields, true ) ) {
1097              $_post_type['menu_position'] = (int) $post_type->menu_position;
1098              $_post_type['menu_icon']     = $post_type->menu_icon;
1099              $_post_type['show_in_menu']  = (bool) $post_type->show_in_menu;
1100          }
1101  
1102          if ( in_array( 'taxonomies', $fields, true ) ) {
1103              $_post_type['taxonomies'] = get_object_taxonomies( $post_type->name, 'names' );
1104          }
1105  
1106          /**
1107           * Filters XML-RPC-prepared date for the given post type.
1108           *
1109           * @since 3.4.0
1110           * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
1111           *
1112           * @param array        $_post_type An array of post type data.
1113           * @param WP_Post_Type $post_type  Post type object.
1114           */
1115          return apply_filters( 'xmlrpc_prepare_post_type', $_post_type, $post_type );
1116      }
1117  
1118      /**
1119       * Prepares media item data for return in an XML-RPC object.
1120       *
1121       * @param WP_Post $media_item     The unprepared media item data.
1122       * @param string  $thumbnail_size The image size to use for the thumbnail URL.
1123       * @return array The prepared media item data.
1124       */
1125  	protected function _prepare_media_item( $media_item, $thumbnail_size = 'thumbnail' ) {
1126          $_media_item = array(
1127              'attachment_id'    => (string) $media_item->ID,
1128              'date_created_gmt' => $this->_convert_date_gmt( $media_item->post_date_gmt, $media_item->post_date ),
1129              'parent'           => $media_item->post_parent,
1130              'link'             => wp_get_attachment_url( $media_item->ID ),
1131              'title'            => $media_item->post_title,
1132              'caption'          => $media_item->post_excerpt,
1133              'description'      => $media_item->post_content,
1134              'metadata'         => wp_get_attachment_metadata( $media_item->ID ),
1135              'type'             => $media_item->post_mime_type,
1136              'alt'              => get_post_meta( $media_item->ID, '_wp_attachment_image_alt', true ),
1137          );
1138  
1139          $thumbnail_src = image_downsize( $media_item->ID, $thumbnail_size );
1140          if ( $thumbnail_src ) {
1141              $_media_item['thumbnail'] = $thumbnail_src[0];
1142          } else {
1143              $_media_item['thumbnail'] = $_media_item['link'];
1144          }
1145  
1146          /**
1147           * Filters XML-RPC-prepared data for the given media item.
1148           *
1149           * @since 3.4.0
1150           *
1151           * @param array   $_media_item    An array of media item data.
1152           * @param WP_Post $media_item     Media item object.
1153           * @param string  $thumbnail_size Image size.
1154           */
1155          return apply_filters( 'xmlrpc_prepare_media_item', $_media_item, $media_item, $thumbnail_size );
1156      }
1157  
1158      /**
1159       * Prepares page data for return in an XML-RPC object.
1160       *
1161       * @param WP_Post $page The unprepared page data.
1162       * @return array The prepared page data.
1163       */
1164  	protected function _prepare_page( $page ) {
1165          // Get all of the page content and link.
1166          $full_page = get_extended( $page->post_content );
1167          $link      = get_permalink( $page->ID );
1168  
1169          // Get info the page parent if there is one.
1170          $parent_title = '';
1171          if ( ! empty( $page->post_parent ) ) {
1172              $parent       = get_post( $page->post_parent );
1173              $parent_title = $parent->post_title;
1174          }
1175  
1176          // Determine comment and ping settings.
1177          $allow_comments = comments_open( $page->ID ) ? 1 : 0;
1178          $allow_pings    = pings_open( $page->ID ) ? 1 : 0;
1179  
1180          // Format page date.
1181          $page_date     = $this->_convert_date( $page->post_date );
1182          $page_date_gmt = $this->_convert_date_gmt( $page->post_date_gmt, $page->post_date );
1183  
1184          // Pull the categories info together.
1185          $categories = array();
1186          if ( is_object_in_taxonomy( 'page', 'category' ) ) {
1187              foreach ( wp_get_post_categories( $page->ID ) as $cat_id ) {
1188                  $categories[] = get_cat_name( $cat_id );
1189              }
1190          }
1191  
1192          // Get the author info.
1193          $author = get_userdata( $page->post_author );
1194  
1195          $page_template = get_page_template_slug( $page->ID );
1196          if ( empty( $page_template ) ) {
1197              $page_template = 'default';
1198          }
1199  
1200          $_page = array(
1201              'dateCreated'            => $page_date,
1202              'userid'                 => $page->post_author,
1203              'page_id'                => $page->ID,
1204              'page_status'            => $page->post_status,
1205              'description'            => $full_page['main'],
1206              'title'                  => $page->post_title,
1207              'link'                   => $link,
1208              'permaLink'              => $link,
1209              'categories'             => $categories,
1210              'excerpt'                => $page->post_excerpt,
1211              'text_more'              => $full_page['extended'],
1212              'mt_allow_comments'      => $allow_comments,
1213              'mt_allow_pings'         => $allow_pings,
1214              'wp_slug'                => $page->post_name,
1215              'wp_password'            => $page->post_password,
1216              'wp_author'              => $author->display_name,
1217              'wp_page_parent_id'      => $page->post_parent,
1218              'wp_page_parent_title'   => $parent_title,
1219              'wp_page_order'          => $page->menu_order,
1220              'wp_author_id'           => (string) $author->ID,
1221              'wp_author_display_name' => $author->display_name,
1222              'date_created_gmt'       => $page_date_gmt,
1223              'custom_fields'          => $this->get_custom_fields( $page->ID ),
1224              'wp_page_template'       => $page_template,
1225          );
1226  
1227          /**
1228           * Filters XML-RPC-prepared data for the given page.
1229           *
1230           * @since 3.4.0
1231           *
1232           * @param array   $_page An array of page data.
1233           * @param WP_Post $page  Page object.
1234           */
1235          return apply_filters( 'xmlrpc_prepare_page', $_page, $page );
1236      }
1237  
1238      /**
1239       * Prepares comment data for return in an XML-RPC object.
1240       *
1241       * @param WP_Comment $comment The unprepared comment data.
1242       * @return array The prepared comment data.
1243       */
1244  	protected function _prepare_comment( $comment ) {
1245          // Format page date.
1246          $comment_date_gmt = $this->_convert_date_gmt( $comment->comment_date_gmt, $comment->comment_date );
1247  
1248          if ( '0' === $comment->comment_approved ) {
1249              $comment_status = 'hold';
1250          } elseif ( 'spam' === $comment->comment_approved ) {
1251              $comment_status = 'spam';
1252          } elseif ( '1' === $comment->comment_approved ) {
1253              $comment_status = 'approve';
1254          } else {
1255              $comment_status = $comment->comment_approved;
1256          }
1257  
1258          $can_moderate_or_edit = current_user_can( 'moderate_comments' ) || current_user_can( 'edit_comment', $comment->comment_ID );
1259  
1260          $_comment = array(
1261              'date_created_gmt' => $comment_date_gmt,
1262              'user_id'          => $comment->user_id,
1263              'comment_id'       => $comment->comment_ID,
1264              'parent'           => $comment->comment_parent,
1265              'status'           => $comment_status,
1266              'content'          => $comment->comment_content,
1267              'link'             => get_comment_link( $comment ),
1268              'post_id'          => $comment->comment_post_ID,
1269              'post_title'       => get_the_title( $comment->comment_post_ID ),
1270              'author'           => $comment->comment_author,
1271              'author_url'       => $comment->comment_author_url,
1272              'author_email'     => $can_moderate_or_edit ? $comment->comment_author_email : '',
1273              'author_ip'        => $can_moderate_or_edit ? $comment->comment_author_IP : '',
1274              'type'             => $comment->comment_type,
1275          );
1276  
1277          /**
1278           * Filters XML-RPC-prepared data for the given comment.
1279           *
1280           * @since 3.4.0
1281           *
1282           * @param array      $_comment An array of prepared comment data.
1283           * @param WP_Comment $comment  Comment object.
1284           */
1285          return apply_filters( 'xmlrpc_prepare_comment', $_comment, $comment );
1286      }
1287  
1288      /**
1289       * Prepares user data for return in an XML-RPC object.
1290       *
1291       * @param WP_User $user   The unprepared user object.
1292       * @param array   $fields The subset of user fields to return.
1293       * @return array The prepared user data.
1294       */
1295  	protected function _prepare_user( $user, $fields ) {
1296          $_user = array( 'user_id' => (string) $user->ID );
1297  
1298          $user_fields = array(
1299              'username'     => $user->user_login,
1300              'first_name'   => $user->user_firstname,
1301              'last_name'    => $user->user_lastname,
1302              'registered'   => $this->_convert_date( $user->user_registered ),
1303              'bio'          => $user->user_description,
1304              'email'        => $user->user_email,
1305              'nickname'     => $user->nickname,
1306              'nicename'     => $user->user_nicename,
1307              'url'          => $user->user_url,
1308              'display_name' => $user->display_name,
1309              'roles'        => $user->roles,
1310          );
1311  
1312          if ( in_array( 'all', $fields, true ) ) {
1313              $_user = array_merge( $_user, $user_fields );
1314          } else {
1315              if ( in_array( 'basic', $fields, true ) ) {
1316                  $basic_fields = array( 'username', 'email', 'registered', 'display_name', 'nicename' );
1317                  $fields       = array_merge( $fields, $basic_fields );
1318              }
1319              $requested_fields = array_intersect_key( $user_fields, array_flip( $fields ) );
1320              $_user            = array_merge( $_user, $requested_fields );
1321          }
1322  
1323          /**
1324           * Filters XML-RPC-prepared data for the given user.
1325           *
1326           * @since 3.5.0
1327           *
1328           * @param array   $_user  An array of user data.
1329           * @param WP_User $user   User object.
1330           * @param array   $fields An array of user fields.
1331           */
1332          return apply_filters( 'xmlrpc_prepare_user', $_user, $user, $fields );
1333      }
1334  
1335      /**
1336       * Creates a new post for any registered post type.
1337       *
1338       * @since 3.4.0
1339       *
1340       * @link https://en.wikipedia.org/wiki/RSS_enclosure for information on RSS enclosures.
1341       *
1342       * @param array $args {
1343       *     Method arguments. Note: top-level arguments must be ordered as documented.
1344       *
1345       *     @type int    $0 Blog ID (unused).
1346       *     @type string $1 Username.
1347       *     @type string $2 Password.
1348       *     @type array  $3 {
1349       *         Content struct for adding a new post. See wp_insert_post() for information on
1350       *         additional post fields
1351       *
1352       *         @type string $post_type      Post type. Default 'post'.
1353       *         @type string $post_status    Post status. Default 'draft'
1354       *         @type string $post_title     Post title.
1355       *         @type int    $post_author    Post author ID.
1356       *         @type string $post_excerpt   Post excerpt.
1357       *         @type string $post_content   Post content.
1358       *         @type string $post_date_gmt  Post date in GMT.
1359       *         @type string $post_date      Post date.
1360       *         @type string $post_password  Post password (20-character limit).
1361       *         @type string $comment_status Post comment enabled status. Accepts 'open' or 'closed'.
1362       *         @type string $ping_status    Post ping status. Accepts 'open' or 'closed'.
1363       *         @type bool   $sticky         Whether the post should be sticky. Automatically false if
1364       *                                      `$post_status` is 'private'.
1365       *         @type int    $post_thumbnail ID of an image to use as the post thumbnail/featured image.
1366       *         @type array  $custom_fields  Array of meta key/value pairs to add to the post.
1367       *         @type array  $terms          Associative array with taxonomy names as keys and arrays
1368       *                                      of term IDs as values.
1369       *         @type array  $terms_names    Associative array with taxonomy names as keys and arrays
1370       *                                      of term names as values.
1371       *         @type array  $enclosure      {
1372       *             Array of feed enclosure data to add to post meta.
1373       *
1374       *             @type string $url    URL for the feed enclosure.
1375       *             @type int    $length Size in bytes of the enclosure.
1376       *             @type string $type   Mime-type for the enclosure.
1377       *         }
1378       *     }
1379       * }
1380       * @return int|IXR_Error Post ID on success, IXR_Error instance otherwise.
1381       */
1382  	public function wp_newPost( $args ) {
1383          if ( ! $this->minimum_args( $args, 4 ) ) {
1384              return $this->error;
1385          }
1386  
1387          $this->escape( $args );
1388  
1389          $username       = $args[1];
1390          $password       = $args[2];
1391          $content_struct = $args[3];
1392  
1393          $user = $this->login( $username, $password );
1394          if ( ! $user ) {
1395              return $this->error;
1396          }
1397  
1398          // Convert the date field back to IXR form.
1399          if ( isset( $content_struct['post_date'] ) && ! ( $content_struct['post_date'] instanceof IXR_Date ) ) {
1400              $content_struct['post_date'] = $this->_convert_date( $content_struct['post_date'] );
1401          }
1402  
1403          /*
1404           * Ignore the existing GMT date if it is empty or a non-GMT date was supplied in $content_struct,
1405           * since _insert_post() will ignore the non-GMT date if the GMT date is set.
1406           */
1407          if ( isset( $content_struct['post_date_gmt'] ) && ! ( $content_struct['post_date_gmt'] instanceof IXR_Date ) ) {
1408              if ( '0000-00-00 00:00:00' === $content_struct['post_date_gmt'] || isset( $content_struct['post_date'] ) ) {
1409                  unset( $content_struct['post_date_gmt'] );
1410              } else {
1411                  $content_struct['post_date_gmt'] = $this->_convert_date( $content_struct['post_date_gmt'] );
1412              }
1413          }
1414  
1415          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
1416          do_action( 'xmlrpc_call', 'wp.newPost', $args, $this );
1417  
1418          unset( $content_struct['ID'] );
1419  
1420          return $this->_insert_post( $user, $content_struct );
1421      }
1422  
1423      /**
1424       * Helper method for filtering out elements from an array.
1425       *
1426       * @since 3.4.0
1427       *
1428       * @param int $count Number to compare to one.
1429       * @return bool True if the number is greater than one, false otherwise.
1430       */
1431  	private function _is_greater_than_one( $count ) {
1432          return $count > 1;
1433      }
1434  
1435      /**
1436       * Encapsulates the logic for sticking a post and determining if
1437       * the user has permission to do so.
1438       *
1439       * @since 4.3.0
1440       *
1441       * @param array $post_data
1442       * @param bool  $update
1443       * @return void|IXR_Error
1444       */
1445  	private function _toggle_sticky( $post_data, $update = false ) {
1446          $post_type = get_post_type_object( $post_data['post_type'] );
1447  
1448          // Private and password-protected posts cannot be stickied.
1449          if ( 'private' === $post_data['post_status'] || ! empty( $post_data['post_password'] ) ) {
1450              // Error if the client tried to stick the post, otherwise, silently unstick.
1451              if ( ! empty( $post_data['sticky'] ) ) {
1452                  return new IXR_Error( 401, __( 'Sorry, you cannot stick a private post.' ) );
1453              }
1454  
1455              if ( $update ) {
1456                  unstick_post( $post_data['ID'] );
1457              }
1458          } elseif ( isset( $post_data['sticky'] ) ) {
1459              if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
1460                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to make posts sticky.' ) );
1461              }
1462  
1463              $sticky = wp_validate_boolean( $post_data['sticky'] );
1464              if ( $sticky ) {
1465                  stick_post( $post_data['ID'] );
1466              } else {
1467                  unstick_post( $post_data['ID'] );
1468              }
1469          }
1470      }
1471  
1472      /**
1473       * Helper method for wp_newPost() and wp_editPost(), containing shared logic.
1474       *
1475       * @since 3.4.0
1476       *
1477       * @see wp_insert_post()
1478       *
1479       * @param WP_User         $user           The post author if post_author isn't set in $content_struct.
1480       * @param array|IXR_Error $content_struct Post data to insert.
1481       * @return IXR_Error|string
1482       */
1483  	protected function _insert_post( $user, $content_struct ) {
1484          $defaults = array(
1485              'post_status'    => 'draft',
1486              'post_type'      => 'post',
1487              'post_author'    => 0,
1488              'post_password'  => '',
1489              'post_excerpt'   => '',
1490              'post_content'   => '',
1491              'post_title'     => '',
1492              'post_date'      => '',
1493              'post_date_gmt'  => '',
1494              'post_format'    => null,
1495              'post_name'      => null,
1496              'post_thumbnail' => null,
1497              'post_parent'    => 0,
1498              'ping_status'    => '',
1499              'comment_status' => '',
1500              'custom_fields'  => null,
1501              'terms_names'    => null,
1502              'terms'          => null,
1503              'sticky'         => null,
1504              'enclosure'      => null,
1505              'ID'             => null,
1506          );
1507  
1508          $post_data = wp_parse_args( array_intersect_key( $content_struct, $defaults ), $defaults );
1509  
1510          $post_type = get_post_type_object( $post_data['post_type'] );
1511          if ( ! $post_type ) {
1512              return new IXR_Error( 403, __( 'Invalid post type.' ) );
1513          }
1514  
1515          // Reject writes to internal-only builtin post types (e.g. customize_changeset)
1516          // whose intended write path is a dedicated helper, not a generic post API.
1517          $is_internal_only = (
1518              empty( $post_type->public )
1519              && empty( $post_type->show_in_rest )
1520              && ! empty( $post_type->_builtin )
1521          );
1522  
1523          /**
1524           * Filters whether a post type accepts writes via XML-RPC.
1525           *
1526           * Defaults to false for internal-only builtin post types (public=false,
1527           * show_in_rest=false, _builtin=true), such as customize_changeset, whose
1528           * writes are meant to flow through dedicated helpers. Return true to opt
1529           * a post type back in.
1530           *
1531           * @since 7.1.1
1532           *
1533           * @param bool         $allowed   Whether the post type accepts XML-RPC writes.
1534           * @param WP_Post_Type $post_type The post type object.
1535           */
1536          $allowed = apply_filters( 'xmlrpc_allow_post_type_writes', ! $is_internal_only, $post_type );
1537  
1538          if ( ! $allowed ) {
1539              return new IXR_Error( 403, __( 'Sorry, this post type is not supported over XML-RPC.' ) );
1540          }
1541  
1542          $update = ! empty( $post_data['ID'] );
1543  
1544          if ( $update ) {
1545              if ( ! get_post( $post_data['ID'] ) ) {
1546                  return new IXR_Error( 401, __( 'Invalid post ID.' ) );
1547              }
1548              if ( ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
1549                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
1550              }
1551              if ( get_post_type( $post_data['ID'] ) !== $post_data['post_type'] ) {
1552                  return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
1553              }
1554          } else {
1555              if ( ! current_user_can( $post_type->cap->create_posts ) || ! current_user_can( $post_type->cap->edit_posts ) ) {
1556                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to post on this site.' ) );
1557              }
1558          }
1559  
1560          switch ( $post_data['post_status'] ) {
1561              case 'draft':
1562              case 'pending':
1563                  break;
1564              case 'private':
1565                  if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1566                      return new IXR_Error( 401, __( 'Sorry, you are not allowed to create private posts in this post type.' ) );
1567                  }
1568                  break;
1569              case 'publish':
1570              case 'future':
1571                  if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1572                      return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts in this post type.' ) );
1573                  }
1574                  break;
1575              default:
1576                  if ( ! get_post_status_object( $post_data['post_status'] ) ) {
1577                      $post_data['post_status'] = 'draft';
1578                  }
1579                  break;
1580          }
1581  
1582          if ( ! empty( $post_data['post_password'] ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
1583              return new IXR_Error( 401, __( 'Sorry, you are not allowed to create password protected posts in this post type.' ) );
1584          }
1585  
1586          $post_data['post_author'] = absint( $post_data['post_author'] );
1587          if ( ! empty( $post_data['post_author'] ) && $post_data['post_author'] !== $user->ID ) {
1588              if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
1589                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
1590              }
1591  
1592              $author = get_userdata( $post_data['post_author'] );
1593  
1594              if ( ! $author ) {
1595                  return new IXR_Error( 404, __( 'Invalid author ID.' ) );
1596              }
1597          } else {
1598              $post_data['post_author'] = $user->ID;
1599          }
1600  
1601          if ( 'open' !== $post_data['comment_status'] && 'closed' !== $post_data['comment_status'] ) {
1602              unset( $post_data['comment_status'] );
1603          }
1604  
1605          if ( 'open' !== $post_data['ping_status'] && 'closed' !== $post_data['ping_status'] ) {
1606              unset( $post_data['ping_status'] );
1607          }
1608  
1609          // Do some timestamp voodoo.
1610          if ( ! empty( $post_data['post_date_gmt'] ) ) {
1611              // We know this is supposed to be GMT, so we're going to slap that Z on there by force.
1612              $date_created = rtrim( $post_data['post_date_gmt']->getIso(), 'Z' ) . 'Z';
1613          } elseif ( ! empty( $post_data['post_date'] ) ) {
1614              $date_created = $post_data['post_date']->getIso();
1615          }
1616  
1617          // Default to not flagging the post date to be edited unless it's intentional.
1618          $post_data['edit_date'] = false;
1619  
1620          if ( ! empty( $date_created ) ) {
1621              $post_data['post_date']     = iso8601_to_datetime( $date_created );
1622              $post_data['post_date_gmt'] = iso8601_to_datetime( $date_created, 'gmt' );
1623  
1624              // Flag the post date to be edited.
1625              $post_data['edit_date'] = true;
1626          }
1627  
1628          if ( ! isset( $post_data['ID'] ) ) {
1629              $post_data['ID'] = get_default_post_to_edit( $post_data['post_type'], true )->ID;
1630          }
1631          $post_id = $post_data['ID'];
1632  
1633          if ( 'post' === $post_data['post_type'] ) {
1634              $error = $this->_toggle_sticky( $post_data, $update );
1635              if ( $error ) {
1636                  return $error;
1637              }
1638          }
1639  
1640          if ( isset( $post_data['post_thumbnail'] ) ) {
1641              // Empty value deletes, non-empty value adds/updates.
1642              if ( ! $post_data['post_thumbnail'] ) {
1643                  delete_post_thumbnail( $post_id );
1644              } elseif ( ! get_post( absint( $post_data['post_thumbnail'] ) ) ) {
1645                  return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
1646              }
1647              set_post_thumbnail( $post_id, $post_data['post_thumbnail'] );
1648              unset( $content_struct['post_thumbnail'] );
1649          }
1650  
1651          if ( isset( $post_data['custom_fields'] ) ) {
1652              $this->set_custom_fields( $post_id, $post_data['custom_fields'] );
1653          }
1654  
1655          if ( isset( $post_data['terms'] ) || isset( $post_data['terms_names'] ) ) {
1656              $post_type_taxonomies = get_object_taxonomies( $post_data['post_type'], 'objects' );
1657  
1658              // Accumulate term IDs from terms and terms_names.
1659              $terms = array();
1660  
1661              // First validate the terms specified by ID.
1662              if ( isset( $post_data['terms'] ) && is_array( $post_data['terms'] ) ) {
1663                  $taxonomies = array_keys( $post_data['terms'] );
1664  
1665                  // Validating term IDs.
1666                  foreach ( $taxonomies as $taxonomy ) {
1667                      if ( ! array_key_exists( $taxonomy, $post_type_taxonomies ) ) {
1668                          return new IXR_Error( 401, __( 'Sorry, one of the given taxonomies is not supported by the post type.' ) );
1669                      }
1670  
1671                      if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->assign_terms ) ) {
1672                          return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign a term to one of the given taxonomies.' ) );
1673                      }
1674  
1675                      $term_ids           = $post_data['terms'][ $taxonomy ];
1676                      $terms[ $taxonomy ] = array();
1677                      foreach ( $term_ids as $term_id ) {
1678                          $term = get_term_by( 'id', $term_id, $taxonomy );
1679  
1680                          if ( ! $term ) {
1681                              return new IXR_Error( 403, __( 'Invalid term ID.' ) );
1682                          }
1683  
1684                          $terms[ $taxonomy ][] = (int) $term_id;
1685                      }
1686                  }
1687              }
1688  
1689              // Now validate terms specified by name.
1690              if ( isset( $post_data['terms_names'] ) && is_array( $post_data['terms_names'] ) ) {
1691                  $taxonomies = array_keys( $post_data['terms_names'] );
1692  
1693                  foreach ( $taxonomies as $taxonomy ) {
1694                      if ( ! array_key_exists( $taxonomy, $post_type_taxonomies ) ) {
1695                          return new IXR_Error( 401, __( 'Sorry, one of the given taxonomies is not supported by the post type.' ) );
1696                      }
1697  
1698                      if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->assign_terms ) ) {
1699                          return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign a term to one of the given taxonomies.' ) );
1700                      }
1701  
1702                      /*
1703                       * For hierarchical taxonomies, we can't assign a term when multiple terms
1704                       * in the hierarchy share the same name.
1705                       */
1706                      $ambiguous_terms = array();
1707                      if ( is_taxonomy_hierarchical( $taxonomy ) ) {
1708                          $tax_term_names = get_terms(
1709                              array(
1710                                  'taxonomy'   => $taxonomy,
1711                                  'fields'     => 'names',
1712                                  'hide_empty' => false,
1713                              )
1714                          );
1715  
1716                          // Count the number of terms with the same name.
1717                          $tax_term_names_count = array_count_values( $tax_term_names );
1718  
1719                          // Filter out non-ambiguous term names.
1720                          $ambiguous_tax_term_counts = array_filter( $tax_term_names_count, array( $this, '_is_greater_than_one' ) );
1721  
1722                          $ambiguous_terms = array_keys( $ambiguous_tax_term_counts );
1723                      }
1724  
1725                      $term_names = $post_data['terms_names'][ $taxonomy ];
1726                      foreach ( $term_names as $term_name ) {
1727                          if ( in_array( $term_name, $ambiguous_terms, true ) ) {
1728                              return new IXR_Error( 401, __( 'Ambiguous term name used in a hierarchical taxonomy. Please use term ID instead.' ) );
1729                          }
1730  
1731                          $term = get_term_by( 'name', $term_name, $taxonomy );
1732  
1733                          if ( ! $term ) {
1734                              // Term doesn't exist, so check that the user is allowed to create new terms.
1735                              if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->edit_terms ) ) {
1736                                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to add a term to one of the given taxonomies.' ) );
1737                              }
1738  
1739                              // Create the new term.
1740                              $term_info = wp_insert_term( $term_name, $taxonomy );
1741                              if ( is_wp_error( $term_info ) ) {
1742                                  return new IXR_Error( 500, $term_info->get_error_message() );
1743                              }
1744  
1745                              $terms[ $taxonomy ][] = (int) $term_info['term_id'];
1746                          } else {
1747                              $terms[ $taxonomy ][] = (int) $term->term_id;
1748                          }
1749                      }
1750                  }
1751              }
1752  
1753              $post_data['tax_input'] = $terms;
1754              unset( $post_data['terms'], $post_data['terms_names'] );
1755          }
1756  
1757          if ( isset( $post_data['post_format'] ) ) {
1758              $format = set_post_format( $post_id, $post_data['post_format'] );
1759  
1760              if ( is_wp_error( $format ) ) {
1761                  return new IXR_Error( 500, $format->get_error_message() );
1762              }
1763  
1764              unset( $post_data['post_format'] );
1765          }
1766  
1767          // Handle enclosures.
1768          $enclosure = $post_data['enclosure'] ?? null;
1769          $this->add_enclosure_if_new( $post_id, $enclosure );
1770  
1771          $this->attach_uploads( $post_id, $post_data['post_content'] );
1772  
1773          /**
1774           * Filters post data array to be inserted via XML-RPC.
1775           *
1776           * @since 3.4.0
1777           *
1778           * @param array $post_data      Parsed array of post data.
1779           * @param array $content_struct Post data array.
1780           */
1781          $post_data = apply_filters( 'xmlrpc_wp_insert_post_data', $post_data, $content_struct );
1782  
1783          // Remove all null values to allow for using the insert/update post default values for those keys instead.
1784          $post_data = array_filter(
1785              $post_data,
1786              static function ( $value ) {
1787                  return null !== $value;
1788              }
1789          );
1790  
1791          $post_id = $update ? wp_update_post( $post_data, true ) : wp_insert_post( $post_data, true );
1792          if ( is_wp_error( $post_id ) ) {
1793              return new IXR_Error( 500, $post_id->get_error_message() );
1794          }
1795  
1796          if ( ! $post_id ) {
1797              if ( $update ) {
1798                  return new IXR_Error( 401, __( 'Sorry, the post could not be updated.' ) );
1799              } else {
1800                  return new IXR_Error( 401, __( 'Sorry, the post could not be created.' ) );
1801              }
1802          }
1803  
1804          return (string) $post_id;
1805      }
1806  
1807      /**
1808       * Edits a post for any registered post type.
1809       *
1810       * The $content_struct parameter only needs to contain fields that
1811       * should be changed. All other fields will retain their existing values.
1812       *
1813       * @since 3.4.0
1814       *
1815       * @param array $args {
1816       *     Method arguments. Note: arguments must be ordered as documented.
1817       *
1818       *     @type int    $0 Blog ID (unused).
1819       *     @type string $1 Username.
1820       *     @type string $2 Password.
1821       *     @type int    $3 Post ID.
1822       *     @type array  $4 Extra content arguments.
1823       * }
1824       * @return true|IXR_Error True on success, IXR_Error on failure.
1825       */
1826  	public function wp_editPost( $args ) {
1827          if ( ! $this->minimum_args( $args, 5 ) ) {
1828              return $this->error;
1829          }
1830  
1831          $this->escape( $args );
1832  
1833          $username       = $args[1];
1834          $password       = $args[2];
1835          $post_id        = (int) $args[3];
1836          $content_struct = $args[4];
1837  
1838          $user = $this->login( $username, $password );
1839          if ( ! $user ) {
1840              return $this->error;
1841          }
1842  
1843          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
1844          do_action( 'xmlrpc_call', 'wp.editPost', $args, $this );
1845  
1846          $post = get_post( $post_id, ARRAY_A );
1847  
1848          if ( empty( $post['ID'] ) ) {
1849              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1850          }
1851  
1852          if ( isset( $content_struct['if_not_modified_since'] ) ) {
1853              // If the post has been modified since the date provided, return an error.
1854              if ( mysql2date( 'U', $post['post_modified_gmt'] ) > $content_struct['if_not_modified_since']->getTimestamp() ) {
1855                  return new IXR_Error( 409, __( 'There is a revision of this post that is more recent.' ) );
1856              }
1857          }
1858  
1859          // Convert the date field back to IXR form.
1860          $post['post_date'] = $this->_convert_date( $post['post_date'] );
1861  
1862          /*
1863           * Ignore the existing GMT date if it is empty or a non-GMT date was supplied in $content_struct,
1864           * since _insert_post() will ignore the non-GMT date if the GMT date is set.
1865           */
1866          if ( '0000-00-00 00:00:00' === $post['post_date_gmt'] || isset( $content_struct['post_date'] ) ) {
1867              unset( $post['post_date_gmt'] );
1868          } else {
1869              $post['post_date_gmt'] = $this->_convert_date( $post['post_date_gmt'] );
1870          }
1871  
1872          /*
1873           * If the API client did not provide 'post_date', then we must not perpetuate the value that
1874           * was stored in the database, or it will appear to be an intentional edit. Conveying it here
1875           * as if it was coming from the API client will cause an otherwise zeroed out 'post_date_gmt'
1876           * to get set with the value that was originally stored in the database when the draft was created.
1877           */
1878          if ( ! isset( $content_struct['post_date'] ) ) {
1879              unset( $post['post_date'] );
1880          }
1881  
1882          $this->escape( $post );
1883          $merged_content_struct = array_merge( $post, $content_struct );
1884  
1885          $retval = $this->_insert_post( $user, $merged_content_struct );
1886          if ( $retval instanceof IXR_Error ) {
1887              return $retval;
1888          }
1889  
1890          return true;
1891      }
1892  
1893      /**
1894       * Deletes a post for any registered post type.
1895       *
1896       * @since 3.4.0
1897       *
1898       * @see wp_delete_post()
1899       *
1900       * @param array $args {
1901       *     Method arguments. Note: arguments must be ordered as documented.
1902       *
1903       *     @type int    $0 Blog ID (unused).
1904       *     @type string $1 Username.
1905       *     @type string $2 Password.
1906       *     @type int    $3 Post ID.
1907       * }
1908       * @return true|IXR_Error True on success, IXR_Error instance on failure.
1909       */
1910  	public function wp_deletePost( $args ) {
1911          if ( ! $this->minimum_args( $args, 4 ) ) {
1912              return $this->error;
1913          }
1914  
1915          $this->escape( $args );
1916  
1917          $username = $args[1];
1918          $password = $args[2];
1919          $post_id  = (int) $args[3];
1920  
1921          $user = $this->login( $username, $password );
1922          if ( ! $user ) {
1923              return $this->error;
1924          }
1925  
1926          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
1927          do_action( 'xmlrpc_call', 'wp.deletePost', $args, $this );
1928  
1929          $post = get_post( $post_id, ARRAY_A );
1930          if ( empty( $post['ID'] ) ) {
1931              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1932          }
1933  
1934          if ( ! current_user_can( 'delete_post', $post_id ) ) {
1935              return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
1936          }
1937  
1938          $result = wp_delete_post( $post_id );
1939  
1940          if ( ! $result ) {
1941              return new IXR_Error( 500, __( 'Sorry, the post could not be deleted.' ) );
1942          }
1943  
1944          return true;
1945      }
1946  
1947      /**
1948       * Retrieves a post.
1949       *
1950       * @since 3.4.0
1951       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
1952       *
1953       * The optional $fields parameter specifies what fields will be included
1954       * in the response array. This should be a list of field names. 'post_id' will
1955       * always be included in the response regardless of the value of $fields.
1956       *
1957       * Instead of, or in addition to, individual field names, conceptual group
1958       * names can be used to specify multiple fields. The available conceptual
1959       * groups are 'post' (all basic fields), 'taxonomies', 'custom_fields',
1960       * and 'enclosure'.
1961       *
1962       * @see get_post()
1963       *
1964       * @param array $args {
1965       *     Method arguments. Note: arguments must be ordered as documented.
1966       *
1967       *     @type int    $0 Blog ID (unused).
1968       *     @type string $1 Username.
1969       *     @type string $2 Password.
1970       *     @type int    $3 Post ID.
1971       *     @type array  $4 Optional. The subset of post type fields to return.
1972       * }
1973       * @return array|IXR_Error Array contains (based on $fields parameter):
1974       *  - 'post_id'
1975       *  - 'post_title'
1976       *  - 'post_date'
1977       *  - 'post_date_gmt'
1978       *  - 'post_modified'
1979       *  - 'post_modified_gmt'
1980       *  - 'post_status'
1981       *  - 'post_type'
1982       *  - 'post_name'
1983       *  - 'post_author'
1984       *  - 'post_password'
1985       *  - 'post_excerpt'
1986       *  - 'post_content'
1987       *  - 'link'
1988       *  - 'comment_status'
1989       *  - 'ping_status'
1990       *  - 'sticky'
1991       *  - 'custom_fields'
1992       *  - 'terms'
1993       *  - 'categories'
1994       *  - 'tags'
1995       *  - 'enclosure'
1996       */
1997  	public function wp_getPost( $args ) {
1998          if ( ! $this->minimum_args( $args, 4 ) ) {
1999              return $this->error;
2000          }
2001  
2002          $this->escape( $args );
2003  
2004          $username = $args[1];
2005          $password = $args[2];
2006          $post_id  = (int) $args[3];
2007  
2008          if ( isset( $args[4] ) ) {
2009              if ( ! $this->_is_fields_array( $args[4] ) ) {
2010                  return $this->error;
2011              }
2012  
2013              $fields = $args[4];
2014          } else {
2015              /**
2016               * Filters the default post query fields used by the given XML-RPC method.
2017               *
2018               * @since 3.4.0
2019               *
2020               * @param array  $fields An array of post fields to retrieve. By default,
2021               *                       contains 'post', 'terms', and 'custom_fields'.
2022               * @param string $method Method name.
2023               */
2024              $fields = apply_filters( 'xmlrpc_default_post_fields', array( 'post', 'terms', 'custom_fields' ), 'wp.getPost' );
2025          }
2026  
2027          $user = $this->login( $username, $password );
2028          if ( ! $user ) {
2029              return $this->error;
2030          }
2031  
2032          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2033          do_action( 'xmlrpc_call', 'wp.getPost', $args, $this );
2034  
2035          $post = get_post( $post_id, ARRAY_A );
2036  
2037          if ( empty( $post['ID'] ) ) {
2038              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
2039          }
2040  
2041          if ( ! current_user_can( 'edit_post', $post_id ) ) {
2042              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
2043          }
2044  
2045          return $this->_prepare_post( $post, $fields );
2046      }
2047  
2048      /**
2049       * Retrieves posts.
2050       *
2051       * @since 3.4.0
2052       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
2053       *
2054       * @see wp_get_recent_posts()
2055       * @see wp_getPost() for more on `$fields`
2056       * @see get_posts() for more on `$filter` values
2057       *
2058       * @param array $args {
2059       *     Method arguments. Note: arguments must be ordered as documented.
2060       *
2061       *     @type int    $0 Blog ID (unused).
2062       *     @type string $1 Username.
2063       *     @type string $2 Password.
2064       *     @type array  $3 Optional. Modifies the query used to retrieve posts. Accepts 'post_type',
2065       *                     'post_status', 'number', 'offset', 'orderby', 's', and 'order'.
2066       *                     Default empty array.
2067       *     @type array  $4 Optional. The subset of post type fields to return in the response array.
2068       * }
2069       * @return array|IXR_Error Array containing a collection of posts.
2070       */
2071  	public function wp_getPosts( $args ) {
2072          if ( ! $this->minimum_args( $args, 3 ) ) {
2073              return $this->error;
2074          }
2075  
2076          $this->escape( $args );
2077  
2078          $username = $args[1];
2079          $password = $args[2];
2080          $filter   = $args[3] ?? array();
2081  
2082          if ( isset( $args[4] ) ) {
2083              if ( ! $this->_is_fields_array( $args[4] ) ) {
2084                  return $this->error;
2085              }
2086  
2087              $fields = $args[4];
2088          } else {
2089              /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2090              $fields = apply_filters( 'xmlrpc_default_post_fields', array( 'post', 'terms', 'custom_fields' ), 'wp.getPosts' );
2091          }
2092  
2093          $user = $this->login( $username, $password );
2094          if ( ! $user ) {
2095              return $this->error;
2096          }
2097  
2098          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2099          do_action( 'xmlrpc_call', 'wp.getPosts', $args, $this );
2100  
2101          $query = array();
2102  
2103          if ( isset( $filter['post_type'] ) ) {
2104              $post_type = get_post_type_object( $filter['post_type'] );
2105              if ( ! ( (bool) $post_type ) ) {
2106                  return new IXR_Error( 403, __( 'Invalid post type.' ) );
2107              }
2108          } else {
2109              $post_type = get_post_type_object( 'post' );
2110          }
2111  
2112          if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
2113              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
2114          }
2115  
2116          $query['post_type'] = $post_type->name;
2117  
2118          if ( isset( $filter['post_status'] ) ) {
2119              $query['post_status'] = $filter['post_status'];
2120          }
2121  
2122          if ( isset( $filter['number'] ) ) {
2123              $query['numberposts'] = absint( $filter['number'] );
2124          }
2125  
2126          if ( isset( $filter['offset'] ) ) {
2127              $query['offset'] = absint( $filter['offset'] );
2128          }
2129  
2130          if ( isset( $filter['orderby'] ) ) {
2131              $query['orderby'] = $filter['orderby'];
2132  
2133              if ( isset( $filter['order'] ) ) {
2134                  $query['order'] = $filter['order'];
2135              }
2136          }
2137  
2138          if ( isset( $filter['s'] ) ) {
2139              $query['s'] = $filter['s'];
2140          }
2141  
2142          $posts_list = wp_get_recent_posts( $query );
2143  
2144          if ( ! $posts_list ) {
2145              return array();
2146          }
2147  
2148          // Holds all the posts data.
2149          $struct = array();
2150  
2151          foreach ( $posts_list as $post ) {
2152              if ( ! current_user_can( 'edit_post', $post['ID'] ) ) {
2153                  continue;
2154              }
2155  
2156              $struct[] = $this->_prepare_post( $post, $fields );
2157          }
2158  
2159          return $struct;
2160      }
2161  
2162      /**
2163       * Creates a new term.
2164       *
2165       * @since 3.4.0
2166       *
2167       * @see wp_insert_term()
2168       *
2169       * @param array $args {
2170       *     Method arguments. Note: arguments must be ordered as documented.
2171       *
2172       *     @type int    $0 Blog ID (unused).
2173       *     @type string $1 Username.
2174       *     @type string $2 Password.
2175       *     @type array  $3 Content struct for adding a new term. The struct must contain
2176       *                     the term 'name' and 'taxonomy'. Optional accepted values include
2177       *                     'parent', 'description', and 'slug'.
2178       * }
2179       * @return int|IXR_Error The term ID on success, or an IXR_Error object on failure.
2180       */
2181  	public function wp_newTerm( $args ) {
2182          if ( ! $this->minimum_args( $args, 4 ) ) {
2183              return $this->error;
2184          }
2185  
2186          $this->escape( $args );
2187  
2188          $username       = $args[1];
2189          $password       = $args[2];
2190          $content_struct = $args[3];
2191  
2192          $user = $this->login( $username, $password );
2193          if ( ! $user ) {
2194              return $this->error;
2195          }
2196  
2197          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2198          do_action( 'xmlrpc_call', 'wp.newTerm', $args, $this );
2199  
2200          if ( ! taxonomy_exists( $content_struct['taxonomy'] ) ) {
2201              return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2202          }
2203  
2204          $taxonomy = get_taxonomy( $content_struct['taxonomy'] );
2205  
2206          if ( ! current_user_can( $taxonomy->cap->edit_terms ) ) {
2207              return new IXR_Error( 401, __( 'Sorry, you are not allowed to create terms in this taxonomy.' ) );
2208          }
2209  
2210          $taxonomy = (array) $taxonomy;
2211  
2212          // Hold the data of the term.
2213          $term_data = array();
2214  
2215          $term_data['name'] = trim( $content_struct['name'] );
2216          if ( empty( $term_data['name'] ) ) {
2217              return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
2218          }
2219  
2220          if ( isset( $content_struct['parent'] ) ) {
2221              if ( ! $taxonomy['hierarchical'] ) {
2222                  return new IXR_Error( 403, __( 'This taxonomy is not hierarchical.' ) );
2223              }
2224  
2225              $parent_term_id = (int) $content_struct['parent'];
2226              $parent_term    = get_term( $parent_term_id, $taxonomy['name'] );
2227  
2228              if ( is_wp_error( $parent_term ) ) {
2229                  return new IXR_Error( 500, $parent_term->get_error_message() );
2230              }
2231  
2232              if ( ! $parent_term ) {
2233                  return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
2234              }
2235  
2236              $term_data['parent'] = $content_struct['parent'];
2237          }
2238  
2239          if ( isset( $content_struct['description'] ) ) {
2240              $term_data['description'] = $content_struct['description'];
2241          }
2242  
2243          if ( isset( $content_struct['slug'] ) ) {
2244              $term_data['slug'] = $content_struct['slug'];
2245          }
2246  
2247          $term = wp_insert_term( $term_data['name'], $taxonomy['name'], $term_data );
2248  
2249          if ( is_wp_error( $term ) ) {
2250              return new IXR_Error( 500, $term->get_error_message() );
2251          }
2252  
2253          if ( ! $term ) {
2254              return new IXR_Error( 500, __( 'Sorry, the term could not be created.' ) );
2255          }
2256  
2257          // Add term meta.
2258          if ( isset( $content_struct['custom_fields'] ) ) {
2259              $this->set_term_custom_fields( $term['term_id'], $content_struct['custom_fields'] );
2260          }
2261  
2262          return (string) $term['term_id'];
2263      }
2264  
2265      /**
2266       * Edits a term.
2267       *
2268       * @since 3.4.0
2269       *
2270       * @see wp_update_term()
2271       *
2272       * @param array $args {
2273       *     Method arguments. Note: arguments must be ordered as documented.
2274       *
2275       *     @type int    $0 Blog ID (unused).
2276       *     @type string $1 Username.
2277       *     @type string $2 Password.
2278       *     @type int    $3 Term ID.
2279       *     @type array  $4 Content struct for editing a term. The struct must contain the
2280       *                     term 'taxonomy'. Optional accepted values include 'name', 'parent',
2281       *                     'description', and 'slug'.
2282       * }
2283       * @return true|IXR_Error True on success, IXR_Error instance on failure.
2284       */
2285  	public function wp_editTerm( $args ) {
2286          if ( ! $this->minimum_args( $args, 5 ) ) {
2287              return $this->error;
2288          }
2289  
2290          $this->escape( $args );
2291  
2292          $username       = $args[1];
2293          $password       = $args[2];
2294          $term_id        = (int) $args[3];
2295          $content_struct = $args[4];
2296  
2297          $user = $this->login( $username, $password );
2298          if ( ! $user ) {
2299              return $this->error;
2300          }
2301  
2302          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2303          do_action( 'xmlrpc_call', 'wp.editTerm', $args, $this );
2304  
2305          if ( ! isset( $content_struct['taxonomy'] )
2306              || ! taxonomy_exists( $content_struct['taxonomy'] )
2307          ) {
2308              return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2309          }
2310  
2311          $taxonomy = get_taxonomy( $content_struct['taxonomy'] );
2312  
2313          $taxonomy = (array) $taxonomy;
2314  
2315          // Hold the data of the term.
2316          $term_data = array();
2317  
2318          $term = get_term( $term_id, $content_struct['taxonomy'] );
2319  
2320          if ( is_wp_error( $term ) ) {
2321              return new IXR_Error( 500, $term->get_error_message() );
2322          }
2323  
2324          if ( ! $term ) {
2325              return new IXR_Error( 404, __( 'Invalid term ID.' ) );
2326          }
2327  
2328          if ( ! current_user_can( 'edit_term', $term_id ) ) {
2329              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this term.' ) );
2330          }
2331  
2332          if ( isset( $content_struct['name'] ) ) {
2333              $term_data['name'] = trim( $content_struct['name'] );
2334  
2335              if ( empty( $term_data['name'] ) ) {
2336                  return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
2337              }
2338          }
2339  
2340          if ( ! empty( $content_struct['parent'] ) ) {
2341              if ( ! $taxonomy['hierarchical'] ) {
2342                  return new IXR_Error( 403, __( 'Cannot set parent term, taxonomy is not hierarchical.' ) );
2343              }
2344  
2345              $parent_term_id = (int) $content_struct['parent'];
2346              $parent_term    = get_term( $parent_term_id, $taxonomy['name'] );
2347  
2348              if ( is_wp_error( $parent_term ) ) {
2349                  return new IXR_Error( 500, $parent_term->get_error_message() );
2350              }
2351  
2352              if ( ! $parent_term ) {
2353                  return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
2354              }
2355  
2356              $term_data['parent'] = $content_struct['parent'];
2357          }
2358  
2359          if ( isset( $content_struct['description'] ) ) {
2360              $term_data['description'] = $content_struct['description'];
2361          }
2362  
2363          if ( isset( $content_struct['slug'] ) ) {
2364              $term_data['slug'] = $content_struct['slug'];
2365          }
2366  
2367          $term = wp_update_term( $term_id, $taxonomy['name'], $term_data );
2368  
2369          if ( is_wp_error( $term ) ) {
2370              return new IXR_Error( 500, $term->get_error_message() );
2371          }
2372  
2373          if ( ! $term ) {
2374              return new IXR_Error( 500, __( 'Sorry, editing the term failed.' ) );
2375          }
2376  
2377          // Update term meta.
2378          if ( isset( $content_struct['custom_fields'] ) ) {
2379              $this->set_term_custom_fields( $term_id, $content_struct['custom_fields'] );
2380          }
2381  
2382          return true;
2383      }
2384  
2385      /**
2386       * Deletes a term.
2387       *
2388       * @since 3.4.0
2389       *
2390       * @see wp_delete_term()
2391       *
2392       * @param array $args {
2393       *     Method arguments. Note: arguments must be ordered as documented.
2394       *
2395       *     @type int    $0 Blog ID (unused).
2396       *     @type string $1 Username.
2397       *     @type string $2 Password.
2398       *     @type string $3 Taxonomy name.
2399       *     @type int    $4 Term ID.
2400       * }
2401       * @return true|IXR_Error True on success, IXR_Error instance on failure.
2402       */
2403  	public function wp_deleteTerm( $args ) {
2404          if ( ! $this->minimum_args( $args, 5 ) ) {
2405              return $this->error;
2406          }
2407  
2408          $this->escape( $args );
2409  
2410          $username = $args[1];
2411          $password = $args[2];
2412          $taxonomy = $args[3];
2413          $term_id  = (int) $args[4];
2414  
2415          $user = $this->login( $username, $password );
2416          if ( ! $user ) {
2417              return $this->error;
2418          }
2419  
2420          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2421          do_action( 'xmlrpc_call', 'wp.deleteTerm', $args, $this );
2422  
2423          if ( ! taxonomy_exists( $taxonomy ) ) {
2424              return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2425          }
2426  
2427          $taxonomy = get_taxonomy( $taxonomy );
2428          $term     = get_term( $term_id, $taxonomy->name );
2429  
2430          if ( is_wp_error( $term ) ) {
2431              return new IXR_Error( 500, $term->get_error_message() );
2432          }
2433  
2434          if ( ! $term ) {
2435              return new IXR_Error( 404, __( 'Invalid term ID.' ) );
2436          }
2437  
2438          if ( ! current_user_can( 'delete_term', $term_id ) ) {
2439              return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this term.' ) );
2440          }
2441  
2442          $result = wp_delete_term( $term_id, $taxonomy->name );
2443  
2444          if ( is_wp_error( $result ) ) {
2445              return new IXR_Error( 500, $result->get_error_message() );
2446          }
2447  
2448          if ( ! $result ) {
2449              return new IXR_Error( 500, __( 'Sorry, deleting the term failed.' ) );
2450          }
2451  
2452          return $result;
2453      }
2454  
2455      /**
2456       * Retrieves a term.
2457       *
2458       * @since 3.4.0
2459       *
2460       * @see get_term()
2461       *
2462       * @param array $args {
2463       *     Method arguments. Note: arguments must be ordered as documented.
2464       *
2465       *     @type int    $0 Blog ID (unused).
2466       *     @type string $1 Username.
2467       *     @type string $2 Password.
2468       *     @type string $3 Taxonomy name.
2469       *     @type int    $4 Term ID.
2470       * }
2471       * @return array|IXR_Error IXR_Error on failure, array on success, containing:
2472       *  - 'term_id'
2473       *  - 'name'
2474       *  - 'slug'
2475       *  - 'term_group'
2476       *  - 'term_taxonomy_id'
2477       *  - 'taxonomy'
2478       *  - 'description'
2479       *  - 'parent'
2480       *  - 'count'
2481       */
2482  	public function wp_getTerm( $args ) {
2483          if ( ! $this->minimum_args( $args, 5 ) ) {
2484              return $this->error;
2485          }
2486  
2487          $this->escape( $args );
2488  
2489          $username = $args[1];
2490          $password = $args[2];
2491          $taxonomy = $args[3];
2492          $term_id  = (int) $args[4];
2493  
2494          $user = $this->login( $username, $password );
2495          if ( ! $user ) {
2496              return $this->error;
2497          }
2498  
2499          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2500          do_action( 'xmlrpc_call', 'wp.getTerm', $args, $this );
2501  
2502          if ( ! taxonomy_exists( $taxonomy ) ) {
2503              return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2504          }
2505  
2506          $taxonomy = get_taxonomy( $taxonomy );
2507  
2508          $term = get_term( $term_id, $taxonomy->name, ARRAY_A );
2509  
2510          if ( is_wp_error( $term ) ) {
2511              return new IXR_Error( 500, $term->get_error_message() );
2512          }
2513  
2514          if ( ! $term ) {
2515              return new IXR_Error( 404, __( 'Invalid term ID.' ) );
2516          }
2517  
2518          if ( ! current_user_can( 'assign_term', $term_id ) ) {
2519              return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign this term.' ) );
2520          }
2521  
2522          return $this->_prepare_term( $term );
2523      }
2524  
2525      /**
2526       * Retrieves all terms for a taxonomy.
2527       *
2528       * @since 3.4.0
2529       *
2530       * The optional $filter parameter modifies the query used to retrieve terms.
2531       * Accepted keys are 'number', 'offset', 'orderby', 'order', 'hide_empty', and 'search'.
2532       *
2533       * @see get_terms()
2534       *
2535       * @param array $args {
2536       *     Method arguments. Note: arguments must be ordered as documented.
2537       *
2538       *     @type int    $0 Blog ID (unused).
2539       *     @type string $1 Username.
2540       *     @type string $2 Password.
2541       *     @type string $3 Taxonomy name.
2542       *     @type array  $4 Optional. Modifies the query used to retrieve posts. Accepts 'number',
2543       *                     'offset', 'orderby', 'order', 'hide_empty', and 'search'. Default empty array.
2544       * }
2545       * @return array|IXR_Error An associative array of terms data on success, IXR_Error instance otherwise.
2546       */
2547  	public function wp_getTerms( $args ) {
2548          if ( ! $this->minimum_args( $args, 4 ) ) {
2549              return $this->error;
2550          }
2551  
2552          $this->escape( $args );
2553  
2554          $username = $args[1];
2555          $password = $args[2];
2556          $taxonomy = $args[3];
2557          $filter   = $args[4] ?? array();
2558  
2559          $user = $this->login( $username, $password );
2560          if ( ! $user ) {
2561              return $this->error;
2562          }
2563  
2564          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2565          do_action( 'xmlrpc_call', 'wp.getTerms', $args, $this );
2566  
2567          if ( ! taxonomy_exists( $taxonomy ) ) {
2568              return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2569          }
2570  
2571          $taxonomy = get_taxonomy( $taxonomy );
2572  
2573          if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
2574              return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
2575          }
2576  
2577          $query = array( 'taxonomy' => $taxonomy->name );
2578  
2579          if ( isset( $filter['number'] ) ) {
2580              $query['number'] = absint( $filter['number'] );
2581          }
2582  
2583          if ( isset( $filter['offset'] ) ) {
2584              $query['offset'] = absint( $filter['offset'] );
2585          }
2586  
2587          if ( isset( $filter['orderby'] ) ) {
2588              $query['orderby'] = $filter['orderby'];
2589  
2590              if ( isset( $filter['order'] ) ) {
2591                  $query['order'] = $filter['order'];
2592              }
2593          }
2594  
2595          if ( isset( $filter['hide_empty'] ) ) {
2596              $query['hide_empty'] = $filter['hide_empty'];
2597          } else {
2598              $query['get'] = 'all';
2599          }
2600  
2601          if ( isset( $filter['search'] ) ) {
2602              $query['search'] = $filter['search'];
2603          }
2604  
2605          $terms = get_terms( $query );
2606  
2607          if ( is_wp_error( $terms ) ) {
2608              return new IXR_Error( 500, $terms->get_error_message() );
2609          }
2610  
2611          $struct = array();
2612  
2613          foreach ( $terms as $term ) {
2614              $struct[] = $this->_prepare_term( $term );
2615          }
2616  
2617          return $struct;
2618      }
2619  
2620      /**
2621       * Retrieves a taxonomy.
2622       *
2623       * @since 3.4.0
2624       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
2625       *
2626       * @see get_taxonomy()
2627       *
2628       * @param array $args {
2629       *     Method arguments. Note: arguments must be ordered as documented.
2630       *
2631       *     @type int    $0 Blog ID (unused).
2632       *     @type string $1 Username.
2633       *     @type string $2 Password.
2634       *     @type string $3 Taxonomy name.
2635       *     @type array  $4 Optional. Array of taxonomy fields to limit to in the return.
2636       *                     Accepts 'labels', 'cap', 'menu', and 'object_type'.
2637       *                     Default empty array.
2638       * }
2639       * @return array|IXR_Error An array of taxonomy data on success, IXR_Error instance otherwise.
2640       */
2641  	public function wp_getTaxonomy( $args ) {
2642          if ( ! $this->minimum_args( $args, 4 ) ) {
2643              return $this->error;
2644          }
2645  
2646          $this->escape( $args );
2647  
2648          $username = $args[1];
2649          $password = $args[2];
2650          $taxonomy = $args[3];
2651  
2652          if ( isset( $args[4] ) ) {
2653              if ( ! $this->_is_fields_array( $args[4] ) ) {
2654                  return $this->error;
2655              }
2656  
2657              $fields = $args[4];
2658          } else {
2659              /**
2660               * Filters the default taxonomy query fields used by the given XML-RPC method.
2661               *
2662               * @since 3.4.0
2663               *
2664               * @param array  $fields An array of taxonomy fields to retrieve. By default,
2665               *                       contains 'labels', 'cap', and 'object_type'.
2666               * @param string $method The method name.
2667               */
2668              $fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomy' );
2669          }
2670  
2671          $user = $this->login( $username, $password );
2672          if ( ! $user ) {
2673              return $this->error;
2674          }
2675  
2676          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2677          do_action( 'xmlrpc_call', 'wp.getTaxonomy', $args, $this );
2678  
2679          if ( ! taxonomy_exists( $taxonomy ) ) {
2680              return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2681          }
2682  
2683          $taxonomy = get_taxonomy( $taxonomy );
2684  
2685          if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
2686              return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
2687          }
2688  
2689          return $this->_prepare_taxonomy( $taxonomy, $fields );
2690      }
2691  
2692      /**
2693       * Retrieves all taxonomies.
2694       *
2695       * @since 3.4.0
2696       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
2697       *
2698       * @see get_taxonomies()
2699       *
2700       * @param array $args {
2701       *     Method arguments. Note: arguments must be ordered as documented.
2702       *
2703       *     @type int    $0 Blog ID (unused).
2704       *     @type string $1 Username.
2705       *     @type string $2 Password.
2706       *     @type array  $3 Optional. An array of arguments for retrieving taxonomies.
2707       *     @type array  $4 Optional. The subset of taxonomy fields to return.
2708       * }
2709       * @return array|IXR_Error An associative array of taxonomy data with returned fields determined
2710       *                         by `$fields`, or an IXR_Error instance on failure.
2711       */
2712  	public function wp_getTaxonomies( $args ) {
2713          if ( ! $this->minimum_args( $args, 3 ) ) {
2714              return $this->error;
2715          }
2716  
2717          $this->escape( $args );
2718  
2719          $username = $args[1];
2720          $password = $args[2];
2721          $filter   = $args[3] ?? array( 'public' => true );
2722  
2723          if ( isset( $args[4] ) ) {
2724              if ( ! $this->_is_fields_array( $args[4] ) ) {
2725                  return $this->error;
2726              }
2727  
2728              $fields = $args[4];
2729          } else {
2730              /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2731              $fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomies' );
2732          }
2733  
2734          $user = $this->login( $username, $password );
2735          if ( ! $user ) {
2736              return $this->error;
2737          }
2738  
2739          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2740          do_action( 'xmlrpc_call', 'wp.getTaxonomies', $args, $this );
2741  
2742          $taxonomies = get_taxonomies( $filter, 'objects' );
2743  
2744          // Holds all the taxonomy data.
2745          $struct = array();
2746  
2747          foreach ( $taxonomies as $taxonomy ) {
2748              // Capability check for post types.
2749              if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
2750                  continue;
2751              }
2752  
2753              $struct[] = $this->_prepare_taxonomy( $taxonomy, $fields );
2754          }
2755  
2756          return $struct;
2757      }
2758  
2759      /**
2760       * Retrieves a user.
2761       *
2762       * The optional $fields parameter specifies what fields will be included
2763       * in the response array. This should be a list of field names. 'user_id' will
2764       * always be included in the response regardless of the value of $fields.
2765       *
2766       * Instead of, or in addition to, individual field names, conceptual group
2767       * names can be used to specify multiple fields. The available conceptual
2768       * groups are 'basic' and 'all'.
2769       *
2770       * @since 3.5.0
2771       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
2772       *
2773       * @uses get_userdata()
2774       *
2775       * @param array $args {
2776       *     Method arguments. Note: arguments must be ordered as documented.
2777       *
2778       *     @type int    $0 Blog ID (unused).
2779       *     @type string $1 Username.
2780       *     @type string $2 Password.
2781       *     @type int    $3 User ID.
2782       *     @type array  $4 Optional. Array of fields to return.
2783       * }
2784       * @return array|IXR_Error Array contains (based on $fields parameter):
2785       *  - 'user_id'
2786       *  - 'username'
2787       *  - 'first_name'
2788       *  - 'last_name'
2789       *  - 'registered'
2790       *  - 'bio'
2791       *  - 'email'
2792       *  - 'nickname'
2793       *  - 'nicename'
2794       *  - 'url'
2795       *  - 'display_name'
2796       *  - 'roles'
2797       */
2798  	public function wp_getUser( $args ) {
2799          if ( ! $this->minimum_args( $args, 4 ) ) {
2800              return $this->error;
2801          }
2802  
2803          $this->escape( $args );
2804  
2805          $username = $args[1];
2806          $password = $args[2];
2807          $user_id  = (int) $args[3];
2808  
2809          if ( isset( $args[4] ) ) {
2810              if ( ! $this->_is_fields_array( $args[4] ) ) {
2811                  return $this->error;
2812              }
2813  
2814              $fields = $args[4];
2815          } else {
2816              /**
2817               * Filters the default user query fields used by the given XML-RPC method.
2818               *
2819               * @since 3.5.0
2820               *
2821               * @param array  $fields An array of user fields to retrieve. By default, contains 'all'.
2822               * @param string $method The method name.
2823               */
2824              $fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUser' );
2825          }
2826  
2827          $user = $this->login( $username, $password );
2828          if ( ! $user ) {
2829              return $this->error;
2830          }
2831  
2832          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2833          do_action( 'xmlrpc_call', 'wp.getUser', $args, $this );
2834  
2835          if ( ! current_user_can( 'edit_user', $user_id ) ) {
2836              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this user.' ) );
2837          }
2838  
2839          $user_data = get_userdata( $user_id );
2840  
2841          if ( ! $user_data ) {
2842              return new IXR_Error( 404, __( 'Invalid user ID.' ) );
2843          }
2844  
2845          return $this->_prepare_user( $user_data, $fields );
2846      }
2847  
2848      /**
2849       * Retrieves users.
2850       *
2851       * The optional $filter parameter modifies the query used to retrieve users.
2852       * Accepted keys are 'number' (default: 50), 'offset' (default: 0), 'role',
2853       * 'who', 'orderby', and 'order'.
2854       *
2855       * The optional $fields parameter specifies what fields will be included
2856       * in the response array.
2857       *
2858       * @since 3.5.0
2859       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
2860       *
2861       * @uses get_users()
2862       * @see wp_getUser() for more on $fields and return values
2863       *
2864       * @param array $args {
2865       *     Method arguments. Note: arguments must be ordered as documented.
2866       *
2867       *     @type int    $0 Blog ID (unused).
2868       *     @type string $1 Username.
2869       *     @type string $2 Password.
2870       *     @type array  $3 Optional. Arguments for the user query.
2871       *     @type array  $4 Optional. Fields to return.
2872       * }
2873       * @return array|IXR_Error users data
2874       */
2875  	public function wp_getUsers( $args ) {
2876          if ( ! $this->minimum_args( $args, 3 ) ) {
2877              return $this->error;
2878          }
2879  
2880          $this->escape( $args );
2881  
2882          $username = $args[1];
2883          $password = $args[2];
2884          $filter   = $args[3] ?? array();
2885  
2886          if ( isset( $args[4] ) ) {
2887              if ( ! $this->_is_fields_array( $args[4] ) ) {
2888                  return $this->error;
2889              }
2890  
2891              $fields = $args[4];
2892          } else {
2893              /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2894              $fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUsers' );
2895          }
2896  
2897          $user = $this->login( $username, $password );
2898          if ( ! $user ) {
2899              return $this->error;
2900          }
2901  
2902          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2903          do_action( 'xmlrpc_call', 'wp.getUsers', $args, $this );
2904  
2905          if ( ! current_user_can( 'list_users' ) ) {
2906              return new IXR_Error( 401, __( 'Sorry, you are not allowed to list users.' ) );
2907          }
2908  
2909          $query = array( 'fields' => 'all_with_meta' );
2910  
2911          $query['number'] = ( isset( $filter['number'] ) ) ? absint( $filter['number'] ) : 50;
2912          $query['offset'] = ( isset( $filter['offset'] ) ) ? absint( $filter['offset'] ) : 0;
2913  
2914          if ( isset( $filter['orderby'] ) ) {
2915              $query['orderby'] = $filter['orderby'];
2916  
2917              if ( isset( $filter['order'] ) ) {
2918                  $query['order'] = $filter['order'];
2919              }
2920          }
2921  
2922          if ( isset( $filter['role'] ) ) {
2923              if ( get_role( $filter['role'] ) === null ) {
2924                  return new IXR_Error( 403, __( 'Invalid role.' ) );
2925              }
2926  
2927              $query['role'] = $filter['role'];
2928          }
2929  
2930          if ( isset( $filter['who'] ) ) {
2931              $query['who'] = $filter['who'];
2932          }
2933  
2934          $users = get_users( $query );
2935  
2936          $_users = array();
2937          foreach ( $users as $user_data ) {
2938              if ( current_user_can( 'edit_user', $user_data->ID ) ) {
2939                  $_users[] = $this->_prepare_user( $user_data, $fields );
2940              }
2941          }
2942          return $_users;
2943      }
2944  
2945      /**
2946       * Retrieves information about the requesting user.
2947       *
2948       * @since 3.5.0
2949       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
2950       *
2951       * @uses get_userdata()
2952       *
2953       * @param array $args {
2954       *     Method arguments. Note: arguments must be ordered as documented.
2955       *
2956       *     @type int    $0 Blog ID (unused).
2957       *     @type string $1 Username
2958       *     @type string $2 Password
2959       *     @type array  $3 Optional. Fields to return.
2960       * }
2961       * @return array|IXR_Error (@see wp_getUser)
2962       */
2963  	public function wp_getProfile( $args ) {
2964          if ( ! $this->minimum_args( $args, 3 ) ) {
2965              return $this->error;
2966          }
2967  
2968          $this->escape( $args );
2969  
2970          $username = $args[1];
2971          $password = $args[2];
2972  
2973          if ( isset( $args[3] ) ) {
2974              if ( ! $this->_is_fields_array( $args[3] ) ) {
2975                  return $this->error;
2976              }
2977  
2978              $fields = $args[3];
2979          } else {
2980              /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2981              $fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getProfile' );
2982          }
2983  
2984          $user = $this->login( $username, $password );
2985          if ( ! $user ) {
2986              return $this->error;
2987          }
2988  
2989          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2990          do_action( 'xmlrpc_call', 'wp.getProfile', $args, $this );
2991  
2992          if ( ! current_user_can( 'edit_user', $user->ID ) ) {
2993              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
2994          }
2995  
2996          $user_data = get_userdata( $user->ID );
2997  
2998          return $this->_prepare_user( $user_data, $fields );
2999      }
3000  
3001      /**
3002       * Edits user's profile.
3003       *
3004       * @uses wp_update_user()
3005       *
3006       * @param array $args {
3007       *     Method arguments. Note: arguments must be ordered as documented.
3008       *
3009       *     @type int    $0 Blog ID (unused).
3010       *     @type string $1 Username.
3011       *     @type string $2 Password.
3012       *     @type array  $3 Content struct. It can optionally contain:
3013       *      - 'first_name'
3014       *      - 'last_name'
3015       *      - 'website'
3016       *      - 'display_name'
3017       *      - 'nickname'
3018       *      - 'nicename'
3019       *      - 'bio'
3020       * }
3021       * @return true|IXR_Error True, on success.
3022       */
3023  	public function wp_editProfile( $args ) {
3024          if ( ! $this->minimum_args( $args, 4 ) ) {
3025              return $this->error;
3026          }
3027  
3028          $this->escape( $args );
3029  
3030          $username       = $args[1];
3031          $password       = $args[2];
3032          $content_struct = $args[3];
3033  
3034          $user = $this->login( $username, $password );
3035          if ( ! $user ) {
3036              return $this->error;
3037          }
3038  
3039          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3040          do_action( 'xmlrpc_call', 'wp.editProfile', $args, $this );
3041  
3042          if ( ! current_user_can( 'edit_user', $user->ID ) ) {
3043              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
3044          }
3045  
3046          // Holds data of the user.
3047          $user_data       = array();
3048          $user_data['ID'] = $user->ID;
3049  
3050          // Only set the user details if they were given.
3051          if ( isset( $content_struct['first_name'] ) ) {
3052              $user_data['first_name'] = $content_struct['first_name'];
3053          }
3054  
3055          if ( isset( $content_struct['last_name'] ) ) {
3056              $user_data['last_name'] = $content_struct['last_name'];
3057          }
3058  
3059          if ( isset( $content_struct['url'] ) ) {
3060              $user_data['user_url'] = $content_struct['url'];
3061          }
3062  
3063          if ( isset( $content_struct['display_name'] ) ) {
3064              $user_data['display_name'] = $content_struct['display_name'];
3065          }
3066  
3067          if ( isset( $content_struct['nickname'] ) ) {
3068              $user_data['nickname'] = $content_struct['nickname'];
3069          }
3070  
3071          if ( isset( $content_struct['nicename'] ) ) {
3072              $user_data['user_nicename'] = $content_struct['nicename'];
3073          }
3074  
3075          if ( isset( $content_struct['bio'] ) ) {
3076              $user_data['description'] = $content_struct['bio'];
3077          }
3078  
3079          $result = wp_update_user( $user_data );
3080  
3081          if ( is_wp_error( $result ) ) {
3082              return new IXR_Error( 500, $result->get_error_message() );
3083          }
3084  
3085          if ( ! $result ) {
3086              return new IXR_Error( 500, __( 'Sorry, the user could not be updated.' ) );
3087          }
3088  
3089          return true;
3090      }
3091  
3092      /**
3093       * Retrieves a page.
3094       *
3095       * @since 2.2.0
3096       *
3097       * @param array $args {
3098       *     Method arguments. Note: arguments must be ordered as documented.
3099       *
3100       *     @type int    $0 Blog ID (unused).
3101       *     @type int    $1 Page ID.
3102       *     @type string $2 Username.
3103       *     @type string $3 Password.
3104       * }
3105       * @return array|IXR_Error
3106       */
3107  	public function wp_getPage( $args ) {
3108          $this->escape( $args );
3109  
3110          $page_id  = (int) $args[1];
3111          $username = $args[2];
3112          $password = $args[3];
3113  
3114          $user = $this->login( $username, $password );
3115          if ( ! $user ) {
3116              return $this->error;
3117          }
3118  
3119          $page = get_post( $page_id );
3120          if ( ! $page ) {
3121              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
3122          }
3123  
3124          if ( ! current_user_can( 'edit_page', $page_id ) ) {
3125              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
3126          }
3127  
3128          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3129          do_action( 'xmlrpc_call', 'wp.getPage', $args, $this );
3130  
3131          // If we found the page then format the data.
3132          if ( $page->ID && ( 'page' === $page->post_type ) ) {
3133              return $this->_prepare_page( $page );
3134          } else {
3135              // If the page doesn't exist, indicate that.
3136              return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
3137          }
3138      }
3139  
3140      /**
3141       * Retrieves Pages.
3142       *
3143       * @since 2.2.0
3144       *
3145       * @param array $args {
3146       *     Method arguments. Note: arguments must be ordered as documented.
3147       *
3148       *     @type int    $0 Blog ID (unused).
3149       *     @type string $1 Username.
3150       *     @type string $2 Password.
3151       *     @type int    $3 Optional. Number of pages. Default 10.
3152       * }
3153       * @return array|IXR_Error
3154       */
3155  	public function wp_getPages( $args ) {
3156          $this->escape( $args );
3157  
3158          $username  = $args[1];
3159          $password  = $args[2];
3160          $num_pages = isset( $args[3] ) ? (int) $args[3] : 10;
3161  
3162          $user = $this->login( $username, $password );
3163          if ( ! $user ) {
3164              return $this->error;
3165          }
3166  
3167          if ( ! current_user_can( 'edit_pages' ) ) {
3168              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
3169          }
3170  
3171          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3172          do_action( 'xmlrpc_call', 'wp.getPages', $args, $this );
3173  
3174          $pages     = get_posts(
3175              array(
3176                  'post_type'   => 'page',
3177                  'post_status' => 'any',
3178                  'numberposts' => $num_pages,
3179              )
3180          );
3181          $num_pages = count( $pages );
3182  
3183          // If we have pages, put together their info.
3184          if ( $num_pages >= 1 ) {
3185              $pages_struct = array();
3186  
3187              foreach ( $pages as $page ) {
3188                  if ( current_user_can( 'edit_page', $page->ID ) ) {
3189                      $pages_struct[] = $this->_prepare_page( $page );
3190                  }
3191              }
3192  
3193              return $pages_struct;
3194          }
3195  
3196          return array();
3197      }
3198  
3199      /**
3200       * Creates a new page.
3201       *
3202       * @since 2.2.0
3203       *
3204       * @see wp_xmlrpc_server::mw_newPost()
3205       *
3206       * @param array $args {
3207       *     Method arguments. Note: arguments must be ordered as documented.
3208       *
3209       *     @type int    $0 Blog ID (unused).
3210       *     @type string $1 Username.
3211       *     @type string $2 Password.
3212       *     @type array  $3 Content struct.
3213       * }
3214       * @return int|IXR_Error
3215       */
3216  	public function wp_newPage( $args ) {
3217          // Items not escaped here will be escaped in wp_newPost().
3218          $username = $this->escape( $args[1] );
3219          $password = $this->escape( $args[2] );
3220  
3221          $user = $this->login( $username, $password );
3222          if ( ! $user ) {
3223              return $this->error;
3224          }
3225  
3226          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3227          do_action( 'xmlrpc_call', 'wp.newPage', $args, $this );
3228  
3229          // Mark this as content for a page.
3230          $args[3]['post_type'] = 'page';
3231  
3232          // Let mw_newPost() do all of the heavy lifting.
3233          return $this->mw_newPost( $args );
3234      }
3235  
3236      /**
3237       * Deletes a page.
3238       *
3239       * @since 2.2.0
3240       *
3241       * @param array $args {
3242       *     Method arguments. Note: arguments must be ordered as documented.
3243       *
3244       *     @type int    $0 Blog ID (unused).
3245       *     @type string $1 Username.
3246       *     @type string $2 Password.
3247       *     @type int    $3 Page ID.
3248       * }
3249       * @return true|IXR_Error True, if success.
3250       */
3251  	public function wp_deletePage( $args ) {
3252          $this->escape( $args );
3253  
3254          $username = $args[1];
3255          $password = $args[2];
3256          $page_id  = (int) $args[3];
3257  
3258          $user = $this->login( $username, $password );
3259          if ( ! $user ) {
3260              return $this->error;
3261          }
3262  
3263          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3264          do_action( 'xmlrpc_call', 'wp.deletePage', $args, $this );
3265  
3266          /*
3267           * Get the current page based on the 'page_id' and
3268           * make sure it is a page and not a post.
3269           */
3270          $actual_page = get_post( $page_id, ARRAY_A );
3271          if ( ! $actual_page || ( 'page' !== $actual_page['post_type'] ) ) {
3272              return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
3273          }
3274  
3275          // Make sure the user can delete pages.
3276          if ( ! current_user_can( 'delete_page', $page_id ) ) {
3277              return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this page.' ) );
3278          }
3279  
3280          // Attempt to delete the page.
3281          $result = wp_delete_post( $page_id );
3282          if ( ! $result ) {
3283              return new IXR_Error( 500, __( 'Failed to delete the page.' ) );
3284          }
3285  
3286          /**
3287           * Fires after a page has been successfully deleted via XML-RPC.
3288           *
3289           * @since 3.4.0
3290           *
3291           * @param int   $page_id ID of the deleted page.
3292           * @param array $args    An array of arguments to delete the page.
3293           */
3294          do_action( 'xmlrpc_call_success_wp_deletePage', $page_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
3295  
3296          return true;
3297      }
3298  
3299      /**
3300       * Edits a page.
3301       *
3302       * @since 2.2.0
3303       *
3304       * @param array $args {
3305       *     Method arguments. Note: arguments must be ordered as documented.
3306       *
3307       *     @type int    $0 Blog ID (unused).
3308       *     @type int    $1 Page ID.
3309       *     @type string $2 Username.
3310       *     @type string $3 Password.
3311       *     @type array  $4 Content struct, with keys documented on {@see self::mw_newPost()}.
3312       *     @type int    $5 Publish flag. 0 for draft, 1 for publish.
3313       * }
3314       * @return array|IXR_Error
3315       */
3316  	public function wp_editPage( $args ) {
3317          // Items will be escaped in mw_editPost().
3318          $page_id  = (int) $args[1];
3319          $username = $args[2];
3320          $password = $args[3];
3321          $content  = $args[4];
3322          $publish  = $args[5];
3323  
3324          $escaped_username = $this->escape( $username );
3325          $escaped_password = $this->escape( $password );
3326  
3327          $user = $this->login( $escaped_username, $escaped_password );
3328          if ( ! $user ) {
3329              return $this->error;
3330          }
3331  
3332          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3333          do_action( 'xmlrpc_call', 'wp.editPage', $args, $this );
3334  
3335          // Get the page data and make sure it is a page.
3336          $actual_page = get_post( $page_id, ARRAY_A );
3337          if ( ! $actual_page || ( 'page' !== $actual_page['post_type'] ) ) {
3338              return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
3339          }
3340  
3341          // Make sure the user is allowed to edit pages.
3342          if ( ! current_user_can( 'edit_page', $page_id ) ) {
3343              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
3344          }
3345  
3346          // Mark this as content for a page.
3347          $content['post_type'] = 'page';
3348  
3349          // Arrange args in the way mw_editPost() understands.
3350          $args = array(
3351              $page_id,
3352              $username,
3353              $password,
3354              $content,
3355              $publish,
3356          );
3357  
3358          // Let mw_editPost() do all of the heavy lifting.
3359          return $this->mw_editPost( $args );
3360      }
3361  
3362      /**
3363       * Retrieves page list.
3364       *
3365       * @since 2.2.0
3366       *
3367       * @global wpdb $wpdb WordPress database abstraction object.
3368       *
3369       * @param array $args {
3370       *     Method arguments. Note: arguments must be ordered as documented.
3371       *
3372       *     @type int    $0 Blog ID (unused).
3373       *     @type string $1 Username.
3374       *     @type string $2 Password.
3375       * }
3376       * @return array|IXR_Error
3377       */
3378  	public function wp_getPageList( $args ) {
3379          global $wpdb;
3380  
3381          $this->escape( $args );
3382  
3383          $username = $args[1];
3384          $password = $args[2];
3385  
3386          $user = $this->login( $username, $password );
3387          if ( ! $user ) {
3388              return $this->error;
3389          }
3390  
3391          if ( ! current_user_can( 'edit_pages' ) ) {
3392              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
3393          }
3394  
3395          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3396          do_action( 'xmlrpc_call', 'wp.getPageList', $args, $this );
3397  
3398          // Get list of page IDs and titles.
3399          $page_list = $wpdb->get_results(
3400              "
3401              SELECT ID page_id,
3402                  post_title page_title,
3403                  post_parent page_parent_id,
3404                  post_date_gmt,
3405                  post_date,
3406                  post_status
3407              FROM {$wpdb->posts}
3408              WHERE post_type = 'page'
3409              ORDER BY ID
3410          "
3411          );
3412  
3413          // The date needs to be formatted properly.
3414          $num_pages = count( $page_list );
3415          for ( $i = 0; $i < $num_pages; $i++ ) {
3416              $page_list[ $i ]->dateCreated      = $this->_convert_date( $page_list[ $i ]->post_date );
3417              $page_list[ $i ]->date_created_gmt = $this->_convert_date_gmt( $page_list[ $i ]->post_date_gmt, $page_list[ $i ]->post_date );
3418  
3419              unset( $page_list[ $i ]->post_date_gmt );
3420              unset( $page_list[ $i ]->post_date );
3421              unset( $page_list[ $i ]->post_status );
3422          }
3423  
3424          return $page_list;
3425      }
3426  
3427      /**
3428       * Retrieves authors list.
3429       *
3430       * @since 2.2.0
3431       *
3432       * @param array $args {
3433       *     Method arguments. Note: arguments must be ordered as documented.
3434       *
3435       *     @type int    $0 Blog ID (unused).
3436       *     @type string $1 Username.
3437       *     @type string $2 Password.
3438       * }
3439       * @return array|IXR_Error
3440       */
3441  	public function wp_getAuthors( $args ) {
3442          $this->escape( $args );
3443  
3444          $username = $args[1];
3445          $password = $args[2];
3446  
3447          $user = $this->login( $username, $password );
3448          if ( ! $user ) {
3449              return $this->error;
3450          }
3451  
3452          if ( ! current_user_can( 'edit_posts' ) ) {
3453              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
3454          }
3455  
3456          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3457          do_action( 'xmlrpc_call', 'wp.getAuthors', $args, $this );
3458  
3459          $authors = array();
3460          foreach ( get_users( array( 'fields' => array( 'ID', 'user_login', 'display_name' ) ) ) as $user ) {
3461              $authors[] = array(
3462                  'user_id'      => $user->ID,
3463                  'user_login'   => $user->user_login,
3464                  'display_name' => $user->display_name,
3465              );
3466          }
3467  
3468          return $authors;
3469      }
3470  
3471      /**
3472       * Gets the list of all tags.
3473       *
3474       * @since 2.7.0
3475       *
3476       * @param array $args {
3477       *     Method arguments. Note: arguments must be ordered as documented.
3478       *
3479       *     @type int    $0 Blog ID (unused).
3480       *     @type string $1 Username.
3481       *     @type string $2 Password.
3482       * }
3483       * @return array|IXR_Error
3484       */
3485  	public function wp_getTags( $args ) {
3486          $this->escape( $args );
3487  
3488          $username = $args[1];
3489          $password = $args[2];
3490  
3491          $user = $this->login( $username, $password );
3492          if ( ! $user ) {
3493              return $this->error;
3494          }
3495  
3496          if ( ! current_user_can( 'edit_posts' ) ) {
3497              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view tags.' ) );
3498          }
3499  
3500          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3501          do_action( 'xmlrpc_call', 'wp.getKeywords', $args, $this );
3502  
3503          $tags = array();
3504  
3505          $all_tags = get_tags();
3506          if ( $all_tags ) {
3507              foreach ( (array) $all_tags as $tag ) {
3508                  $struct             = array();
3509                  $struct['tag_id']   = $tag->term_id;
3510                  $struct['name']     = $tag->name;
3511                  $struct['count']    = $tag->count;
3512                  $struct['slug']     = $tag->slug;
3513                  $struct['html_url'] = esc_html( get_tag_link( $tag->term_id ) );
3514                  $struct['rss_url']  = esc_html( get_tag_feed_link( $tag->term_id ) );
3515  
3516                  $tags[] = $struct;
3517              }
3518          }
3519  
3520          return $tags;
3521      }
3522  
3523      /**
3524       * Creates a new category.
3525       *
3526       * @since 2.2.0
3527       *
3528       * @param array $args {
3529       *     Method arguments. Note: arguments must be ordered as documented.
3530       *
3531       *     @type int    $0 Blog ID (unused).
3532       *     @type string $1 Username.
3533       *     @type string $2 Password.
3534       *     @type array  $3 Category.
3535       * }
3536       * @return int|IXR_Error Category ID.
3537       */
3538  	public function wp_newCategory( $args ) {
3539          $this->escape( $args );
3540  
3541          $username = $args[1];
3542          $password = $args[2];
3543          $category = $args[3];
3544  
3545          $user = $this->login( $username, $password );
3546          if ( ! $user ) {
3547              return $this->error;
3548          }
3549  
3550          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3551          do_action( 'xmlrpc_call', 'wp.newCategory', $args, $this );
3552  
3553          // Make sure the user is allowed to add a category.
3554          if ( ! current_user_can( 'manage_categories' ) ) {
3555              return new IXR_Error( 401, __( 'Sorry, you are not allowed to add a category.' ) );
3556          }
3557  
3558          /*
3559           * If no slug was provided, make it empty
3560           * so that WordPress will generate one.
3561           */
3562          if ( empty( $category['slug'] ) ) {
3563              $category['slug'] = '';
3564          }
3565  
3566          /*
3567           * If no parent_id was provided, make it empty
3568           * so that it will be a top-level page (no parent).
3569           */
3570          if ( ! isset( $category['parent_id'] ) ) {
3571              $category['parent_id'] = '';
3572          }
3573  
3574          // If no description was provided, make it empty.
3575          if ( empty( $category['description'] ) ) {
3576              $category['description'] = '';
3577          }
3578  
3579          $new_category = array(
3580              'cat_name'             => $category['name'],
3581              'category_nicename'    => $category['slug'],
3582              'category_parent'      => $category['parent_id'],
3583              'category_description' => $category['description'],
3584          );
3585  
3586          $cat_id = wp_insert_category( $new_category, true );
3587          if ( is_wp_error( $cat_id ) ) {
3588              if ( 'term_exists' === $cat_id->get_error_code() ) {
3589                  return (int) $cat_id->get_error_data();
3590              } else {
3591                  return new IXR_Error( 500, __( 'Sorry, the category could not be created.' ) );
3592              }
3593          } elseif ( ! $cat_id ) {
3594              return new IXR_Error( 500, __( 'Sorry, the category could not be created.' ) );
3595          }
3596  
3597          /**
3598           * Fires after a new category has been successfully created via XML-RPC.
3599           *
3600           * @since 3.4.0
3601           *
3602           * @param int   $cat_id ID of the new category.
3603           * @param array $args   An array of new category arguments.
3604           */
3605          do_action( 'xmlrpc_call_success_wp_newCategory', $cat_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
3606  
3607          return $cat_id;
3608      }
3609  
3610      /**
3611       * Deletes a category.
3612       *
3613       * @since 2.5.0
3614       *
3615       * @param array $args {
3616       *     Method arguments. Note: arguments must be ordered as documented.
3617       *
3618       *     @type int    $0 Blog ID (unused).
3619       *     @type string $1 Username.
3620       *     @type string $2 Password.
3621       *     @type int    $3 Category ID.
3622       * }
3623       * @return bool|IXR_Error See wp_delete_term() for return info.
3624       */
3625  	public function wp_deleteCategory( $args ) {
3626          $this->escape( $args );
3627  
3628          $username    = $args[1];
3629          $password    = $args[2];
3630          $category_id = (int) $args[3];
3631  
3632          $user = $this->login( $username, $password );
3633          if ( ! $user ) {
3634              return $this->error;
3635          }
3636  
3637          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3638          do_action( 'xmlrpc_call', 'wp.deleteCategory', $args, $this );
3639  
3640          if ( ! current_user_can( 'delete_term', $category_id ) ) {
3641              return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this category.' ) );
3642          }
3643  
3644          $status = wp_delete_term( $category_id, 'category' );
3645  
3646          if ( true === $status ) {
3647              /**
3648               * Fires after a category has been successfully deleted via XML-RPC.
3649               *
3650               * @since 3.4.0
3651               *
3652               * @param int   $category_id ID of the deleted category.
3653               * @param array $args        An array of arguments to delete the category.
3654               */
3655              do_action( 'xmlrpc_call_success_wp_deleteCategory', $category_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
3656          }
3657  
3658          return $status;
3659      }
3660  
3661      /**
3662       * Retrieves category list.
3663       *
3664       * @since 2.2.0
3665       *
3666       * @param array $args {
3667       *     Method arguments. Note: arguments must be ordered as documented.
3668       *
3669       *     @type int    $0 Blog ID (unused).
3670       *     @type string $1 Username.
3671       *     @type string $2 Password.
3672       *     @type array  $3 Category
3673       *     @type int    $4 Max number of results.
3674       * }
3675       * @return array|IXR_Error
3676       */
3677  	public function wp_suggestCategories( $args ) {
3678          $this->escape( $args );
3679  
3680          $username    = $args[1];
3681          $password    = $args[2];
3682          $category    = $args[3];
3683          $max_results = (int) $args[4];
3684  
3685          $user = $this->login( $username, $password );
3686          if ( ! $user ) {
3687              return $this->error;
3688          }
3689  
3690          if ( ! current_user_can( 'edit_posts' ) ) {
3691              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
3692          }
3693  
3694          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3695          do_action( 'xmlrpc_call', 'wp.suggestCategories', $args, $this );
3696  
3697          $category_suggestions = array();
3698          $args                 = array(
3699              'get'        => 'all',
3700              'number'     => $max_results,
3701              'name__like' => $category,
3702          );
3703          foreach ( (array) get_categories( $args ) as $cat ) {
3704              $category_suggestions[] = array(
3705                  'category_id'   => $cat->term_id,
3706                  'category_name' => $cat->name,
3707              );
3708          }
3709  
3710          return $category_suggestions;
3711      }
3712  
3713      /**
3714       * Retrieves a comment.
3715       *
3716       * @since 2.7.0
3717       *
3718       * @param array $args {
3719       *     Method arguments. Note: arguments must be ordered as documented.
3720       *
3721       *     @type int    $0 Blog ID (unused).
3722       *     @type string $1 Username.
3723       *     @type string $2 Password.
3724       *     @type int    $3 Comment ID.
3725       * }
3726       * @return array|IXR_Error
3727       */
3728  	public function wp_getComment( $args ) {
3729          $this->escape( $args );
3730  
3731          $username   = $args[1];
3732          $password   = $args[2];
3733          $comment_id = (int) $args[3];
3734  
3735          $user = $this->login( $username, $password );
3736          if ( ! $user ) {
3737              return $this->error;
3738          }
3739  
3740          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3741          do_action( 'xmlrpc_call', 'wp.getComment', $args, $this );
3742  
3743          $comment = get_comment( $comment_id );
3744          if ( ! $comment ) {
3745              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
3746          }
3747  
3748          if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
3749              return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
3750          }
3751  
3752          return $this->_prepare_comment( $comment );
3753      }
3754  
3755      /**
3756       * Retrieves comments.
3757       *
3758       * Besides the common blog_id (unused), username, and password arguments,
3759       * it takes a filter array as the last argument.
3760       *
3761       * Accepted 'filter' keys are 'status', 'post_id', 'offset', and 'number'.
3762       *
3763       * The defaults are as follows:
3764       * - 'status'  - Default is ''. Filter by status (e.g., 'approve', 'hold')
3765       * - 'post_id' - Default is ''. The post where the comment is posted.
3766       *               Empty string shows all comments.
3767       * - 'number'  - Default is 10. Total number of media items to retrieve.
3768       * - 'offset'  - Default is 0. See WP_Query::query() for more.
3769       *
3770       * @since 2.7.0
3771       *
3772       * @param array $args {
3773       *     Method arguments. Note: arguments must be ordered as documented.
3774       *
3775       *     @type int    $0 Blog ID (unused).
3776       *     @type string $1 Username.
3777       *     @type string $2 Password.
3778       *     @type array  $3 Optional. Query arguments.
3779       * }
3780       * @return array|IXR_Error Array containing a collection of comments.
3781       *                         See wp_xmlrpc_server::wp_getComment() for a description
3782       *                         of each item contents.
3783       */
3784  	public function wp_getComments( $args ) {
3785          $this->escape( $args );
3786  
3787          $username = $args[1];
3788          $password = $args[2];
3789          $struct   = $args[3] ?? array();
3790  
3791          $user = $this->login( $username, $password );
3792          if ( ! $user ) {
3793              return $this->error;
3794          }
3795  
3796          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3797          do_action( 'xmlrpc_call', 'wp.getComments', $args, $this );
3798  
3799          $status = $struct['status'] ?? '';
3800  
3801          $can_moderate = current_user_can( 'moderate_comments' );
3802  
3803          if ( ! $can_moderate && 'approve' !== $status ) {
3804              return new IXR_Error( 401, __( 'Invalid comment status.' ) );
3805          }
3806  
3807          $post_id = '';
3808          if ( isset( $struct['post_id'] ) ) {
3809              $post_id = absint( $struct['post_id'] );
3810          }
3811  
3812          $has_public_status = static function ( $post ) {
3813              $status        = get_post_status( $post );
3814              $status_object = $status ? get_post_status_object( $status ) : null;
3815  
3816              return $status_object && $status_object->public;
3817          };
3818  
3819          if ( $post_id && ! $can_moderate && ! $has_public_status( $post_id ) && ! current_user_can( 'read_post', $post_id ) ) {
3820              return new IXR_Error( 401, __( 'Invalid post ID.' ) );
3821          }
3822  
3823          $post_type = '';
3824          if ( isset( $struct['post_type'] ) ) {
3825              $post_type_object = get_post_type_object( $struct['post_type'] );
3826              if ( ! $post_type_object || ! post_type_supports( $post_type_object->name, 'comments' ) ) {
3827                  return new IXR_Error( 404, __( 'Invalid post type.' ) );
3828              }
3829              $post_type = $struct['post_type'];
3830          }
3831  
3832          $offset = 0;
3833          if ( isset( $struct['offset'] ) ) {
3834              $offset = absint( $struct['offset'] );
3835          }
3836  
3837          $number = 10;
3838          if ( isset( $struct['number'] ) ) {
3839              $number = absint( $struct['number'] );
3840          }
3841  
3842          $comments = get_comments(
3843              array(
3844                  'status'                    => $status,
3845                  'post_id'                   => $post_id,
3846                  'offset'                    => $offset,
3847                  'number'                    => $number,
3848                  'post_type'                 => $post_type,
3849                  'update_comment_post_cache' => true,
3850              )
3851          );
3852  
3853          $comments_struct = array();
3854          if ( is_array( $comments ) ) {
3855              foreach ( $comments as $comment ) {
3856                  if ( ! $can_moderate && ! current_user_can( 'edit_comment', $comment->comment_ID ) ) {
3857                      $post = get_post( $comment->comment_post_ID );
3858  
3859                      if (
3860                          ! $post
3861                          || ! is_post_type_viewable( $post->post_type )
3862                          || post_password_required( $post )
3863                          || ( ! $has_public_status( $post ) && ! current_user_can( 'read_post', $post->ID ) )
3864                      ) {
3865                          continue;
3866                      }
3867                  }
3868  
3869                  $comments_struct[] = $this->_prepare_comment( $comment );
3870              }
3871          }
3872  
3873          return $comments_struct;
3874      }
3875  
3876      /**
3877       * Deletes a comment.
3878       *
3879       * By default, the comment will be moved to the Trash instead of deleted.
3880       * See wp_delete_comment() for more information on this behavior.
3881       *
3882       * @since 2.7.0
3883       *
3884       * @param array $args {
3885       *     Method arguments. Note: arguments must be ordered as documented.
3886       *
3887       *     @type int    $0 Blog ID (unused).
3888       *     @type string $1 Username.
3889       *     @type string $2 Password.
3890       *     @type int    $3 Comment ID.
3891       * }
3892       * @return bool|IXR_Error See wp_delete_comment().
3893       */
3894  	public function wp_deleteComment( $args ) {
3895          $this->escape( $args );
3896  
3897          $username   = $args[1];
3898          $password   = $args[2];
3899          $comment_id = (int) $args[3];
3900  
3901          $user = $this->login( $username, $password );
3902          if ( ! $user ) {
3903              return $this->error;
3904          }
3905  
3906          if ( ! get_comment( $comment_id ) ) {
3907              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
3908          }
3909  
3910          if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
3911              return new IXR_Error( 403, __( 'Sorry, you are not allowed to delete this comment.' ) );
3912          }
3913  
3914          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3915          do_action( 'xmlrpc_call', 'wp.deleteComment', $args, $this );
3916  
3917          $status = wp_delete_comment( $comment_id );
3918  
3919          if ( true === $status ) {
3920              /**
3921               * Fires after a comment has been successfully deleted via XML-RPC.
3922               *
3923               * @since 3.4.0
3924               *
3925               * @param int   $comment_id ID of the deleted comment.
3926               * @param array $args       An array of arguments to delete the comment.
3927               */
3928              do_action( 'xmlrpc_call_success_wp_deleteComment', $comment_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
3929          }
3930  
3931          return $status;
3932      }
3933  
3934      /**
3935       * Edits a comment.
3936       *
3937       * Besides the common blog_id (unused), username, and password arguments,
3938       * it takes a comment_id integer and a content_struct array as the last argument.
3939       *
3940       * The allowed keys in the content_struct array are:
3941       *  - 'author'
3942       *  - 'author_url'
3943       *  - 'author_email'
3944       *  - 'content'
3945       *  - 'date_created_gmt'
3946       *  - 'status'. Common statuses are 'approve', 'hold', 'spam'. See get_comment_statuses() for more details.
3947       *
3948       * @since 2.7.0
3949       *
3950       * @param array $args {
3951       *     Method arguments. Note: arguments must be ordered as documented.
3952       *
3953       *     @type int    $0 Blog ID (unused).
3954       *     @type string $1 Username.
3955       *     @type string $2 Password.
3956       *     @type int    $3 Comment ID.
3957       *     @type array  $4 Content structure.
3958       * }
3959       * @return true|IXR_Error True, on success.
3960       */
3961  	public function wp_editComment( $args ) {
3962          $this->escape( $args );
3963  
3964          $username       = $args[1];
3965          $password       = $args[2];
3966          $comment_id     = (int) $args[3];
3967          $content_struct = $args[4];
3968  
3969          $user = $this->login( $username, $password );
3970          if ( ! $user ) {
3971              return $this->error;
3972          }
3973  
3974          $existing_comment = get_comment( $comment_id );
3975  
3976          if ( ! $existing_comment ) {
3977              return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
3978          }
3979  
3980          if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
3981              return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
3982          }
3983  
3984          // Reactions are only validated on creation. Removing one is a delete.
3985          if ( 'reaction' === $existing_comment->comment_type ) {
3986              return new IXR_Error( 403, __( 'Reactions cannot be edited. Remove the reaction and add a new one instead.' ) );
3987          }
3988  
3989          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3990          do_action( 'xmlrpc_call', 'wp.editComment', $args, $this );
3991          $comment = array(
3992              'comment_ID' => $comment_id,
3993          );
3994  
3995          if ( isset( $content_struct['status'] ) ) {
3996              $statuses = get_comment_statuses();
3997              $statuses = array_keys( $statuses );
3998  
3999              if ( ! in_array( $content_struct['status'], $statuses, true ) ) {
4000                  return new IXR_Error( 401, __( 'Invalid comment status.' ) );
4001              }
4002  
4003              $comment['comment_approved'] = $content_struct['status'];
4004          }
4005  
4006          // Do some timestamp voodoo.
4007          if ( ! empty( $content_struct['date_created_gmt'] ) ) {
4008              // We know this is supposed to be GMT, so we're going to slap that Z on there by force.
4009              $date_created = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
4010  
4011              $comment['comment_date']     = get_date_from_gmt( $date_created );
4012              $comment['comment_date_gmt'] = iso8601_to_datetime( $date_created, 'gmt' );
4013          }
4014  
4015          if ( isset( $content_struct['content'] ) ) {
4016              $comment['comment_content'] = $content_struct['content'];
4017          }
4018  
4019          if ( isset( $content_struct['author'] ) ) {
4020              $comment['comment_author'] = $content_struct['author'];
4021          }
4022  
4023          if ( isset( $content_struct['author_url'] ) ) {
4024              $comment['comment_author_url'] = $content_struct['author_url'];
4025          }
4026  
4027          if ( isset( $content_struct['author_email'] ) ) {
4028              $comment['comment_author_email'] = $content_struct['author_email'];
4029          }
4030  
4031          $result = wp_update_comment( $comment, true );
4032          if ( is_wp_error( $result ) ) {
4033              return new IXR_Error( 500, $result->get_error_message() );
4034          }
4035  
4036          if ( ! $result ) {
4037              return new IXR_Error( 500, __( 'Sorry, the comment could not be updated.' ) );
4038          }
4039  
4040          /**
4041           * Fires after a comment has been successfully updated via XML-RPC.
4042           *
4043           * @since 3.4.0
4044           *
4045           * @param int   $comment_id ID of the updated comment.
4046           * @param array $args       An array of arguments to update the comment.
4047           */
4048          do_action( 'xmlrpc_call_success_wp_editComment', $comment_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
4049  
4050          return true;
4051      }
4052  
4053      /**
4054       * Creates a new comment.
4055       *
4056       * @since 2.7.0
4057       *
4058       * @param array $args {
4059       *     Method arguments. Note: arguments must be ordered as documented.
4060       *
4061       *     @type int        $0 Blog ID (unused).
4062       *     @type string     $1 Username.
4063       *     @type string     $2 Password.
4064       *     @type string|int $3 Post ID or URL.
4065       *     @type array      $4 Content structure.
4066       * }
4067       * @return int|IXR_Error See wp_new_comment().
4068       */
4069  	public function wp_newComment( $args ) {
4070          $this->escape( $args );
4071  
4072          $username       = $args[1];
4073          $password       = $args[2];
4074          $post           = $args[3];
4075          $content_struct = $args[4];
4076  
4077          /**
4078           * Filters whether to allow anonymous comments over XML-RPC.
4079           *
4080           * @since 2.7.0
4081           *
4082           * @param bool $allow Whether to allow anonymous commenting via XML-RPC.
4083           *                    Default false.
4084           */
4085          $allow_anon = apply_filters( 'xmlrpc_allow_anonymous_comments', false );
4086  
4087          $user = $this->login( $username, $password );
4088  
4089          if ( ! $user ) {
4090              $logged_in = false;
4091              if ( $allow_anon && get_option( 'comment_registration' ) ) {
4092                  return new IXR_Error( 403, __( 'Sorry, you must be logged in to comment.' ) );
4093              } elseif ( ! $allow_anon ) {
4094                  return $this->error;
4095              }
4096          } else {
4097              $logged_in = true;
4098          }
4099  
4100          if ( is_numeric( $post ) ) {
4101              $post_id = absint( $post );
4102          } else {
4103              $post_id = url_to_postid( $post );
4104          }
4105  
4106          if ( ! $post_id ) {
4107              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4108          }
4109  
4110          if ( ! get_post( $post_id ) ) {
4111              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4112          }
4113  
4114          if ( ! comments_open( $post_id ) ) {
4115              return new IXR_Error( 403, __( 'Sorry, comments are closed for this item.' ) );
4116          }
4117  
4118          if (
4119              'publish' === get_post_status( $post_id ) &&
4120              ! current_user_can( 'edit_post', $post_id ) &&
4121              post_password_required( $post_id )
4122          ) {
4123              return new IXR_Error( 403, __( 'Sorry, you are not allowed to comment on this post.' ) );
4124          }
4125  
4126          if (
4127              'private' === get_post_status( $post_id ) &&
4128              ! current_user_can( 'read_post', $post_id )
4129          ) {
4130              return new IXR_Error( 403, __( 'Sorry, you are not allowed to comment on this post.' ) );
4131          }
4132  
4133          $comment = array(
4134              'comment_post_ID' => $post_id,
4135              'comment_content' => trim( $content_struct['content'] ),
4136          );
4137  
4138          if ( $logged_in ) {
4139              $display_name = $user->display_name;
4140              $user_email   = $user->user_email;
4141              $user_url     = $user->user_url;
4142  
4143              $comment['comment_author']       = $this->escape( $display_name );
4144              $comment['comment_author_email'] = $this->escape( $user_email );
4145              $comment['comment_author_url']   = $this->escape( $user_url );
4146              $comment['user_id']              = $user->ID;
4147          } else {
4148              $comment['comment_author'] = '';
4149              if ( isset( $content_struct['author'] ) ) {
4150                  $comment['comment_author'] = $content_struct['author'];
4151              }
4152  
4153              $comment['comment_author_email'] = '';
4154              if ( isset( $content_struct['author_email'] ) ) {
4155                  $comment['comment_author_email'] = $content_struct['author_email'];
4156              }
4157  
4158              $comment['comment_author_url'] = '';
4159              if ( isset( $content_struct['author_url'] ) ) {
4160                  $comment['comment_author_url'] = $content_struct['author_url'];
4161              }
4162  
4163              $comment['user_id'] = 0;
4164  
4165              if ( get_option( 'require_name_email' ) ) {
4166                  if ( strlen( $comment['comment_author_email'] ) < 6 || '' === $comment['comment_author'] ) {
4167                      return new IXR_Error( 403, __( 'Comment author name and email are required.' ) );
4168                  } elseif ( ! is_email( $comment['comment_author_email'] ) ) {
4169                      return new IXR_Error( 403, __( 'A valid email address is required.' ) );
4170                  }
4171              }
4172          }
4173  
4174          $comment['comment_parent'] = isset( $content_struct['comment_parent'] ) ? absint( $content_struct['comment_parent'] ) : 0;
4175  
4176          /** This filter is documented in wp-includes/comment.php */
4177          $allow_empty = apply_filters( 'allow_empty_comment', false, $comment );
4178  
4179          if ( ! $allow_empty && '' === $comment['comment_content'] ) {
4180              return new IXR_Error( 403, __( 'Comment is required.' ) );
4181          }
4182  
4183          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4184          do_action( 'xmlrpc_call', 'wp.newComment', $args, $this );
4185  
4186          $comment_id = wp_new_comment( $comment, true );
4187          if ( is_wp_error( $comment_id ) ) {
4188              return new IXR_Error( 403, $comment_id->get_error_message() );
4189          }
4190  
4191          if ( ! $comment_id ) {
4192              return new IXR_Error( 403, __( 'An error occurred while processing your comment. Please ensure all fields are filled correctly and try again.' ) );
4193          }
4194  
4195          /**
4196           * Fires after a new comment has been successfully created via XML-RPC.
4197           *
4198           * @since 3.4.0
4199           *
4200           * @param int   $comment_id ID of the new comment.
4201           * @param array $args       An array of new comment arguments.
4202           */
4203          do_action( 'xmlrpc_call_success_wp_newComment', $comment_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
4204  
4205          return $comment_id;
4206      }
4207  
4208      /**
4209       * Retrieves all of the comment status.
4210       *
4211       * @since 2.7.0
4212       *
4213       * @param array $args {
4214       *     Method arguments. Note: arguments must be ordered as documented.
4215       *
4216       *     @type int    $0 Blog ID (unused).
4217       *     @type string $1 Username.
4218       *     @type string $2 Password.
4219       * }
4220       * @return array|IXR_Error
4221       */
4222  	public function wp_getCommentStatusList( $args ) {
4223          $this->escape( $args );
4224  
4225          $username = $args[1];
4226          $password = $args[2];
4227  
4228          $user = $this->login( $username, $password );
4229          if ( ! $user ) {
4230              return $this->error;
4231          }
4232  
4233          if ( ! current_user_can( 'publish_posts' ) ) {
4234              return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
4235          }
4236  
4237          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4238          do_action( 'xmlrpc_call', 'wp.getCommentStatusList', $args, $this );
4239  
4240          return get_comment_statuses();
4241      }
4242  
4243      /**
4244       * Retrieves comment counts.
4245       *
4246       * @since 2.5.0
4247       *
4248       * @param array $args {
4249       *     Method arguments. Note: arguments must be ordered as documented.
4250       *
4251       *     @type int    $0 Blog ID (unused).
4252       *     @type string $1 Username.
4253       *     @type string $2 Password.
4254       *     @type int    $3 Post ID.
4255       * }
4256       * @return array|IXR_Error
4257       */
4258  	public function wp_getCommentCount( $args ) {
4259          $this->escape( $args );
4260  
4261          $username = $args[1];
4262          $password = $args[2];
4263          $post_id  = (int) $args[3];
4264  
4265          $user = $this->login( $username, $password );
4266          if ( ! $user ) {
4267              return $this->error;
4268          }
4269  
4270          $post = get_post( $post_id, ARRAY_A );
4271          if ( empty( $post['ID'] ) ) {
4272              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4273          }
4274  
4275          if ( ! current_user_can( 'edit_post', $post_id ) ) {
4276              return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details of this post.' ) );
4277          }
4278  
4279          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4280          do_action( 'xmlrpc_call', 'wp.getCommentCount', $args, $this );
4281  
4282          $count = wp_count_comments( $post_id );
4283  
4284          return array(
4285              'approved'            => $count->approved,
4286              'awaiting_moderation' => $count->moderated,
4287              'spam'                => $count->spam,
4288              'total_comments'      => $count->total_comments,
4289          );
4290      }
4291  
4292      /**
4293       * Retrieves post statuses.
4294       *
4295       * @since 2.5.0
4296       *
4297       * @param array $args {
4298       *     Method arguments. Note: arguments must be ordered as documented.
4299       *
4300       *     @type int    $0 Blog ID (unused).
4301       *     @type string $1 Username.
4302       *     @type string $2 Password.
4303       * }
4304       * @return array|IXR_Error
4305       */
4306  	public function wp_getPostStatusList( $args ) {
4307          $this->escape( $args );
4308  
4309          $username = $args[1];
4310          $password = $args[2];
4311  
4312          $user = $this->login( $username, $password );
4313          if ( ! $user ) {
4314              return $this->error;
4315          }
4316  
4317          if ( ! current_user_can( 'edit_posts' ) ) {
4318              return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
4319          }
4320  
4321          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4322          do_action( 'xmlrpc_call', 'wp.getPostStatusList', $args, $this );
4323  
4324          return get_post_statuses();
4325      }
4326  
4327      /**
4328       * Retrieves page statuses.
4329       *
4330       * @since 2.5.0
4331       *
4332       * @param array $args {
4333       *     Method arguments. Note: arguments must be ordered as documented.
4334       *
4335       *     @type int    $0 Blog ID (unused).
4336       *     @type string $1 Username.
4337       *     @type string $2 Password.
4338       * }
4339       * @return array|IXR_Error
4340       */
4341  	public function wp_getPageStatusList( $args ) {
4342          $this->escape( $args );
4343  
4344          $username = $args[1];
4345          $password = $args[2];
4346  
4347          $user = $this->login( $username, $password );
4348          if ( ! $user ) {
4349              return $this->error;
4350          }
4351  
4352          if ( ! current_user_can( 'edit_pages' ) ) {
4353              return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
4354          }
4355  
4356          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4357          do_action( 'xmlrpc_call', 'wp.getPageStatusList', $args, $this );
4358  
4359          return get_page_statuses();
4360      }
4361  
4362      /**
4363       * Retrieves page templates.
4364       *
4365       * @since 2.6.0
4366       *
4367       * @param array $args {
4368       *     Method arguments. Note: arguments must be ordered as documented.
4369       *
4370       *     @type int    $0 Blog ID (unused).
4371       *     @type string $1 Username.
4372       *     @type string $2 Password.
4373       * }
4374       * @return array|IXR_Error
4375       */
4376  	public function wp_getPageTemplates( $args ) {
4377          $this->escape( $args );
4378  
4379          $username = $args[1];
4380          $password = $args[2];
4381  
4382          $user = $this->login( $username, $password );
4383          if ( ! $user ) {
4384              return $this->error;
4385          }
4386  
4387          if ( ! current_user_can( 'edit_pages' ) ) {
4388              return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
4389          }
4390  
4391          $templates            = get_page_templates();
4392          $templates['Default'] = 'default';
4393  
4394          return $templates;
4395      }
4396  
4397      /**
4398       * Retrieves blog options.
4399       *
4400       * @since 2.6.0
4401       *
4402       * @param array $args {
4403       *     Method arguments. Note: arguments must be ordered as documented.
4404       *
4405       *     @type int    $0 Blog ID (unused).
4406       *     @type string $1 Username.
4407       *     @type string $2 Password.
4408       *     @type array  $3 Optional. Options.
4409       * }
4410       * @return array|IXR_Error
4411       */
4412  	public function wp_getOptions( $args ) {
4413          $this->escape( $args );
4414  
4415          $username = $args[1];
4416          $password = $args[2];
4417          $options  = isset( $args[3] ) ? (array) $args[3] : array();
4418  
4419          $user = $this->login( $username, $password );
4420          if ( ! $user ) {
4421              return $this->error;
4422          }
4423  
4424          // If no specific options where asked for, return all of them.
4425          if ( count( $options ) === 0 ) {
4426              $options = array_keys( $this->blog_options );
4427          }
4428  
4429          return $this->_getOptions( $options );
4430      }
4431  
4432      /**
4433       * Retrieves blog options value from list.
4434       *
4435       * @since 2.6.0
4436       *
4437       * @param array $options Options to retrieve.
4438       * @return array
4439       */
4440  	public function _getOptions( $options ) {
4441          $data       = array();
4442          $can_manage = current_user_can( 'manage_options' );
4443          foreach ( $options as $option ) {
4444              if ( array_key_exists( $option, $this->blog_options ) ) {
4445                  $data[ $option ] = $this->blog_options[ $option ];
4446                  // Is the value static or dynamic?
4447                  if ( isset( $data[ $option ]['option'] ) ) {
4448                      $data[ $option ]['value'] = get_option( $data[ $option ]['option'] );
4449                      unset( $data[ $option ]['option'] );
4450                  }
4451  
4452                  if ( ! $can_manage ) {
4453                      $data[ $option ]['readonly'] = true;
4454                  }
4455              }
4456          }
4457  
4458          return $data;
4459      }
4460  
4461      /**
4462       * Updates blog options.
4463       *
4464       * @since 2.6.0
4465       *
4466       * @param array $args {
4467       *     Method arguments. Note: arguments must be ordered as documented.
4468       *
4469       *     @type int    $0 Blog ID (unused).
4470       *     @type string $1 Username.
4471       *     @type string $2 Password.
4472       *     @type array  $3 Options.
4473       * }
4474       * @return array|IXR_Error
4475       */
4476  	public function wp_setOptions( $args ) {
4477          $this->escape( $args );
4478  
4479          $username = $args[1];
4480          $password = $args[2];
4481          $options  = (array) $args[3];
4482  
4483          $user = $this->login( $username, $password );
4484          if ( ! $user ) {
4485              return $this->error;
4486          }
4487  
4488          if ( ! current_user_can( 'manage_options' ) ) {
4489              return new IXR_Error( 403, __( 'Sorry, you are not allowed to update options.' ) );
4490          }
4491  
4492          $option_names = array();
4493          foreach ( $options as $o_name => $o_value ) {
4494              $option_names[] = $o_name;
4495              if ( ! array_key_exists( $o_name, $this->blog_options ) ) {
4496                  continue;
4497              }
4498  
4499              if ( $this->blog_options[ $o_name ]['readonly'] ) {
4500                  continue;
4501              }
4502  
4503              update_option( $this->blog_options[ $o_name ]['option'], wp_unslash( $o_value ) );
4504          }
4505  
4506          // Now return the updated values.
4507          return $this->_getOptions( $option_names );
4508      }
4509  
4510      /**
4511       * Retrieves a media item by ID.
4512       *
4513       * @since 3.1.0
4514       *
4515       * @param array $args {
4516       *     Method arguments. Note: arguments must be ordered as documented.
4517       *
4518       *     @type int    $0 Blog ID (unused).
4519       *     @type string $1 Username.
4520       *     @type string $2 Password.
4521       *     @type int    $3 Attachment ID.
4522       * }
4523       * @return array|IXR_Error Associative array contains:
4524       *  - 'date_created_gmt'
4525       *  - 'parent'
4526       *  - 'link'
4527       *  - 'thumbnail'
4528       *  - 'title'
4529       *  - 'caption'
4530       *  - 'description'
4531       *  - 'metadata'
4532       */
4533  	public function wp_getMediaItem( $args ) {
4534          $this->escape( $args );
4535  
4536          $username      = $args[1];
4537          $password      = $args[2];
4538          $attachment_id = (int) $args[3];
4539  
4540          $user = $this->login( $username, $password );
4541          if ( ! $user ) {
4542              return $this->error;
4543          }
4544  
4545          if ( ! current_user_can( 'upload_files' ) ) {
4546              return new IXR_Error( 403, __( 'Sorry, you are not allowed to upload files.' ) );
4547          }
4548  
4549          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4550          do_action( 'xmlrpc_call', 'wp.getMediaItem', $args, $this );
4551  
4552          $attachment = get_post( $attachment_id );
4553          if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
4554              return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
4555          }
4556  
4557          return $this->_prepare_media_item( $attachment );
4558      }
4559  
4560      /**
4561       * Retrieves a collection of media library items (or attachments).
4562       *
4563       * Besides the common blog_id (unused), username, and password arguments,
4564       * it takes a filter array as the last argument.
4565       *
4566       * Accepted 'filter' keys are 'parent_id', 'mime_type', 'offset', and 'number'.
4567       *
4568       * The defaults are as follows:
4569       * - 'number'    - Default is 5. Total number of media items to retrieve.
4570       * - 'offset'    - Default is 0. See WP_Query::query() for more.
4571       * - 'parent_id' - Default is ''. The post where the media item is attached.
4572       *                 Empty string shows all media items. 0 shows unattached media items.
4573       * - 'mime_type' - Default is ''. Filter by mime type (e.g., 'image/jpeg', 'application/pdf')
4574       *
4575       * @since 3.1.0
4576       *
4577       * @param array $args {
4578       *     Method arguments. Note: arguments must be ordered as documented.
4579       *
4580       *     @type int    $0 Blog ID (unused).
4581       *     @type string $1 Username.
4582       *     @type string $2 Password.
4583       *     @type array  $3 Optional. Query arguments.
4584       * }
4585       * @return array|IXR_Error Array containing a collection of media items.
4586       *                         See wp_xmlrpc_server::wp_getMediaItem() for a description
4587       *                         of each item contents.
4588       */
4589  	public function wp_getMediaLibrary( $args ) {
4590          $this->escape( $args );
4591  
4592          $username = $args[1];
4593          $password = $args[2];
4594          $struct   = $args[3] ?? array();
4595  
4596          $user = $this->login( $username, $password );
4597          if ( ! $user ) {
4598              return $this->error;
4599          }
4600  
4601          if ( ! current_user_can( 'upload_files' ) ) {
4602              return new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
4603          }
4604  
4605          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4606          do_action( 'xmlrpc_call', 'wp.getMediaLibrary', $args, $this );
4607  
4608          $parent_id = ( isset( $struct['parent_id'] ) ) ? absint( $struct['parent_id'] ) : '';
4609          $mime_type = $struct['mime_type'] ?? '';
4610          $offset    = ( isset( $struct['offset'] ) ) ? absint( $struct['offset'] ) : 0;
4611          $number    = ( isset( $struct['number'] ) ) ? absint( $struct['number'] ) : -1;
4612  
4613          $attachments = get_posts(
4614              array(
4615                  'post_type'      => 'attachment',
4616                  'post_parent'    => $parent_id,
4617                  'offset'         => $offset,
4618                  'numberposts'    => $number,
4619                  'post_mime_type' => $mime_type,
4620              )
4621          );
4622  
4623          $attachments_struct = array();
4624  
4625          foreach ( $attachments as $attachment ) {
4626              $attachments_struct[] = $this->_prepare_media_item( $attachment );
4627          }
4628  
4629          return $attachments_struct;
4630      }
4631  
4632      /**
4633       * Retrieves a list of post formats used by the site.
4634       *
4635       * @since 3.1.0
4636       *
4637       * @param array $args {
4638       *     Method arguments. Note: arguments must be ordered as documented.
4639       *
4640       *     @type int    $0 Blog ID (unused).
4641       *     @type string $1 Username.
4642       *     @type string $2 Password.
4643       * }
4644       * @return array|IXR_Error List of post formats, otherwise IXR_Error object.
4645       */
4646  	public function wp_getPostFormats( $args ) {
4647          $this->escape( $args );
4648  
4649          $username = $args[1];
4650          $password = $args[2];
4651  
4652          $user = $this->login( $username, $password );
4653          if ( ! $user ) {
4654              return $this->error;
4655          }
4656  
4657          if ( ! current_user_can( 'edit_posts' ) ) {
4658              return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
4659          }
4660  
4661          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4662          do_action( 'xmlrpc_call', 'wp.getPostFormats', $args, $this );
4663  
4664          $formats = get_post_format_strings();
4665  
4666          // Find out if they want a list of currently supports formats.
4667          if ( isset( $args[3] ) && is_array( $args[3] ) ) {
4668              if ( $args[3]['show-supported'] ) {
4669                  if ( current_theme_supports( 'post-formats' ) ) {
4670                      $supported = get_theme_support( 'post-formats' );
4671  
4672                      $data              = array();
4673                      $data['all']       = $formats;
4674                      $data['supported'] = $supported[0];
4675  
4676                      $formats = $data;
4677                  }
4678              }
4679          }
4680  
4681          return $formats;
4682      }
4683  
4684      /**
4685       * Retrieves a post type.
4686       *
4687       * @since 3.4.0
4688       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
4689       *
4690       * @see get_post_type_object()
4691       *
4692       * @param array $args {
4693       *     Method arguments. Note: arguments must be ordered as documented.
4694       *
4695       *     @type int    $0 Blog ID (unused).
4696       *     @type string $1 Username.
4697       *     @type string $2 Password.
4698       *     @type string $3 Post type name.
4699       *     @type array  $4 Optional. Fields to fetch.
4700       * }
4701       * @return array|IXR_Error Array contains:
4702       *  - 'labels'
4703       *  - 'description'
4704       *  - 'capability_type'
4705       *  - 'cap'
4706       *  - 'map_meta_cap'
4707       *  - 'hierarchical'
4708       *  - 'menu_position'
4709       *  - 'taxonomies'
4710       *  - 'supports'
4711       */
4712  	public function wp_getPostType( $args ) {
4713          if ( ! $this->minimum_args( $args, 4 ) ) {
4714              return $this->error;
4715          }
4716  
4717          $this->escape( $args );
4718  
4719          $username       = $args[1];
4720          $password       = $args[2];
4721          $post_type_name = $args[3];
4722  
4723          if ( isset( $args[4] ) ) {
4724              if ( ! $this->_is_fields_array( $args[4] ) ) {
4725                  return $this->error;
4726              }
4727  
4728              $fields = $args[4];
4729          } else {
4730              /**
4731               * Filters the default post type query fields used by the given XML-RPC method.
4732               *
4733               * @since 3.4.0
4734               *
4735               * @param array  $fields An array of post type fields to retrieve. By default,
4736               *                       contains 'labels', 'cap', and 'taxonomies'.
4737               * @param string $method The method name.
4738               */
4739              $fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostType' );
4740          }
4741  
4742          $user = $this->login( $username, $password );
4743          if ( ! $user ) {
4744              return $this->error;
4745          }
4746  
4747          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4748          do_action( 'xmlrpc_call', 'wp.getPostType', $args, $this );
4749  
4750          if ( ! post_type_exists( $post_type_name ) ) {
4751              return new IXR_Error( 403, __( 'Invalid post type.' ) );
4752          }
4753  
4754          $post_type = get_post_type_object( $post_type_name );
4755  
4756          if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
4757              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
4758          }
4759  
4760          return $this->_prepare_post_type( $post_type, $fields );
4761      }
4762  
4763      /**
4764       * Retrieves post types.
4765       *
4766       * @since 3.4.0
4767       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
4768       *
4769       * @see get_post_types()
4770       *
4771       * @param array $args {
4772       *     Method arguments. Note: arguments must be ordered as documented.
4773       *
4774       *     @type int    $0 Blog ID (unused).
4775       *     @type string $1 Username.
4776       *     @type string $2 Password.
4777       *     @type array  $3 Optional. Query arguments.
4778       *     @type array  $4 Optional. Fields to fetch.
4779       * }
4780       * @return array|IXR_Error
4781       */
4782  	public function wp_getPostTypes( $args ) {
4783          if ( ! $this->minimum_args( $args, 3 ) ) {
4784              return $this->error;
4785          }
4786  
4787          $this->escape( $args );
4788  
4789          $username = $args[1];
4790          $password = $args[2];
4791          $filter   = $args[3] ?? array( 'public' => true );
4792  
4793          if ( isset( $args[4] ) ) {
4794              if ( ! $this->_is_fields_array( $args[4] ) ) {
4795                  return $this->error;
4796              }
4797  
4798              $fields = $args[4];
4799          } else {
4800              /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4801              $fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostTypes' );
4802          }
4803  
4804          $user = $this->login( $username, $password );
4805          if ( ! $user ) {
4806              return $this->error;
4807          }
4808  
4809          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4810          do_action( 'xmlrpc_call', 'wp.getPostTypes', $args, $this );
4811  
4812          $post_types = get_post_types( $filter, 'objects' );
4813  
4814          $struct = array();
4815  
4816          foreach ( $post_types as $post_type ) {
4817              if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
4818                  continue;
4819              }
4820  
4821              $struct[ $post_type->name ] = $this->_prepare_post_type( $post_type, $fields );
4822          }
4823  
4824          return $struct;
4825      }
4826  
4827      /**
4828       * Retrieves revisions for a specific post.
4829       *
4830       * @since 3.5.0
4831       * @since 7.2.0 Returns an error if the `$fields` argument is not an array.
4832       *
4833       * The optional $fields parameter specifies what fields will be included
4834       * in the response array.
4835       *
4836       * @uses wp_get_post_revisions()
4837       * @see wp_getPost() for more on $fields
4838       *
4839       * @param array $args {
4840       *     Method arguments. Note: arguments must be ordered as documented.
4841       *
4842       *     @type int    $0 Blog ID (unused).
4843       *     @type string $1 Username.
4844       *     @type string $2 Password.
4845       *     @type int    $3 Post ID.
4846       *     @type array  $4 Optional. Fields to fetch.
4847       * }
4848       * @return array|IXR_Error Array containing a collection of posts.
4849       */
4850  	public function wp_getRevisions( $args ) {
4851          if ( ! $this->minimum_args( $args, 4 ) ) {
4852              return $this->error;
4853          }
4854  
4855          $this->escape( $args );
4856  
4857          $username = $args[1];
4858          $password = $args[2];
4859          $post_id  = (int) $args[3];
4860  
4861          if ( isset( $args[4] ) ) {
4862              if ( ! $this->_is_fields_array( $args[4] ) ) {
4863                  return $this->error;
4864              }
4865  
4866              $fields = $args[4];
4867          } else {
4868              /**
4869               * Filters the default revision query fields used by the given XML-RPC method.
4870               *
4871               * @since 3.5.0
4872               *
4873               * @param array  $field  An array of revision fields to retrieve. By default,
4874               *                       contains 'post_date' and 'post_date_gmt'.
4875               * @param string $method The method name.
4876               */
4877              $fields = apply_filters( 'xmlrpc_default_revision_fields', array( 'post_date', 'post_date_gmt' ), 'wp.getRevisions' );
4878          }
4879  
4880          $user = $this->login( $username, $password );
4881          if ( ! $user ) {
4882              return $this->error;
4883          }
4884  
4885          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4886          do_action( 'xmlrpc_call', 'wp.getRevisions', $args, $this );
4887  
4888          $post = get_post( $post_id );
4889          if ( ! $post ) {
4890              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4891          }
4892  
4893          if ( ! current_user_can( 'edit_post', $post_id ) ) {
4894              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
4895          }
4896  
4897          // Check if revisions are enabled.
4898          if ( ! wp_revisions_enabled( $post ) ) {
4899              return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
4900          }
4901  
4902          $revisions = wp_get_post_revisions( $post_id );
4903  
4904          if ( ! $revisions ) {
4905              return array();
4906          }
4907  
4908          $struct = array();
4909  
4910          foreach ( $revisions as $revision ) {
4911              if ( ! current_user_can( 'read_post', $revision->ID ) ) {
4912                  continue;
4913              }
4914  
4915              // Skip autosaves.
4916              if ( wp_is_post_autosave( $revision ) ) {
4917                  continue;
4918              }
4919  
4920              $struct[] = $this->_prepare_post( get_object_vars( $revision ), $fields );
4921          }
4922  
4923          return $struct;
4924      }
4925  
4926      /**
4927       * Restores a post revision.
4928       *
4929       * @since 3.5.0
4930       *
4931       * @uses wp_restore_post_revision()
4932       *
4933       * @param array $args {
4934       *     Method arguments. Note: arguments must be ordered as documented.
4935       *
4936       *     @type int    $0 Blog ID (unused).
4937       *     @type string $1 Username.
4938       *     @type string $2 Password.
4939       *     @type int    $3 Revision ID.
4940       * }
4941       * @return bool|IXR_Error false if there was an error restoring, true if success.
4942       */
4943  	public function wp_restoreRevision( $args ) {
4944          if ( ! $this->minimum_args( $args, 3 ) ) {
4945              return $this->error;
4946          }
4947  
4948          $this->escape( $args );
4949  
4950          $username    = $args[1];
4951          $password    = $args[2];
4952          $revision_id = (int) $args[3];
4953  
4954          $user = $this->login( $username, $password );
4955          if ( ! $user ) {
4956              return $this->error;
4957          }
4958  
4959          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4960          do_action( 'xmlrpc_call', 'wp.restoreRevision', $args, $this );
4961  
4962          $revision = wp_get_post_revision( $revision_id );
4963          if ( ! $revision ) {
4964              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4965          }
4966  
4967          if ( wp_is_post_autosave( $revision ) ) {
4968              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4969          }
4970  
4971          $post = get_post( $revision->post_parent );
4972          if ( ! $post ) {
4973              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4974          }
4975  
4976          if ( ! current_user_can( 'edit_post', $revision->post_parent ) ) {
4977              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
4978          }
4979  
4980          // Check if revisions are disabled.
4981          if ( ! wp_revisions_enabled( $post ) ) {
4982              return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
4983          }
4984  
4985          $post = wp_restore_post_revision( $revision_id );
4986  
4987          return (bool) $post;
4988      }
4989  
4990      /*
4991       * Blogger API functions.
4992       * Specs on http://plant.blogger.com/api and https://groups.yahoo.com/group/bloggerDev/
4993       */
4994  
4995      /**
4996       * Retrieves blogs that user owns.
4997       *
4998       * Will make more sense once we support multiple blogs.
4999       *
5000       * @since 1.5.0
5001       *
5002       * @param array $args {
5003       *     Method arguments. Note: arguments must be ordered as documented.
5004       *
5005       *     @type int    $0 Blog ID (unused).
5006       *     @type string $1 Username.
5007       *     @type string $2 Password.
5008       * }
5009       * @return array|IXR_Error
5010       */
5011  	public function blogger_getUsersBlogs( $args ) {
5012          if ( ! $this->minimum_args( $args, 3 ) ) {
5013              return $this->error;
5014          }
5015  
5016          if ( is_multisite() ) {
5017              return $this->_multisite_getUsersBlogs( $args );
5018          }
5019  
5020          $this->escape( $args );
5021  
5022          $username = $args[1];
5023          $password = $args[2];
5024  
5025          $user = $this->login( $username, $password );
5026          if ( ! $user ) {
5027              return $this->error;
5028          }
5029  
5030          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5031          do_action( 'xmlrpc_call', 'blogger.getUsersBlogs', $args, $this );
5032  
5033          $is_admin = current_user_can( 'manage_options' );
5034  
5035          $struct = array(
5036              'isAdmin'  => $is_admin,
5037              'url'      => get_option( 'home' ) . '/',
5038              'blogid'   => '1',
5039              'blogName' => get_option( 'blogname' ),
5040              'xmlrpc'   => site_url( 'xmlrpc.php', 'rpc' ),
5041          );
5042  
5043          return array( $struct );
5044      }
5045  
5046      /**
5047       * Private function for retrieving a users blogs for multisite setups.
5048       *
5049       * @since 3.0.0
5050       *
5051       * @param array $args {
5052       *     Method arguments. Note: arguments must be ordered as documented.
5053       *
5054       *     @type int    $0 Blog ID (unused).
5055       *     @type string $1 Username.
5056       *     @type string $2 Password.
5057       * }
5058       * @return array|IXR_Error
5059       */
5060  	protected function _multisite_getUsersBlogs( $args ) {
5061          $current_blog = get_site();
5062  
5063          $domain = $current_blog->domain;
5064          $path   = $current_blog->path . 'xmlrpc.php';
5065  
5066          $blogs = $this->wp_getUsersBlogs( array( $args[1], $args[2] ) );
5067          if ( $blogs instanceof IXR_Error ) {
5068              return $blogs;
5069          }
5070  
5071          if ( $_SERVER['HTTP_HOST'] === $domain && $_SERVER['REQUEST_URI'] === $path ) {
5072              return $blogs;
5073          } else {
5074              foreach ( (array) $blogs as $blog ) {
5075                  if ( str_contains( $blog['url'], $_SERVER['HTTP_HOST'] ) ) {
5076                      return array( $blog );
5077                  }
5078              }
5079              return array();
5080          }
5081      }
5082  
5083      /**
5084       * Retrieves user's data.
5085       *
5086       * Gives your client some info about you, so you don't have to.
5087       *
5088       * @since 1.5.0
5089       *
5090       * @param array $args {
5091       *     Method arguments. Note: arguments must be ordered as documented.
5092       *
5093       *     @type int    $0 Blog ID (unused).
5094       *     @type string $1 Username.
5095       *     @type string $2 Password.
5096       * }
5097       * @return array|IXR_Error
5098       */
5099  	public function blogger_getUserInfo( $args ) {
5100          $this->escape( $args );
5101  
5102          $username = $args[1];
5103          $password = $args[2];
5104  
5105          $user = $this->login( $username, $password );
5106          if ( ! $user ) {
5107              return $this->error;
5108          }
5109  
5110          if ( ! current_user_can( 'edit_posts' ) ) {
5111              return new IXR_Error( 401, __( 'Sorry, you are not allowed to access user data on this site.' ) );
5112          }
5113  
5114          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5115          do_action( 'xmlrpc_call', 'blogger.getUserInfo', $args, $this );
5116  
5117          $struct = array(
5118              'nickname'  => $user->nickname,
5119              'userid'    => $user->ID,
5120              'url'       => $user->user_url,
5121              'lastname'  => $user->last_name,
5122              'firstname' => $user->first_name,
5123          );
5124  
5125          return $struct;
5126      }
5127  
5128      /**
5129       * Retrieves a post.
5130       *
5131       * @since 1.5.0
5132       *
5133       * @param array $args {
5134       *     Method arguments. Note: arguments must be ordered as documented.
5135       *
5136       *     @type int    $0 Blog ID (unused).
5137       *     @type int    $1 Post ID.
5138       *     @type string $2 Username.
5139       *     @type string $3 Password.
5140       * }
5141       * @return array|IXR_Error
5142       */
5143  	public function blogger_getPost( $args ) {
5144          $this->escape( $args );
5145  
5146          $post_id  = (int) $args[1];
5147          $username = $args[2];
5148          $password = $args[3];
5149  
5150          $user = $this->login( $username, $password );
5151          if ( ! $user ) {
5152              return $this->error;
5153          }
5154  
5155          $post_data = get_post( $post_id, ARRAY_A );
5156          if ( ! $post_data ) {
5157              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
5158          }
5159  
5160          if ( ! current_user_can( 'edit_post', $post_id ) ) {
5161              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
5162          }
5163  
5164          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5165          do_action( 'xmlrpc_call', 'blogger.getPost', $args, $this );
5166  
5167          $categories = implode( ',', wp_get_post_categories( $post_id ) );
5168  
5169          $content  = '<title>' . wp_unslash( $post_data['post_title'] ) . '</title>';
5170          $content .= '<category>' . $categories . '</category>';
5171          $content .= wp_unslash( $post_data['post_content'] );
5172  
5173          $struct = array(
5174              'userid'      => $post_data['post_author'],
5175              'dateCreated' => $this->_convert_date( $post_data['post_date'] ),
5176              'content'     => $content,
5177              'postid'      => (string) $post_data['ID'],
5178          );
5179  
5180          return $struct;
5181      }
5182  
5183      /**
5184       * Retrieves the list of recent posts.
5185       *
5186       * @since 1.5.0
5187       *
5188       * @param array $args {
5189       *     Method arguments. Note: arguments must be ordered as documented.
5190       *
5191       *     @type string $0 App key (unused).
5192       *     @type int    $1 Blog ID (unused).
5193       *     @type string $2 Username.
5194       *     @type string $3 Password.
5195       *     @type int    $4 Optional. Number of posts.
5196       * }
5197       * @return array|IXR_Error
5198       */
5199  	public function blogger_getRecentPosts( $args ) {
5200  
5201          $this->escape( $args );
5202  
5203          // $args[0] = appkey - ignored.
5204          $username = $args[2];
5205          $password = $args[3];
5206          if ( isset( $args[4] ) ) {
5207              $query = array( 'numberposts' => absint( $args[4] ) );
5208          } else {
5209              $query = array();
5210          }
5211  
5212          $user = $this->login( $username, $password );
5213          if ( ! $user ) {
5214              return $this->error;
5215          }
5216  
5217          if ( ! current_user_can( 'edit_posts' ) ) {
5218              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
5219          }
5220  
5221          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5222          do_action( 'xmlrpc_call', 'blogger.getRecentPosts', $args, $this );
5223  
5224          $posts_list = wp_get_recent_posts( $query );
5225  
5226          if ( ! $posts_list ) {
5227              $this->error = new IXR_Error( 500, __( 'No posts found or an error occurred while retrieving posts.' ) );
5228              return $this->error;
5229          }
5230  
5231          $recent_posts = array();
5232          foreach ( $posts_list as $entry ) {
5233              if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
5234                  continue;
5235              }
5236  
5237              $post_date  = $this->_convert_date( $entry['post_date'] );
5238              $categories = implode( ',', wp_get_post_categories( $entry['ID'] ) );
5239  
5240              $content  = '<title>' . wp_unslash( $entry['post_title'] ) . '</title>';
5241              $content .= '<category>' . $categories . '</category>';
5242              $content .= wp_unslash( $entry['post_content'] );
5243  
5244              $recent_posts[] = array(
5245                  'userid'      => $entry['post_author'],
5246                  'dateCreated' => $post_date,
5247                  'content'     => $content,
5248                  'postid'      => (string) $entry['ID'],
5249              );
5250          }
5251  
5252          return $recent_posts;
5253      }
5254  
5255      /**
5256       * Deprecated.
5257       *
5258       * @since 1.5.0
5259       * @deprecated 3.5.0
5260       *
5261       * @param array $args Unused.
5262       * @return IXR_Error Error object.
5263       */
5264  	public function blogger_getTemplate( $args ) {
5265          return new IXR_Error( 403, __( 'Sorry, this method is not supported.' ) );
5266      }
5267  
5268      /**
5269       * Deprecated.
5270       *
5271       * @since 1.5.0
5272       * @deprecated 3.5.0
5273       *
5274       * @param array $args Unused.
5275       * @return IXR_Error Error object.
5276       */
5277  	public function blogger_setTemplate( $args ) {
5278          return new IXR_Error( 403, __( 'Sorry, this method is not supported.' ) );
5279      }
5280  
5281      /**
5282       * Creates a new post.
5283       *
5284       * @since 1.5.0
5285       *
5286       * @param array $args {
5287       *     Method arguments. Note: arguments must be ordered as documented.
5288       *
5289       *     @type string $0 App key (unused).
5290       *     @type int    $1 Blog ID (unused).
5291       *     @type string $2 Username.
5292       *     @type string $3 Password.
5293       *     @type string $4 Content.
5294       *     @type int    $5 Publish flag. 0 for draft, 1 for publish.
5295       * }
5296       * @return int|IXR_Error
5297       */
5298  	public function blogger_newPost( $args ) {
5299          $this->escape( $args );
5300  
5301          $username = $args[2];
5302          $password = $args[3];
5303          $content  = $args[4];
5304          $publish  = $args[5];
5305  
5306          $user = $this->login( $username, $password );
5307          if ( ! $user ) {
5308              return $this->error;
5309          }
5310  
5311          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5312          do_action( 'xmlrpc_call', 'blogger.newPost', $args, $this );
5313  
5314          $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
5315          if ( ! current_user_can( get_post_type_object( 'post' )->cap->create_posts ) || ! current_user_can( $cap ) ) {
5316              return new IXR_Error( 401, __( 'Sorry, you are not allowed to post on this site.' ) );
5317          }
5318  
5319          $post_status = ( $publish ) ? 'publish' : 'draft';
5320  
5321          $post_author = $user->ID;
5322  
5323          $post_title    = xmlrpc_getposttitle( $content );
5324          $post_category = xmlrpc_getpostcategory( $content );
5325          $post_content  = xmlrpc_removepostdata( $content );
5326  
5327          $post_date     = current_time( 'mysql' );
5328          $post_date_gmt = current_time( 'mysql', true );
5329  
5330          $post_data = compact(
5331              'post_author',
5332              'post_date',
5333              'post_date_gmt',
5334              'post_content',
5335              'post_title',
5336              'post_category',
5337              'post_status'
5338          );
5339  
5340          $post_id = wp_insert_post( $post_data );
5341          if ( is_wp_error( $post_id ) ) {
5342              return new IXR_Error( 500, $post_id->get_error_message() );
5343          }
5344  
5345          if ( ! $post_id ) {
5346              return new IXR_Error( 500, __( 'Sorry, the post could not be created.' ) );
5347          }
5348  
5349          $this->attach_uploads( $post_id, $post_content );
5350  
5351          /**
5352           * Fires after a new post has been successfully created via the XML-RPC Blogger API.
5353           *
5354           * @since 3.4.0
5355           *
5356           * @param int   $post_id ID of the new post.
5357           * @param array $args    An array of new post arguments.
5358           */
5359          do_action( 'xmlrpc_call_success_blogger_newPost', $post_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
5360  
5361          return $post_id;
5362      }
5363  
5364      /**
5365       * Edits a post.
5366       *
5367       * @since 1.5.0
5368       *
5369       * @param array $args {
5370       *     Method arguments. Note: arguments must be ordered as documented.
5371       *
5372       *     @type int    $0 Blog ID (unused).
5373       *     @type int    $1 Post ID.
5374       *     @type string $2 Username.
5375       *     @type string $3 Password.
5376       *     @type string $4 Content
5377       *     @type int    $5 Publish flag. 0 for draft, 1 for publish.
5378       * }
5379       * @return true|IXR_Error true when done.
5380       */
5381  	public function blogger_editPost( $args ) {
5382  
5383          $this->escape( $args );
5384  
5385          $post_id  = (int) $args[1];
5386          $username = $args[2];
5387          $password = $args[3];
5388          $content  = $args[4];
5389          $publish  = $args[5];
5390  
5391          $user = $this->login( $username, $password );
5392          if ( ! $user ) {
5393              return $this->error;
5394          }
5395  
5396          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5397          do_action( 'xmlrpc_call', 'blogger.editPost', $args, $this );
5398  
5399          $actual_post = get_post( $post_id, ARRAY_A );
5400  
5401          if ( ! $actual_post || 'post' !== $actual_post['post_type'] ) {
5402              return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
5403          }
5404  
5405          $this->escape( $actual_post );
5406  
5407          if ( ! current_user_can( 'edit_post', $post_id ) ) {
5408              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
5409          }
5410          if ( 'publish' === $actual_post['post_status'] && ! current_user_can( 'publish_posts' ) ) {
5411              return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
5412          }
5413  
5414          $postdata                  = array();
5415          $postdata['ID']            = $actual_post['ID'];
5416          $postdata['post_content']  = xmlrpc_removepostdata( $content );
5417          $postdata['post_title']    = xmlrpc_getposttitle( $content );
5418          $postdata['post_category'] = xmlrpc_getpostcategory( $content );
5419          $postdata['post_status']   = $actual_post['post_status'];
5420          $postdata['post_excerpt']  = $actual_post['post_excerpt'];
5421          $postdata['post_status']   = $publish ? 'publish' : 'draft';
5422  
5423          $result = wp_update_post( $postdata );
5424  
5425          if ( ! $result ) {
5426              return new IXR_Error( 500, __( 'Sorry, the post could not be updated.' ) );
5427          }
5428          $this->attach_uploads( $actual_post['ID'], $postdata['post_content'] );
5429  
5430          /**
5431           * Fires after a post has been successfully updated via the XML-RPC Blogger API.
5432           *
5433           * @since 3.4.0
5434           *
5435           * @param int   $post_id ID of the updated post.
5436           * @param array $args    An array of arguments for the post to edit.
5437           */
5438          do_action( 'xmlrpc_call_success_blogger_editPost', $post_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
5439  
5440          return true;
5441      }
5442  
5443      /**
5444       * Deletes a post.
5445       *
5446       * @since 1.5.0
5447       *
5448       * @param array $args {
5449       *     Method arguments. Note: arguments must be ordered as documented.
5450       *
5451       *     @type int    $0 Blog ID (unused).
5452       *     @type int    $1 Post ID.
5453       *     @type string $2 Username.
5454       *     @type string $3 Password.
5455       * }
5456       * @return true|IXR_Error True when post is deleted.
5457       */
5458  	public function blogger_deletePost( $args ) {
5459          $this->escape( $args );
5460  
5461          $post_id  = (int) $args[1];
5462          $username = $args[2];
5463          $password = $args[3];
5464  
5465          $user = $this->login( $username, $password );
5466          if ( ! $user ) {
5467              return $this->error;
5468          }
5469  
5470          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5471          do_action( 'xmlrpc_call', 'blogger.deletePost', $args, $this );
5472  
5473          $actual_post = get_post( $post_id, ARRAY_A );
5474  
5475          if ( ! $actual_post || 'post' !== $actual_post['post_type'] ) {
5476              return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
5477          }
5478  
5479          if ( ! current_user_can( 'delete_post', $post_id ) ) {
5480              return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
5481          }
5482  
5483          $result = wp_delete_post( $post_id );
5484  
5485          if ( ! $result ) {
5486              return new IXR_Error( 500, __( 'Sorry, the post could not be deleted.' ) );
5487          }
5488  
5489          /**
5490           * Fires after a post has been successfully deleted via the XML-RPC Blogger API.
5491           *
5492           * @since 3.4.0
5493           *
5494           * @param int   $post_id ID of the deleted post.
5495           * @param array $args    An array of arguments to delete the post.
5496           */
5497          do_action( 'xmlrpc_call_success_blogger_deletePost', $post_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
5498  
5499          return true;
5500      }
5501  
5502      /*
5503       * MetaWeblog API functions.
5504       * Specs on wherever Dave Winer wants them to be.
5505       */
5506  
5507      /**
5508       * Creates a new post.
5509       *
5510       * The 'content_struct' argument must contain:
5511       *  - title
5512       *  - description
5513       *  - mt_excerpt
5514       *  - mt_text_more
5515       *  - mt_keywords
5516       *  - mt_tb_ping_urls
5517       *  - categories
5518       *
5519       * Also, it can optionally contain:
5520       *  - wp_slug
5521       *  - wp_password
5522       *  - wp_page_parent_id
5523       *  - wp_page_order
5524       *  - wp_author_id
5525       *  - post_status | page_status - can be 'draft', 'private', 'publish', or 'pending'
5526       *  - mt_allow_comments - can be 'open' or 'closed'
5527       *  - mt_allow_pings - can be 'open' or 'closed'
5528       *  - date_created_gmt
5529       *  - dateCreated
5530       *  - wp_post_thumbnail
5531       *
5532       * @since 1.5.0
5533       *
5534       * @param array $args {
5535       *     Method arguments. Note: arguments must be ordered as documented.
5536       *
5537       *     @type int    $0 Blog ID (unused).
5538       *     @type string $1 Username.
5539       *     @type string $2 Password.
5540       *     @type array  $3 Content structure.
5541       *     @type int    $4 Optional. Publish flag. 0 for draft, 1 for publish. Default 0.
5542       * }
5543       * @return int|IXR_Error
5544       */
5545  	public function mw_newPost( $args ) {
5546          $this->escape( $args );
5547  
5548          $username       = $args[1];
5549          $password       = $args[2];
5550          $content_struct = $args[3];
5551          $publish        = $args[4] ?? 0;
5552  
5553          $user = $this->login( $username, $password );
5554          if ( ! $user ) {
5555              return $this->error;
5556          }
5557  
5558          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5559          do_action( 'xmlrpc_call', 'metaWeblog.newPost', $args, $this );
5560  
5561          $page_template = '';
5562          if ( ! empty( $content_struct['post_type'] ) ) {
5563              if ( 'page' === $content_struct['post_type'] ) {
5564                  if ( $publish ) {
5565                      $cap = 'publish_pages';
5566                  } elseif ( isset( $content_struct['page_status'] ) && 'publish' === $content_struct['page_status'] ) {
5567                      $cap = 'publish_pages';
5568                  } else {
5569                      $cap = 'edit_pages';
5570                  }
5571                  $error_message = __( 'Sorry, you are not allowed to publish pages on this site.' );
5572                  $post_type     = 'page';
5573                  if ( ! empty( $content_struct['wp_page_template'] ) ) {
5574                      $page_template = $content_struct['wp_page_template'];
5575                  }
5576              } elseif ( 'post' === $content_struct['post_type'] ) {
5577                  if ( $publish ) {
5578                      $cap = 'publish_posts';
5579                  } elseif ( isset( $content_struct['post_status'] ) && 'publish' === $content_struct['post_status'] ) {
5580                      $cap = 'publish_posts';
5581                  } else {
5582                      $cap = 'edit_posts';
5583                  }
5584                  $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
5585                  $post_type     = 'post';
5586              } else {
5587                  // No other 'post_type' values are allowed here.
5588                  return new IXR_Error( 401, __( 'Invalid post type.' ) );
5589              }
5590          } else {
5591              if ( $publish ) {
5592                  $cap = 'publish_posts';
5593              } elseif ( isset( $content_struct['post_status'] ) && 'publish' === $content_struct['post_status'] ) {
5594                  $cap = 'publish_posts';
5595              } else {
5596                  $cap = 'edit_posts';
5597              }
5598              $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
5599              $post_type     = 'post';
5600          }
5601  
5602          if ( ! current_user_can( get_post_type_object( $post_type )->cap->create_posts ) ) {
5603              return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts on this site.' ) );
5604          }
5605          if ( ! current_user_can( $cap ) ) {
5606              return new IXR_Error( 401, $error_message );
5607          }
5608  
5609          // Check for a valid post format if one was given.
5610          if ( isset( $content_struct['wp_post_format'] ) ) {
5611              $content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
5612              if ( ! array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
5613                  return new IXR_Error( 404, __( 'Invalid post format.' ) );
5614              }
5615          }
5616  
5617          // Let WordPress generate the 'post_name' (slug) unless
5618          // one has been provided.
5619          $post_name = null;
5620          if ( isset( $content_struct['wp_slug'] ) ) {
5621              $post_name = $content_struct['wp_slug'];
5622          }
5623  
5624          // Only use a password if one was given.
5625          $post_password = '';
5626          if ( isset( $content_struct['wp_password'] ) ) {
5627              $post_password = $content_struct['wp_password'];
5628          }
5629  
5630          // Only set a post parent if one was given.
5631          $post_parent = 0;
5632          if ( isset( $content_struct['wp_page_parent_id'] ) ) {
5633              $post_parent = $content_struct['wp_page_parent_id'];
5634          }
5635  
5636          // Only set the 'menu_order' if it was given.
5637          $menu_order = 0;
5638          if ( isset( $content_struct['wp_page_order'] ) ) {
5639              $menu_order = $content_struct['wp_page_order'];
5640          }
5641  
5642          $post_author = $user->ID;
5643  
5644          // If an author ID was provided then use it instead.
5645          if ( isset( $content_struct['wp_author_id'] ) && ( $user->ID !== (int) $content_struct['wp_author_id'] ) ) {
5646              switch ( $post_type ) {
5647                  case 'post':
5648                      if ( ! current_user_can( 'edit_others_posts' ) ) {
5649                          return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
5650                      }
5651                      break;
5652                  case 'page':
5653                      if ( ! current_user_can( 'edit_others_pages' ) ) {
5654                          return new IXR_Error( 401, __( 'Sorry, you are not allowed to create pages as this user.' ) );
5655                      }
5656                      break;
5657                  default:
5658                      return new IXR_Error( 401, __( 'Invalid post type.' ) );
5659              }
5660              $author = get_userdata( $content_struct['wp_author_id'] );
5661              if ( ! $author ) {
5662                  return new IXR_Error( 404, __( 'Invalid author ID.' ) );
5663              }
5664              $post_author = $content_struct['wp_author_id'];
5665          }
5666  
5667          $post_title   = $content_struct['title'] ?? '';
5668          $post_content = $content_struct['description'] ?? '';
5669  
5670          $post_status = $publish ? 'publish' : 'draft';
5671  
5672          if ( isset( $content_struct[ "{$post_type}_status" ] ) ) {
5673              switch ( $content_struct[ "{$post_type}_status" ] ) {
5674                  case 'draft':
5675                  case 'pending':
5676                  case 'private':
5677                  case 'publish':
5678                      $post_status = $content_struct[ "{$post_type}_status" ];
5679                      break;
5680                  default:
5681                      // Deliberably left empty.
5682                      break;
5683              }
5684          }
5685  
5686          $post_excerpt = $content_struct['mt_excerpt'] ?? '';
5687          $post_more    = $content_struct['mt_text_more'] ?? '';
5688  
5689          $tags_input = $content_struct['mt_keywords'] ?? array();
5690  
5691          if ( isset( $content_struct['mt_allow_comments'] ) ) {
5692              if ( ! is_numeric( $content_struct['mt_allow_comments'] ) ) {
5693                  switch ( $content_struct['mt_allow_comments'] ) {
5694                      case 'closed':
5695                          $comment_status = 'closed';
5696                          break;
5697                      case 'open':
5698                          $comment_status = 'open';
5699                          break;
5700                      default:
5701                          $comment_status = get_default_comment_status( $post_type );
5702                          break;
5703                  }
5704              } else {
5705                  switch ( (int) $content_struct['mt_allow_comments'] ) {
5706                      case 0:
5707                      case 2:
5708                          $comment_status = 'closed';
5709                          break;
5710                      case 1:
5711                          $comment_status = 'open';
5712                          break;
5713                      default:
5714                          $comment_status = get_default_comment_status( $post_type );
5715                          break;
5716                  }
5717              }
5718          } else {
5719              $comment_status = get_default_comment_status( $post_type );
5720          }
5721  
5722          if ( isset( $content_struct['mt_allow_pings'] ) ) {
5723              if ( ! is_numeric( $content_struct['mt_allow_pings'] ) ) {
5724                  switch ( $content_struct['mt_allow_pings'] ) {
5725                      case 'closed':
5726                          $ping_status = 'closed';
5727                          break;
5728                      case 'open':
5729                          $ping_status = 'open';
5730                          break;
5731                      default:
5732                          $ping_status = get_default_comment_status( $post_type, 'pingback' );
5733                          break;
5734                  }
5735              } else {
5736                  switch ( (int) $content_struct['mt_allow_pings'] ) {
5737                      case 0:
5738                          $ping_status = 'closed';
5739                          break;
5740                      case 1:
5741                          $ping_status = 'open';
5742                          break;
5743                      default:
5744                          $ping_status = get_default_comment_status( $post_type, 'pingback' );
5745                          break;
5746                  }
5747              }
5748          } else {
5749              $ping_status = get_default_comment_status( $post_type, 'pingback' );
5750          }
5751  
5752          if ( $post_more ) {
5753              $post_content .= '<!--more-->' . $post_more;
5754          }
5755  
5756          $to_ping = '';
5757          if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
5758              $to_ping = $content_struct['mt_tb_ping_urls'];
5759              if ( is_array( $to_ping ) ) {
5760                  $to_ping = implode( ' ', $to_ping );
5761              }
5762          }
5763  
5764          // Do some timestamp voodoo.
5765          if ( ! empty( $content_struct['date_created_gmt'] ) ) {
5766              // We know this is supposed to be GMT, so we're going to slap that Z on there by force.
5767              $date_created = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
5768          } elseif ( ! empty( $content_struct['dateCreated'] ) ) {
5769              $date_created = $content_struct['dateCreated']->getIso();
5770          }
5771  
5772          $post_date     = '';
5773          $post_date_gmt = '';
5774          if ( ! empty( $date_created ) ) {
5775              $post_date     = iso8601_to_datetime( $date_created );
5776              $post_date_gmt = iso8601_to_datetime( $date_created, 'gmt' );
5777          }
5778  
5779          $post_category = array();
5780          if ( isset( $content_struct['categories'] ) ) {
5781              $catnames = $content_struct['categories'];
5782  
5783              if ( is_array( $catnames ) ) {
5784                  foreach ( $catnames as $cat ) {
5785                      $post_category[] = get_cat_ID( $cat );
5786                  }
5787              }
5788          }
5789  
5790          $postdata = compact(
5791              'post_author',
5792              'post_date',
5793              'post_date_gmt',
5794              'post_content',
5795              'post_title',
5796              'post_category',
5797              'post_status',
5798              'post_excerpt',
5799              'comment_status',
5800              'ping_status',
5801              'to_ping',
5802              'post_type',
5803              'post_name',
5804              'post_password',
5805              'post_parent',
5806              'menu_order',
5807              'tags_input',
5808              'page_template'
5809          );
5810  
5811          $post_id        = get_default_post_to_edit( $post_type, true )->ID;
5812          $postdata['ID'] = $post_id;
5813  
5814          // Only posts can be sticky.
5815          if ( 'post' === $post_type && isset( $content_struct['sticky'] ) ) {
5816              $data           = $postdata;
5817              $data['sticky'] = $content_struct['sticky'];
5818              $error          = $this->_toggle_sticky( $data );
5819              if ( $error ) {
5820                  return $error;
5821              }
5822          }
5823  
5824          if ( isset( $content_struct['custom_fields'] ) ) {
5825              $this->set_custom_fields( $post_id, $content_struct['custom_fields'] );
5826          }
5827  
5828          if ( isset( $content_struct['wp_post_thumbnail'] ) ) {
5829              if ( set_post_thumbnail( $post_id, $content_struct['wp_post_thumbnail'] ) === false ) {
5830                  return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
5831              }
5832  
5833              unset( $content_struct['wp_post_thumbnail'] );
5834          }
5835  
5836          // Handle enclosures.
5837          $enclosure = $content_struct['enclosure'] ?? null;
5838          $this->add_enclosure_if_new( $post_id, $enclosure );
5839  
5840          $this->attach_uploads( $post_id, $post_content );
5841  
5842          /*
5843           * Handle post formats if assigned, value is validated earlier
5844           * in this function.
5845           */
5846          if ( isset( $content_struct['wp_post_format'] ) ) {
5847              set_post_format( $post_id, $content_struct['wp_post_format'] );
5848          }
5849  
5850          $post_id = wp_insert_post( $postdata, true );
5851          if ( is_wp_error( $post_id ) ) {
5852              return new IXR_Error( 500, $post_id->get_error_message() );
5853          }
5854  
5855          if ( ! $post_id ) {
5856              return new IXR_Error( 500, __( 'Sorry, the post could not be created.' ) );
5857          }
5858  
5859          /**
5860           * Fires after a new post has been successfully created via the XML-RPC MovableType API.
5861           *
5862           * @since 3.4.0
5863           *
5864           * @param int   $post_id ID of the new post.
5865           * @param array $args    An array of arguments to create the new post.
5866           */
5867          do_action( 'xmlrpc_call_success_mw_newPost', $post_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
5868  
5869          return (string) $post_id;
5870      }
5871  
5872      /**
5873       * Adds an enclosure to a post if it's new.
5874       *
5875       * @since 2.8.0
5876       *
5877       * @param int   $post_id   Post ID.
5878       * @param array $enclosure Enclosure data.
5879       */
5880  	public function add_enclosure_if_new( $post_id, $enclosure ) {
5881          if ( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
5882              $encstring  = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'] . "\n";
5883              $found      = false;
5884              $enclosures = get_post_meta( $post_id, 'enclosure' );
5885              if ( $enclosures ) {
5886                  foreach ( $enclosures as $enc ) {
5887                      // This method used to omit the trailing new line. #23219
5888                      if ( rtrim( $enc, "\n" ) === rtrim( $encstring, "\n" ) ) {
5889                          $found = true;
5890                          break;
5891                      }
5892                  }
5893              }
5894              if ( ! $found ) {
5895                  add_post_meta( $post_id, 'enclosure', $encstring );
5896              }
5897          }
5898      }
5899  
5900      /**
5901       * Attaches an upload to a post.
5902       *
5903       * @since 2.1.0
5904       *
5905       * @global wpdb $wpdb WordPress database abstraction object.
5906       *
5907       * @param int    $post_id      Post ID.
5908       * @param string $post_content Post Content for attachment.
5909       */
5910  	public function attach_uploads( $post_id, $post_content ) {
5911          global $wpdb;
5912  
5913          // Find any unattached files.
5914          $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '0' AND post_type = 'attachment'" );
5915          if ( is_array( $attachments ) ) {
5916              foreach ( $attachments as $file ) {
5917                  if ( ! empty( $file->guid ) && str_contains( $post_content, $file->guid ) ) {
5918                      $wpdb->update( $wpdb->posts, array( 'post_parent' => $post_id ), array( 'ID' => $file->ID ) );
5919                  }
5920              }
5921          }
5922      }
5923  
5924      /**
5925       * Edits a post.
5926       *
5927       * @since 1.5.0
5928       *
5929       * @param array $args {
5930       *     Method arguments. Note: arguments must be ordered as documented.
5931       *
5932       *     @type int    $0 Post ID.
5933       *     @type string $1 Username.
5934       *     @type string $2 Password.
5935       *     @type array  $3 Content structure.
5936       *     @type int    $4 Optional. Publish flag. 0 for draft, 1 for publish. Default 0.
5937       * }
5938       * @return true|IXR_Error True on success.
5939       */
5940  	public function mw_editPost( $args ) {
5941          $this->escape( $args );
5942  
5943          $post_id        = (int) $args[0];
5944          $username       = $args[1];
5945          $password       = $args[2];
5946          $content_struct = $args[3];
5947          $publish        = $args[4] ?? 0;
5948  
5949          $user = $this->login( $username, $password );
5950          if ( ! $user ) {
5951              return $this->error;
5952          }
5953  
5954          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5955          do_action( 'xmlrpc_call', 'metaWeblog.editPost', $args, $this );
5956  
5957          $postdata = get_post( $post_id, ARRAY_A );
5958  
5959          /*
5960           * If there is no post data for the give post ID, stop now and return an error.
5961           * Otherwise a new post will be created (which was the old behavior).
5962           */
5963          if ( ! $postdata || empty( $postdata['ID'] ) ) {
5964              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
5965          }
5966  
5967          if ( ! current_user_can( 'edit_post', $post_id ) ) {
5968              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
5969          }
5970  
5971          // Use wp.editPost to edit post types other than post and page.
5972          if ( ! in_array( $postdata['post_type'], array( 'post', 'page' ), true ) ) {
5973              return new IXR_Error( 401, __( 'Invalid post type.' ) );
5974          }
5975  
5976          // Thwart attempt to change the post type.
5977          if ( ! empty( $content_struct['post_type'] ) && ( $content_struct['post_type'] !== $postdata['post_type'] ) ) {
5978              return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
5979          }
5980  
5981          // Check for a valid post format if one was given.
5982          if ( isset( $content_struct['wp_post_format'] ) ) {
5983              $content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
5984              if ( ! array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
5985                  return new IXR_Error( 404, __( 'Invalid post format.' ) );
5986              }
5987          }
5988  
5989          $this->escape( $postdata );
5990  
5991          $post_id        = $postdata['ID'];
5992          $post_content   = $postdata['post_content'];
5993          $post_title     = $postdata['post_title'];
5994          $post_excerpt   = $postdata['post_excerpt'];
5995          $post_password  = $postdata['post_password'];
5996          $post_parent    = $postdata['post_parent'];
5997          $post_type      = $postdata['post_type'];
5998          $menu_order     = $postdata['menu_order'];
5999          $ping_status    = $postdata['ping_status'];
6000          $comment_status = $postdata['comment_status'];
6001  
6002          // Let WordPress manage slug if none was provided.
6003          $post_name = $postdata['post_name'];
6004          if ( isset( $content_struct['wp_slug'] ) ) {
6005              $post_name = $content_struct['wp_slug'];
6006          }
6007  
6008          // Only use a password if one was given.
6009          if ( isset( $content_struct['wp_password'] ) ) {
6010              $post_password = $content_struct['wp_password'];
6011          }
6012  
6013          // Only set a post parent if one was given.
6014          if ( isset( $content_struct['wp_page_parent_id'] ) ) {
6015              $post_parent = $content_struct['wp_page_parent_id'];
6016          }
6017  
6018          // Only set the 'menu_order' if it was given.
6019          if ( isset( $content_struct['wp_page_order'] ) ) {
6020              $menu_order = $content_struct['wp_page_order'];
6021          }
6022  
6023          $page_template = '';
6024          if ( ! empty( $content_struct['wp_page_template'] ) && 'page' === $post_type ) {
6025              $page_template = $content_struct['wp_page_template'];
6026          }
6027  
6028          $post_author = $postdata['post_author'];
6029  
6030          // If an author ID was provided then use it instead.
6031          if ( isset( $content_struct['wp_author_id'] ) ) {
6032              // Check permissions if attempting to switch author to or from another user.
6033              if ( $user->ID !== (int) $content_struct['wp_author_id'] || $user->ID !== (int) $post_author ) {
6034                  switch ( $post_type ) {
6035                      case 'post':
6036                          if ( ! current_user_can( 'edit_others_posts' ) ) {
6037                              return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the post author as this user.' ) );
6038                          }
6039                          break;
6040                      case 'page':
6041                          if ( ! current_user_can( 'edit_others_pages' ) ) {
6042                              return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the page author as this user.' ) );
6043                          }
6044                          break;
6045                      default:
6046                          return new IXR_Error( 401, __( 'Invalid post type.' ) );
6047                  }
6048                  $post_author = $content_struct['wp_author_id'];
6049              }
6050          }
6051  
6052          if ( isset( $content_struct['mt_allow_comments'] ) ) {
6053              if ( ! is_numeric( $content_struct['mt_allow_comments'] ) ) {
6054                  switch ( $content_struct['mt_allow_comments'] ) {
6055                      case 'closed':
6056                          $comment_status = 'closed';
6057                          break;
6058                      case 'open':
6059                          $comment_status = 'open';
6060                          break;
6061                      default:
6062                          $comment_status = get_default_comment_status( $post_type );
6063                          break;
6064                  }
6065              } else {
6066                  switch ( (int) $content_struct['mt_allow_comments'] ) {
6067                      case 0:
6068                      case 2:
6069                          $comment_status = 'closed';
6070                          break;
6071                      case 1:
6072                          $comment_status = 'open';
6073                          break;
6074                      default:
6075                          $comment_status = get_default_comment_status( $post_type );
6076                          break;
6077                  }
6078              }
6079          }
6080  
6081          if ( isset( $content_struct['mt_allow_pings'] ) ) {
6082              if ( ! is_numeric( $content_struct['mt_allow_pings'] ) ) {
6083                  switch ( $content_struct['mt_allow_pings'] ) {
6084                      case 'closed':
6085                          $ping_status = 'closed';
6086                          break;
6087                      case 'open':
6088                          $ping_status = 'open';
6089                          break;
6090                      default:
6091                          $ping_status = get_default_comment_status( $post_type, 'pingback' );
6092                          break;
6093                  }
6094              } else {
6095                  switch ( (int) $content_struct['mt_allow_pings'] ) {
6096                      case 0:
6097                          $ping_status = 'closed';
6098                          break;
6099                      case 1:
6100                          $ping_status = 'open';
6101                          break;
6102                      default:
6103                          $ping_status = get_default_comment_status( $post_type, 'pingback' );
6104                          break;
6105                  }
6106              }
6107          }
6108  
6109          if ( isset( $content_struct['title'] ) ) {
6110              $post_title = $content_struct['title'];
6111          }
6112  
6113          if ( isset( $content_struct['description'] ) ) {
6114              $post_content = $content_struct['description'];
6115          }
6116  
6117          $post_category = array();
6118          if ( isset( $content_struct['categories'] ) ) {
6119              $catnames = $content_struct['categories'];
6120              if ( is_array( $catnames ) ) {
6121                  foreach ( $catnames as $cat ) {
6122                      $post_category[] = get_cat_ID( $cat );
6123                  }
6124              }
6125          }
6126  
6127          if ( isset( $content_struct['mt_excerpt'] ) ) {
6128              $post_excerpt = $content_struct['mt_excerpt'];
6129          }
6130  
6131          $post_more = $content_struct['mt_text_more'] ?? '';
6132  
6133          $post_status = $publish ? 'publish' : 'draft';
6134          if ( isset( $content_struct[ "{$post_type}_status" ] ) ) {
6135              switch ( $content_struct[ "{$post_type}_status" ] ) {
6136                  case 'draft':
6137                  case 'pending':
6138                  case 'private':
6139                  case 'publish':
6140                      $post_status = $content_struct[ "{$post_type}_status" ];
6141                      break;
6142                  default:
6143                      $post_status = $publish ? 'publish' : 'draft';
6144                      break;
6145              }
6146          }
6147  
6148          $tags_input = $content_struct['mt_keywords'] ?? array();
6149  
6150          if ( 'publish' === $post_status || 'private' === $post_status ) {
6151              if ( 'page' === $post_type && ! current_user_can( 'publish_pages' ) ) {
6152                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this page.' ) );
6153              } elseif ( ! current_user_can( 'publish_posts' ) ) {
6154                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
6155              }
6156          }
6157  
6158          if ( $post_more ) {
6159              $post_content = $post_content . '<!--more-->' . $post_more;
6160          }
6161  
6162          $to_ping = '';
6163          if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
6164              $to_ping = $content_struct['mt_tb_ping_urls'];
6165              if ( is_array( $to_ping ) ) {
6166                  $to_ping = implode( ' ', $to_ping );
6167              }
6168          }
6169  
6170          // Do some timestamp voodoo.
6171          if ( ! empty( $content_struct['date_created_gmt'] ) ) {
6172              // We know this is supposed to be GMT, so we're going to slap that Z on there by force.
6173              $date_created = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
6174          } elseif ( ! empty( $content_struct['dateCreated'] ) ) {
6175              $date_created = $content_struct['dateCreated']->getIso();
6176          }
6177  
6178          // Default to not flagging the post date to be edited unless it's intentional.
6179          $edit_date = false;
6180  
6181          if ( ! empty( $date_created ) ) {
6182              $post_date     = iso8601_to_datetime( $date_created );
6183              $post_date_gmt = iso8601_to_datetime( $date_created, 'gmt' );
6184  
6185              // Flag the post date to be edited.
6186              $edit_date = true;
6187          } else {
6188              $post_date     = $postdata['post_date'];
6189              $post_date_gmt = $postdata['post_date_gmt'];
6190          }
6191  
6192          $newpost = array(
6193              'ID' => $post_id,
6194          );
6195  
6196          $newpost += compact(
6197              'post_content',
6198              'post_title',
6199              'post_category',
6200              'post_status',
6201              'post_excerpt',
6202              'comment_status',
6203              'ping_status',
6204              'edit_date',
6205              'post_date',
6206              'post_date_gmt',
6207              'to_ping',
6208              'post_name',
6209              'post_password',
6210              'post_parent',
6211              'menu_order',
6212              'post_author',
6213              'tags_input',
6214              'page_template'
6215          );
6216  
6217          // We've got all the data -- post it.
6218          $result = wp_update_post( $newpost, true );
6219          if ( is_wp_error( $result ) ) {
6220              return new IXR_Error( 500, $result->get_error_message() );
6221          }
6222  
6223          if ( ! $result ) {
6224              return new IXR_Error( 500, __( 'Sorry, the post could not be updated.' ) );
6225          }
6226  
6227          // Only posts can be sticky.
6228          if ( 'post' === $post_type && isset( $content_struct['sticky'] ) ) {
6229              $data              = $newpost;
6230              $data['sticky']    = $content_struct['sticky'];
6231              $data['post_type'] = 'post';
6232              $error             = $this->_toggle_sticky( $data, true );
6233              if ( $error ) {
6234                  return $error;
6235              }
6236          }
6237  
6238          if ( isset( $content_struct['custom_fields'] ) ) {
6239              $this->set_custom_fields( $post_id, $content_struct['custom_fields'] );
6240          }
6241  
6242          if ( isset( $content_struct['wp_post_thumbnail'] ) ) {
6243  
6244              // Empty value deletes, non-empty value adds/updates.
6245              if ( empty( $content_struct['wp_post_thumbnail'] ) ) {
6246                  delete_post_thumbnail( $post_id );
6247              } else {
6248                  if ( set_post_thumbnail( $post_id, $content_struct['wp_post_thumbnail'] ) === false ) {
6249                      return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
6250                  }
6251              }
6252              unset( $content_struct['wp_post_thumbnail'] );
6253          }
6254  
6255          // Handle enclosures.
6256          $enclosure = $content_struct['enclosure'] ?? null;
6257          $this->add_enclosure_if_new( $post_id, $enclosure );
6258  
6259          $this->attach_uploads( $post_id, $post_content );
6260  
6261          // Handle post formats if assigned, validation is handled earlier in this function.
6262          if ( isset( $content_struct['wp_post_format'] ) ) {
6263              set_post_format( $post_id, $content_struct['wp_post_format'] );
6264          }
6265  
6266          /**
6267           * Fires after a post has been successfully updated via the XML-RPC MovableType API.
6268           *
6269           * @since 3.4.0
6270           *
6271           * @param int   $post_id ID of the updated post.
6272           * @param array $args    An array of arguments to update the post.
6273           */
6274          do_action( 'xmlrpc_call_success_mw_editPost', $post_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
6275  
6276          return true;
6277      }
6278  
6279      /**
6280       * Retrieves a post.
6281       *
6282       * @since 1.5.0
6283       *
6284       * @param array $args {
6285       *     Method arguments. Note: arguments must be ordered as documented.
6286       *
6287       *     @type int    $0 Post ID.
6288       *     @type string $1 Username.
6289       *     @type string $2 Password.
6290       * }
6291       * @return array|IXR_Error
6292       */
6293  	public function mw_getPost( $args ) {
6294          $this->escape( $args );
6295  
6296          $post_id  = (int) $args[0];
6297          $username = $args[1];
6298          $password = $args[2];
6299  
6300          $user = $this->login( $username, $password );
6301          if ( ! $user ) {
6302              return $this->error;
6303          }
6304  
6305          $postdata = get_post( $post_id, ARRAY_A );
6306          if ( ! $postdata ) {
6307              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
6308          }
6309  
6310          if ( ! current_user_can( 'edit_post', $post_id ) ) {
6311              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
6312          }
6313  
6314          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6315          do_action( 'xmlrpc_call', 'metaWeblog.getPost', $args, $this );
6316  
6317          if ( '' !== $postdata['post_date'] ) {
6318              $post_date         = $this->_convert_date( $postdata['post_date'] );
6319              $post_date_gmt     = $this->_convert_date_gmt( $postdata['post_date_gmt'], $postdata['post_date'] );
6320              $post_modified     = $this->_convert_date( $postdata['post_modified'] );
6321              $post_modified_gmt = $this->_convert_date_gmt( $postdata['post_modified_gmt'], $postdata['post_modified'] );
6322  
6323              $categories = array();
6324              $cat_ids    = wp_get_post_categories( $post_id );
6325              foreach ( $cat_ids as $cat_id ) {
6326                  $categories[] = get_cat_name( $cat_id );
6327              }
6328  
6329              $tagnames = array();
6330              $tags     = wp_get_post_tags( $post_id );
6331              if ( ! empty( $tags ) ) {
6332                  foreach ( $tags as $tag ) {
6333                      $tagnames[] = $tag->name;
6334                  }
6335                  $tagnames = implode( ', ', $tagnames );
6336              } else {
6337                  $tagnames = '';
6338              }
6339  
6340              $post = get_extended( $postdata['post_content'] );
6341              $link = get_permalink( $postdata['ID'] );
6342  
6343              // Get the author info.
6344              $author = get_userdata( $postdata['post_author'] );
6345  
6346              $allow_comments = ( 'open' === $postdata['comment_status'] ) ? 1 : 0;
6347              $allow_pings    = ( 'open' === $postdata['ping_status'] ) ? 1 : 0;
6348  
6349              // Consider future posts as published.
6350              if ( 'future' === $postdata['post_status'] ) {
6351                  $postdata['post_status'] = 'publish';
6352              }
6353  
6354              // Get post format.
6355              $post_format = get_post_format( $post_id );
6356              if ( empty( $post_format ) ) {
6357                  $post_format = 'standard';
6358              }
6359  
6360              $sticky = false;
6361              if ( is_sticky( $post_id ) ) {
6362                  $sticky = true;
6363              }
6364  
6365              $enclosure = array();
6366              foreach ( (array) get_post_custom( $post_id ) as $key => $val ) {
6367                  if ( 'enclosure' === $key ) {
6368                      foreach ( (array) $val as $enc ) {
6369                          $encdata             = explode( "\n", $enc );
6370                          $enclosure['url']    = trim( htmlspecialchars( $encdata[0] ) );
6371                          $enclosure['length'] = (int) trim( $encdata[1] );
6372                          $enclosure['type']   = trim( $encdata[2] );
6373                          break 2;
6374                      }
6375                  }
6376              }
6377  
6378              $resp = array(
6379                  'dateCreated'            => $post_date,
6380                  'userid'                 => $postdata['post_author'],
6381                  'postid'                 => $postdata['ID'],
6382                  'description'            => $post['main'],
6383                  'title'                  => $postdata['post_title'],
6384                  'link'                   => $link,
6385                  'permaLink'              => $link,
6386                  // Commented out because no other tool seems to use this.
6387                  // 'content' => $entry['post_content'],
6388                  'categories'             => $categories,
6389                  'mt_excerpt'             => $postdata['post_excerpt'],
6390                  'mt_text_more'           => $post['extended'],
6391                  'wp_more_text'           => $post['more_text'],
6392                  'mt_allow_comments'      => $allow_comments,
6393                  'mt_allow_pings'         => $allow_pings,
6394                  'mt_keywords'            => $tagnames,
6395                  'wp_slug'                => $postdata['post_name'],
6396                  'wp_password'            => $postdata['post_password'],
6397                  'wp_author_id'           => (string) $author->ID,
6398                  'wp_author_display_name' => $author->display_name,
6399                  'date_created_gmt'       => $post_date_gmt,
6400                  'post_status'            => $postdata['post_status'],
6401                  'custom_fields'          => $this->get_custom_fields( $post_id ),
6402                  'wp_post_format'         => $post_format,
6403                  'sticky'                 => $sticky,
6404                  'date_modified'          => $post_modified,
6405                  'date_modified_gmt'      => $post_modified_gmt,
6406              );
6407  
6408              if ( ! empty( $enclosure ) ) {
6409                  $resp['enclosure'] = $enclosure;
6410              }
6411  
6412              $resp['wp_post_thumbnail'] = get_post_thumbnail_id( $postdata['ID'] );
6413  
6414              return $resp;
6415          } else {
6416              return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
6417          }
6418      }
6419  
6420      /**
6421       * Retrieves list of recent posts.
6422       *
6423       * @since 1.5.0
6424       *
6425       * @param array $args {
6426       *     Method arguments. Note: arguments must be ordered as documented.
6427       *
6428       *     @type int    $0 Blog ID (unused).
6429       *     @type string $1 Username.
6430       *     @type string $2 Password.
6431       *     @type int    $3 Optional. Number of posts.
6432       * }
6433       * @return array|IXR_Error
6434       */
6435  	public function mw_getRecentPosts( $args ) {
6436          $this->escape( $args );
6437  
6438          $username = $args[1];
6439          $password = $args[2];
6440          if ( isset( $args[3] ) ) {
6441              $query = array( 'numberposts' => absint( $args[3] ) );
6442          } else {
6443              $query = array();
6444          }
6445  
6446          $user = $this->login( $username, $password );
6447          if ( ! $user ) {
6448              return $this->error;
6449          }
6450  
6451          if ( ! current_user_can( 'edit_posts' ) ) {
6452              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
6453          }
6454  
6455          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6456          do_action( 'xmlrpc_call', 'metaWeblog.getRecentPosts', $args, $this );
6457  
6458          $posts_list = wp_get_recent_posts( $query );
6459  
6460          if ( ! $posts_list ) {
6461              return array();
6462          }
6463  
6464          $recent_posts = array();
6465          foreach ( $posts_list as $entry ) {
6466              if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
6467                  continue;
6468              }
6469  
6470              $post_date         = $this->_convert_date( $entry['post_date'] );
6471              $post_date_gmt     = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
6472              $post_modified     = $this->_convert_date( $entry['post_modified'] );
6473              $post_modified_gmt = $this->_convert_date_gmt( $entry['post_modified_gmt'], $entry['post_modified'] );
6474  
6475              $categories = array();
6476              $cat_ids    = wp_get_post_categories( $entry['ID'] );
6477              foreach ( $cat_ids as $cat_id ) {
6478                  $categories[] = get_cat_name( $cat_id );
6479              }
6480  
6481              $tagnames = array();
6482              $tags     = wp_get_post_tags( $entry['ID'] );
6483              if ( ! empty( $tags ) ) {
6484                  foreach ( $tags as $tag ) {
6485                      $tagnames[] = $tag->name;
6486                  }
6487                  $tagnames = implode( ', ', $tagnames );
6488              } else {
6489                  $tagnames = '';
6490              }
6491  
6492              $post = get_extended( $entry['post_content'] );
6493              $link = get_permalink( $entry['ID'] );
6494  
6495              // Get the post author info.
6496              $author = get_userdata( $entry['post_author'] );
6497  
6498              $allow_comments = ( 'open' === $entry['comment_status'] ) ? 1 : 0;
6499              $allow_pings    = ( 'open' === $entry['ping_status'] ) ? 1 : 0;
6500  
6501              // Consider future posts as published.
6502              if ( 'future' === $entry['post_status'] ) {
6503                  $entry['post_status'] = 'publish';
6504              }
6505  
6506              // Get post format.
6507              $post_format = get_post_format( $entry['ID'] );
6508              if ( empty( $post_format ) ) {
6509                  $post_format = 'standard';
6510              }
6511  
6512              $recent_posts[] = array(
6513                  'dateCreated'            => $post_date,
6514                  'userid'                 => $entry['post_author'],
6515                  'postid'                 => (string) $entry['ID'],
6516                  'description'            => $post['main'],
6517                  'title'                  => $entry['post_title'],
6518                  'link'                   => $link,
6519                  'permaLink'              => $link,
6520                  // Commented out because no other tool seems to use this.
6521                  // 'content' => $entry['post_content'],
6522                  'categories'             => $categories,
6523                  'mt_excerpt'             => $entry['post_excerpt'],
6524                  'mt_text_more'           => $post['extended'],
6525                  'wp_more_text'           => $post['more_text'],
6526                  'mt_allow_comments'      => $allow_comments,
6527                  'mt_allow_pings'         => $allow_pings,
6528                  'mt_keywords'            => $tagnames,
6529                  'wp_slug'                => $entry['post_name'],
6530                  'wp_password'            => $entry['post_password'],
6531                  'wp_author_id'           => (string) $author->ID,
6532                  'wp_author_display_name' => $author->display_name,
6533                  'date_created_gmt'       => $post_date_gmt,
6534                  'post_status'            => $entry['post_status'],
6535                  'custom_fields'          => $this->get_custom_fields( $entry['ID'] ),
6536                  'wp_post_format'         => $post_format,
6537                  'date_modified'          => $post_modified,
6538                  'date_modified_gmt'      => $post_modified_gmt,
6539                  'sticky'                 => ( 'post' === $entry['post_type'] && is_sticky( $entry['ID'] ) ),
6540                  'wp_post_thumbnail'      => get_post_thumbnail_id( $entry['ID'] ),
6541              );
6542          }
6543  
6544          return $recent_posts;
6545      }
6546  
6547      /**
6548       * Retrieves the list of categories on a given blog.
6549       *
6550       * @since 1.5.0
6551       *
6552       * @param array $args {
6553       *     Method arguments. Note: arguments must be ordered as documented.
6554       *
6555       *     @type int    $0 Blog ID (unused).
6556       *     @type string $1 Username.
6557       *     @type string $2 Password.
6558       * }
6559       * @return array|IXR_Error
6560       */
6561  	public function mw_getCategories( $args ) {
6562          $this->escape( $args );
6563  
6564          $username = $args[1];
6565          $password = $args[2];
6566  
6567          $user = $this->login( $username, $password );
6568          if ( ! $user ) {
6569              return $this->error;
6570          }
6571  
6572          if ( ! current_user_can( 'edit_posts' ) ) {
6573              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
6574          }
6575  
6576          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6577          do_action( 'xmlrpc_call', 'metaWeblog.getCategories', $args, $this );
6578  
6579          $categories_struct = array();
6580  
6581          $cats = get_categories( array( 'get' => 'all' ) );
6582          if ( $cats ) {
6583              foreach ( $cats as $cat ) {
6584                  $struct                        = array();
6585                  $struct['categoryId']          = $cat->term_id;
6586                  $struct['parentId']            = $cat->parent;
6587                  $struct['description']         = $cat->name;
6588                  $struct['categoryDescription'] = $cat->description;
6589                  $struct['categoryName']        = $cat->name;
6590                  $struct['htmlUrl']             = esc_html( get_category_link( $cat->term_id ) );
6591                  $struct['rssUrl']              = esc_html( get_category_feed_link( $cat->term_id, 'rss2' ) );
6592  
6593                  $categories_struct[] = $struct;
6594              }
6595          }
6596  
6597          return $categories_struct;
6598      }
6599  
6600      /**
6601       * Uploads a file, following your settings.
6602       *
6603       * Adapted from a patch by Johann Richard.
6604       *
6605       * @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
6606       *
6607       * @since 1.5.0
6608       *
6609       * @param array $args {
6610       *     Method arguments. Note: top-level arguments must be ordered as documented.
6611       *
6612       *     @type int    $0 Blog ID (unused).
6613       *     @type string $1 Username.
6614       *     @type string $2 Password.
6615       *     @type array  $3 {
6616       *         Data for the file to upload.
6617       *
6618       *         @type string $name    File name. Sanitized with sanitize_file_name().
6619       *         @type string $type    Optional. File MIME type, stored as the attachment's
6620       *                               post MIME type. Default empty string.
6621       *         @type string $bits    Optional. File contents. Default empty string.
6622       *         @type int    $post_id Optional. ID of the post to attach the file to.
6623       *                               Default 0.
6624       *     }
6625       * }
6626       * @return array|IXR_Error
6627       */
6628  	public function mw_newMediaObject( $args ) {
6629          if ( ! $this->minimum_args( $args, 4 ) ) {
6630              return $this->error;
6631          }
6632  
6633          $username = $this->escape( $args[1] );
6634          $password = $this->escape( $args[2] );
6635          $data     = $args[3];
6636  
6637          $user = $this->login( $username, $password );
6638          if ( ! $user ) {
6639              return $this->error;
6640          }
6641  
6642          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6643          do_action( 'xmlrpc_call', 'metaWeblog.newMediaObject', $args, $this );
6644  
6645          if ( ! current_user_can( 'upload_files' ) ) {
6646              $this->error = new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
6647              return $this->error;
6648          }
6649  
6650          if (
6651              ! is_array( $data ) ||
6652              ! is_string( $data['name'] ?? null ) ||
6653              ! is_string( $data['type'] ?? '' ) ||
6654              ! is_string( $data['bits'] ?? '' )
6655          ) {
6656              return new IXR_Error( 400, __( 'Invalid attachment data.' ) );
6657          }
6658  
6659          $name = sanitize_file_name( $data['name'] );
6660  
6661          // A name consisting only of characters the sanitizer strips leaves nothing to write to.
6662          if ( '' === $name ) {
6663              return new IXR_Error( 400, __( 'Invalid attachment data.' ) );
6664          }
6665  
6666          $type = $data['type'] ?? '';
6667          $bits = $data['bits'] ?? '';
6668  
6669          if ( is_multisite() && upload_is_user_over_quota( false ) ) {
6670              $this->error = new IXR_Error(
6671                  401,
6672                  sprintf(
6673                      /* translators: %s: Allowed space allocation. */
6674                      __( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ),
6675                      size_format( get_space_allowed() * MB_IN_BYTES )
6676                  )
6677              );
6678              return $this->error;
6679          }
6680  
6681          /**
6682           * Filters whether to preempt the XML-RPC media upload.
6683           *
6684           * Returning a truthy value will effectively short-circuit the media upload,
6685           * returning that value as a 500 error instead.
6686           *
6687           * @since 2.1.0
6688           *
6689           * @param string|false $error Error message to return instead of uploading, or false to
6690           *                            allow the upload. Default false.
6691           */
6692          $upload_err = apply_filters( 'pre_upload_error', false );
6693          if ( $upload_err ) {
6694              return new IXR_Error( 500, $upload_err );
6695          }
6696  
6697          $upload = wp_upload_bits( $name, null, $bits );
6698          if ( ! empty( $upload['error'] ) ) {
6699              /* translators: 1: File name, 2: Error message. */
6700              $error_string = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
6701              return new IXR_Error( 500, $error_string );
6702          }
6703  
6704          // Construct the attachment array.
6705          $post_id = 0;
6706          if ( ! empty( $data['post_id'] ) ) {
6707              $post_id = (int) $data['post_id'];
6708  
6709              if ( ! current_user_can( 'edit_post', $post_id ) ) {
6710                  return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
6711              }
6712          }
6713  
6714          $attachment = array(
6715              'post_title'     => $name,
6716              'post_content'   => '',
6717              'post_type'      => 'attachment',
6718              'post_parent'    => $post_id,
6719              'post_mime_type' => $type,
6720              'guid'           => $upload['url'],
6721          );
6722  
6723          // Save the data.
6724          $attachment_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
6725          wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) );
6726  
6727          /**
6728           * Fires after a new attachment has been added via the XML-RPC MovableType API.
6729           *
6730           * @since 3.4.0
6731           *
6732           * @param int   $attachment_id ID of the new attachment.
6733           * @param array $args          An array of arguments to add the attachment.
6734           */
6735          do_action( 'xmlrpc_call_success_mw_newMediaObject', $attachment_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
6736  
6737          $struct = $this->_prepare_media_item( get_post( $attachment_id ) );
6738  
6739          // Deprecated values.
6740          $struct['id']   = $struct['attachment_id'];
6741          $struct['file'] = $struct['title'];
6742          $struct['url']  = $struct['link'];
6743  
6744          return $struct;
6745      }
6746  
6747      /*
6748       * MovableType API functions.
6749       * Specs archive on https://web.archive.org/web/20050220091302/http://www.movabletype.org/docs/mtmanual_programmatic.html
6750       */
6751  
6752      /**
6753       * Retrieves the post titles of recent posts.
6754       *
6755       * @since 1.5.0
6756       *
6757       * @param array $args {
6758       *     Method arguments. Note: arguments must be ordered as documented.
6759       *
6760       *     @type int    $0 Blog ID (unused).
6761       *     @type string $1 Username.
6762       *     @type string $2 Password.
6763       *     @type int    $3 Optional. Number of posts.
6764       * }
6765       * @return array|IXR_Error
6766       */
6767  	public function mt_getRecentPostTitles( $args ) {
6768          $this->escape( $args );
6769  
6770          $username = $args[1];
6771          $password = $args[2];
6772          if ( isset( $args[3] ) ) {
6773              $query = array( 'numberposts' => absint( $args[3] ) );
6774          } else {
6775              $query = array();
6776          }
6777  
6778          $user = $this->login( $username, $password );
6779          if ( ! $user ) {
6780              return $this->error;
6781          }
6782  
6783          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6784          do_action( 'xmlrpc_call', 'mt.getRecentPostTitles', $args, $this );
6785  
6786          $posts_list = wp_get_recent_posts( $query );
6787  
6788          if ( ! $posts_list ) {
6789              $this->error = new IXR_Error( 500, __( 'No posts found or an error occurred while retrieving posts.' ) );
6790              return $this->error;
6791          }
6792  
6793          $recent_posts = array();
6794  
6795          foreach ( $posts_list as $entry ) {
6796              if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
6797                  continue;
6798              }
6799  
6800              $post_date     = $this->_convert_date( $entry['post_date'] );
6801              $post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
6802  
6803              $recent_posts[] = array(
6804                  'dateCreated'      => $post_date,
6805                  'userid'           => $entry['post_author'],
6806                  'postid'           => (string) $entry['ID'],
6807                  'title'            => $entry['post_title'],
6808                  'post_status'      => $entry['post_status'],
6809                  'date_created_gmt' => $post_date_gmt,
6810              );
6811          }
6812  
6813          return $recent_posts;
6814      }
6815  
6816      /**
6817       * Retrieves the list of all categories on a blog.
6818       *
6819       * @since 1.5.0
6820       *
6821       * @param array $args {
6822       *     Method arguments. Note: arguments must be ordered as documented.
6823       *
6824       *     @type int    $0 Blog ID (unused).
6825       *     @type string $1 Username.
6826       *     @type string $2 Password.
6827       * }
6828       * @return array|IXR_Error
6829       */
6830  	public function mt_getCategoryList( $args ) {
6831          $this->escape( $args );
6832  
6833          $username = $args[1];
6834          $password = $args[2];
6835  
6836          $user = $this->login( $username, $password );
6837          if ( ! $user ) {
6838              return $this->error;
6839          }
6840  
6841          if ( ! current_user_can( 'edit_posts' ) ) {
6842              return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
6843          }
6844  
6845          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6846          do_action( 'xmlrpc_call', 'mt.getCategoryList', $args, $this );
6847  
6848          $categories_struct = array();
6849  
6850          $cats = get_categories(
6851              array(
6852                  'hide_empty'   => 0,
6853                  'hierarchical' => 0,
6854              )
6855          );
6856          if ( $cats ) {
6857              foreach ( $cats as $cat ) {
6858                  $struct                 = array();
6859                  $struct['categoryId']   = $cat->term_id;
6860                  $struct['categoryName'] = $cat->name;
6861  
6862                  $categories_struct[] = $struct;
6863              }
6864          }
6865  
6866          return $categories_struct;
6867      }
6868  
6869      /**
6870       * Retrieves post categories.
6871       *
6872       * @since 1.5.0
6873       *
6874       * @param array $args {
6875       *     Method arguments. Note: arguments must be ordered as documented.
6876       *
6877       *     @type int    $0 Post ID.
6878       *     @type string $1 Username.
6879       *     @type string $2 Password.
6880       * }
6881       * @return array|IXR_Error
6882       */
6883  	public function mt_getPostCategories( $args ) {
6884          $this->escape( $args );
6885  
6886          $post_id  = (int) $args[0];
6887          $username = $args[1];
6888          $password = $args[2];
6889  
6890          $user = $this->login( $username, $password );
6891          if ( ! $user ) {
6892              return $this->error;
6893          }
6894  
6895          if ( ! get_post( $post_id ) ) {
6896              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
6897          }
6898  
6899          if ( ! current_user_can( 'edit_post', $post_id ) ) {
6900              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
6901          }
6902  
6903          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6904          do_action( 'xmlrpc_call', 'mt.getPostCategories', $args, $this );
6905  
6906          $categories = array();
6907          $cat_ids    = wp_get_post_categories( (int) $post_id );
6908          // First listed category will be the primary category.
6909          $is_primary = true;
6910          foreach ( $cat_ids as $cat_id ) {
6911              $categories[] = array(
6912                  'categoryName' => get_cat_name( $cat_id ),
6913                  'categoryId'   => (string) $cat_id,
6914                  'isPrimary'    => $is_primary,
6915              );
6916              $is_primary   = false;
6917          }
6918  
6919          return $categories;
6920      }
6921  
6922      /**
6923       * Sets categories for a post.
6924       *
6925       * @since 1.5.0
6926       *
6927       * @param array $args {
6928       *     Method arguments. Note: arguments must be ordered as documented.
6929       *
6930       *     @type int    $0 Post ID.
6931       *     @type string $1 Username.
6932       *     @type string $2 Password.
6933       *     @type array  $3 Categories.
6934       * }
6935       * @return true|IXR_Error True on success.
6936       */
6937  	public function mt_setPostCategories( $args ) {
6938          $this->escape( $args );
6939  
6940          $post_id    = (int) $args[0];
6941          $username   = $args[1];
6942          $password   = $args[2];
6943          $categories = $args[3];
6944  
6945          $user = $this->login( $username, $password );
6946          if ( ! $user ) {
6947              return $this->error;
6948          }
6949  
6950          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6951          do_action( 'xmlrpc_call', 'mt.setPostCategories', $args, $this );
6952  
6953          if ( ! get_post( $post_id ) ) {
6954              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
6955          }
6956  
6957          if ( ! current_user_can( 'edit_post', $post_id ) ) {
6958              return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
6959          }
6960  
6961          $cat_ids = array();
6962          foreach ( $categories as $cat ) {
6963              $cat_ids[] = $cat['categoryId'];
6964          }
6965  
6966          wp_set_post_categories( $post_id, $cat_ids );
6967  
6968          return true;
6969      }
6970  
6971      /**
6972       * Retrieves an array of methods supported by this server.
6973       *
6974       * @since 1.5.0
6975       *
6976       * @return array
6977       */
6978  	public function mt_supportedMethods() {
6979          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6980          do_action( 'xmlrpc_call', 'mt.supportedMethods', array(), $this );
6981  
6982          return array_keys( $this->methods );
6983      }
6984  
6985      /**
6986       * Retrieves an empty array because we don't support per-post text filters.
6987       *
6988       * @since 1.5.0
6989       */
6990  	public function mt_supportedTextFilters() {
6991          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6992          do_action( 'xmlrpc_call', 'mt.supportedTextFilters', array(), $this );
6993  
6994          /**
6995           * Filters the MoveableType text filters list for XML-RPC.
6996           *
6997           * @since 2.2.0
6998           *
6999           * @param array $filters An array of text filters.
7000           */
7001          return apply_filters( 'xmlrpc_text_filters', array() );
7002      }
7003  
7004      /**
7005       * Retrieves trackbacks sent to a given post.
7006       *
7007       * @since 1.5.0
7008       *
7009       * @global wpdb $wpdb WordPress database abstraction object.
7010       *
7011       * @param int $post_id
7012       * @return array|IXR_Error
7013       */
7014  	public function mt_getTrackbackPings( $post_id ) {
7015          global $wpdb;
7016  
7017          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
7018          do_action( 'xmlrpc_call', 'mt.getTrackbackPings', $post_id, $this );
7019  
7020          $actual_post = get_post( $post_id, ARRAY_A );
7021  
7022          if ( ! $actual_post ) {
7023              return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
7024          }
7025  
7026          $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 ) );
7027  
7028          if ( ! $comments ) {
7029              return array();
7030          }
7031  
7032          $trackback_pings = array();
7033          foreach ( $comments as $comment ) {
7034              if ( 'trackback' === $comment->comment_type ) {
7035                  $content           = $comment->comment_content;
7036                  $title             = substr( $content, 8, ( strpos( $content, '</strong>' ) - 8 ) );
7037                  $trackback_pings[] = array(
7038                      'pingTitle' => $title,
7039                      'pingURL'   => $comment->comment_author_url,
7040                      'pingIP'    => $comment->comment_author_IP,
7041                  );
7042              }
7043          }
7044  
7045          return $trackback_pings;
7046      }
7047  
7048      /**
7049       * Sets a post's publish status to 'publish'.
7050       *
7051       * @since 1.5.0
7052       *
7053       * @param array $args {
7054       *     Method arguments. Note: arguments must be ordered as documented.
7055       *
7056       *     @type int    $0 Post ID.
7057       *     @type string $1 Username.
7058       *     @type string $2 Password.
7059       * }
7060       * @return int|IXR_Error
7061       */
7062  	public function mt_publishPost( $args ) {
7063          $this->escape( $args );
7064  
7065          $post_id  = (int) $args[0];
7066          $username = $args[1];
7067          $password = $args[2];
7068  
7069          $user = $this->login( $username, $password );
7070          if ( ! $user ) {
7071              return $this->error;
7072          }
7073  
7074          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
7075          do_action( 'xmlrpc_call', 'mt.publishPost', $args, $this );
7076  
7077          $postdata = get_post( $post_id, ARRAY_A );
7078          if ( ! $postdata ) {
7079              return new IXR_Error( 404, __( 'Invalid post ID.' ) );
7080          }
7081  
7082          if ( ! current_user_can( 'publish_posts' ) || ! current_user_can( 'edit_post', $post_id ) ) {
7083              return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
7084          }
7085  
7086          $postdata['post_status'] = 'publish';
7087  
7088          // Retain old categories.
7089          $postdata['post_category'] = wp_get_post_categories( $post_id );
7090          $this->escape( $postdata );
7091  
7092          return wp_update_post( $postdata );
7093      }
7094  
7095      /*
7096       * Pingback functions.
7097       * Specs on www.hixie.ch/specs/pingback/pingback
7098       */
7099  
7100      /**
7101       * Retrieves a pingback and registers it.
7102       *
7103       * @since 1.5.0
7104       *
7105       * @global wpdb $wpdb WordPress database abstraction object.
7106       *
7107       * @param array $args {
7108       *     Method arguments. Note: arguments must be ordered as documented.
7109       *
7110       *     @type string $0 URL of page linked from.
7111       *     @type string $1 URL of page linked to.
7112       * }
7113       * @return string|IXR_Error
7114       */
7115  	public function pingback_ping( $args ) {
7116          global $wpdb;
7117  
7118          /*
7119           * Checked before the `xmlrpc_call` action and any database or network work, so repeated
7120           * calls in a multicall cost nothing, including in plugins that check each pingback.
7121           */
7122          if ( $this->pingback_processed ) {
7123              return $this->pingback_error( 49, __( 'Only one pingback can be processed per request.' ) );
7124          }
7125  
7126          $this->pingback_processed = true;
7127  
7128          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
7129          do_action( 'xmlrpc_call', 'pingback.ping', $args, $this );
7130  
7131          $this->escape( $args );
7132  
7133          $pagelinkedfrom = str_replace( '&amp;', '&', $args[0] );
7134          $pagelinkedto   = str_replace( '&amp;', '&', $args[1] );
7135          $pagelinkedto   = str_replace( '&', '&amp;', $pagelinkedto );
7136  
7137          /**
7138           * Filters the pingback source URI.
7139           *
7140           * @since 3.6.0
7141           *
7142           * @param string $pagelinkedfrom URI of the page linked from.
7143           * @param string $pagelinkedto   URI of the page linked to.
7144           */
7145          $pagelinkedfrom = apply_filters( 'pingback_ping_source_uri', $pagelinkedfrom, $pagelinkedto );
7146  
7147          if ( ! $pagelinkedfrom ) {
7148              return $this->pingback_error( 0, __( 'A valid URL was not provided.' ) );
7149          }
7150  
7151          // Check if the page linked to is on our site.
7152          $pos1 = strpos( $pagelinkedto, str_replace( array( 'http://www.', 'http://', 'https://www.', 'https://' ), '', get_option( 'home' ) ) );
7153          if ( ! $pos1 ) {
7154              return $this->pingback_error( 0, __( 'Is there no link to us?' ) );
7155          }
7156  
7157          /*
7158           * Let's find which post is linked to.
7159           * FIXME: Does url_to_postid() cover all these cases already?
7160           * If so, then let's use it and drop the old code.
7161           */
7162          $urltest = parse_url( $pagelinkedto );
7163          $post_id = url_to_postid( $pagelinkedto );
7164  
7165          if ( $post_id ) {
7166              // $way
7167          } elseif ( isset( $urltest['path'] ) && preg_match( '#p/[0-9]{1,}#', $urltest['path'], $match ) ) {
7168              // The path defines the post_ID (archives/p/XXXX).
7169              $blah    = explode( '/', $match[0] );
7170              $post_id = (int) $blah[1];
7171          } elseif ( isset( $urltest['query'] ) && preg_match( '#p=[0-9]{1,}#', $urltest['query'], $match ) ) {
7172              // The query string defines the post_ID (?p=XXXX).
7173              $blah    = explode( '=', $match[0] );
7174              $post_id = (int) $blah[1];
7175          } elseif ( isset( $urltest['fragment'] ) ) {
7176              // An #anchor is there, it's either...
7177              if ( (int) $urltest['fragment'] ) {
7178                  // ...an integer #XXXX (simplest case),
7179                  $post_id = (int) $urltest['fragment'];
7180              } elseif ( preg_match( '/post-[0-9]+/', $urltest['fragment'] ) ) {
7181                  // ...a post ID in the form 'post-###',
7182                  $post_id = preg_replace( '/[^0-9]+/', '', $urltest['fragment'] );
7183              } elseif ( is_string( $urltest['fragment'] ) ) {
7184                  // ...or a string #title, a little more complicated.
7185                  $title   = preg_replace( '/[^a-z0-9]/i', '.', $urltest['fragment'] );
7186                  $sql     = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title );
7187                  $post_id = $wpdb->get_var( $sql );
7188                  if ( ! $post_id ) {
7189                      // Returning unknown error '0' is better than die()'ing.
7190                      return $this->pingback_error( 0, '' );
7191                  }
7192              }
7193          } else {
7194              // TODO: Attempt to extract a post ID from the given URL.
7195              return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
7196          }
7197  
7198          $post_id = (int) $post_id;
7199          $post    = get_post( $post_id );
7200  
7201          if ( ! $post ) { // Post not found.
7202              return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
7203          }
7204  
7205          if ( url_to_postid( $pagelinkedfrom ) === $post_id ) {
7206              return $this->pingback_error( 0, __( 'The source URL and the target URL cannot both point to the same resource.' ) );
7207          }
7208  
7209          // Check if pings are on.
7210          if ( ! pings_open( $post ) ) {
7211              return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
7212          }
7213  
7214          // Let's check that the remote site didn't already pingback this entry.
7215          if ( $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_id, $pagelinkedfrom ) ) ) {
7216              return $this->pingback_error( 48, __( 'The pingback has already been registered.' ) );
7217          }
7218  
7219          /*
7220           * The remote site may have sent the pingback before it finished publishing its own content
7221           * containing this pingback URL. If that happens then it won't be immediately possible to fetch
7222           * the pinging post; adding a small delay reduces the likelihood of this happening.
7223           *
7224           * While there are more robust methods than calling `sleep()` here (because `sleep()` merely
7225           * mitigates the risk of requesting the remote post before it's available), this is effective
7226           * enough for most cases and avoids introducing more complexity into this code.
7227           *
7228           * One way to improve the reliability of this code might be to add failure-handling to the remote
7229           * fetch and retry up to a set number of times if it receives a 404. This could also handle 401 and
7230           * 403 responses to differentiate the "does not exist" failure from the "may not access" failure.
7231           */
7232          sleep( 1 );
7233  
7234          $remote_ip = preg_replace( '/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR'] );
7235  
7236          /** This filter is documented in wp-includes/class-wp-http.php */
7237          $user_agent = apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $pagelinkedfrom );
7238  
7239          // Let's check the remote site.
7240          $http_api_args = array(
7241              'timeout'             => 10,
7242              'redirection'         => 0,
7243              'limit_response_size' => 153600, // 150 KB
7244              'user-agent'          => "$user_agent; verifying pingback from $remote_ip",
7245              'headers'             => array(
7246                  'X-Pingback-Forwarded-For' => $remote_ip,
7247              ),
7248          );
7249  
7250          $request                = wp_safe_remote_get( $pagelinkedfrom, $http_api_args );
7251          $remote_source          = wp_remote_retrieve_body( $request );
7252          $remote_source_original = $remote_source;
7253  
7254          if ( ! $remote_source ) {
7255              return $this->pingback_error( 16, __( 'The source URL does not exist.' ) );
7256          }
7257  
7258          /**
7259           * Filters the pingback remote source.
7260           *
7261           * @since 2.5.0
7262           *
7263           * @param string $remote_source Response source for the page linked from.
7264           * @param string $pagelinkedto  URL of the page linked to.
7265           */
7266          $remote_source = apply_filters( 'pre_remote_source', $remote_source, $pagelinkedto );
7267  
7268          // Work around bug in strip_tags():
7269          $remote_source = str_replace( '<!DOC', '<DOC', $remote_source );
7270          $remote_source = preg_replace( '/[\r\n\t ]+/', ' ', $remote_source ); // normalize spaces
7271          $remote_source = preg_replace( '/<\/*(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/', "\n\n", $remote_source );
7272  
7273          preg_match( '|<title>([^<]*?)</title>|is', $remote_source, $matchtitle );
7274          $title = $matchtitle[1] ?? '';
7275          if ( empty( $title ) ) {
7276              return $this->pingback_error( 32, __( 'A title on that page cannot be found.' ) );
7277          }
7278  
7279          // Remove all script and style tags including their content.
7280          $remote_source = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $remote_source );
7281          // Just keep the tag we need.
7282          $remote_source = strip_tags( $remote_source, '<a>' );
7283  
7284          $p = explode( "\n\n", $remote_source );
7285  
7286          $preg_target = preg_quote( $pagelinkedto, '|' );
7287  
7288          foreach ( $p as $para ) {
7289              if ( str_contains( $para, $pagelinkedto ) ) { // It exists, but is it a link?
7290                  preg_match( '|<a[^>]+?' . $preg_target . '[^>]*>([^>]+?)</a>|', $para, $context );
7291  
7292                  // If the URL isn't in a link context, keep looking.
7293                  if ( empty( $context ) ) {
7294                      continue;
7295                  }
7296  
7297                  /*
7298                   * We're going to use this fake tag to mark the context in a bit.
7299                   * The marker is needed in case the link text appears more than once in the paragraph.
7300                   */
7301                  $excerpt = preg_replace( '|\</?wpcontext\>|', '', $para );
7302  
7303                  // prevent really long link text
7304                  if ( strlen( $context[1] ) > 100 ) {
7305                      $context[1] = substr( $context[1], 0, 100 ) . '&#8230;';
7306                  }
7307  
7308                  $marker      = '<wpcontext>' . $context[1] . '</wpcontext>';  // Set up our marker.
7309                  $excerpt     = str_replace( $context[0], $marker, $excerpt ); // Swap out the link for our marker.
7310                  $excerpt     = strip_tags( $excerpt, '<wpcontext>' );         // Strip all tags but our context marker.
7311                  $excerpt     = trim( $excerpt );
7312                  $preg_marker = preg_quote( $marker, '|' );
7313                  $excerpt     = preg_replace( "|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt );
7314                  $excerpt     = strip_tags( $excerpt ); // YES, again, to remove the marker wrapper.
7315                  break;
7316              }
7317          }
7318  
7319          if ( empty( $context ) ) { // Link to target not found.
7320              return $this->pingback_error( 17, __( 'The source URL does not contain a link to the target URL, and so cannot be used as a source.' ) );
7321          }
7322  
7323          $pagelinkedfrom = str_replace( '&', '&amp;', $pagelinkedfrom );
7324  
7325          $context        = '[&#8230;] ' . esc_html( $excerpt ) . ' [&#8230;]';
7326          $pagelinkedfrom = $this->escape( $pagelinkedfrom );
7327  
7328          $comment_post_id      = (int) $post_id;
7329          $comment_author       = $title;
7330          $comment_author_email = '';
7331          $this->escape( $comment_author );
7332          $comment_author_url = $pagelinkedfrom;
7333          $comment_content    = $context;
7334          $this->escape( $comment_content );
7335          $comment_type = 'pingback';
7336  
7337          $commentdata = array(
7338              'comment_post_ID' => $comment_post_id,
7339          );
7340  
7341          $commentdata += compact(
7342              'comment_author',
7343              'comment_author_url',
7344              'comment_author_email',
7345              'comment_content',
7346              'comment_type',
7347              'remote_source',
7348              'remote_source_original'
7349          );
7350  
7351          $comment_id = wp_new_comment( $commentdata );
7352  
7353          if ( is_wp_error( $comment_id ) ) {
7354              return $this->pingback_error( 0, $comment_id->get_error_message() );
7355          }
7356  
7357          /**
7358           * Fires after a post pingback has been sent.
7359           *
7360           * @since 0.71
7361           *
7362           * @param int $comment_id Comment ID.
7363           */
7364          do_action( 'pingback_post', $comment_id );
7365  
7366          /* translators: 1: URL of the page linked from, 2: URL of the page linked to. */
7367          return sprintf( __( 'Pingback from %1$s to %2$s registered. Keep the web talking! :-)' ), $pagelinkedfrom, $pagelinkedto );
7368      }
7369  
7370      /**
7371       * Retrieves an array of URLs that pingbacked the given URL.
7372       *
7373       * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
7374       *
7375       * @since 1.5.0
7376       *
7377       * @global wpdb $wpdb WordPress database abstraction object.
7378       *
7379       * @param string $url
7380       * @return array|IXR_Error
7381       */
7382  	public function pingback_extensions_getPingbacks( $url ) {
7383          global $wpdb;
7384  
7385          /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
7386          do_action( 'xmlrpc_call', 'pingback.extensions.getPingbacks', $url, $this );
7387  
7388          $url = $this->escape( $url );
7389  
7390          $post_id = url_to_postid( $url );
7391          if ( ! $post_id ) {
7392              // We aren't sure that the resource is available and/or pingback enabled.
7393              return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
7394          }
7395  
7396          $actual_post = get_post( $post_id, ARRAY_A );
7397  
7398          if ( ! $actual_post ) {
7399              // No such post = resource not found.
7400              return $this->pingback_error( 32, __( 'The specified target URL does not exist.' ) );
7401          }
7402  
7403          $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 ) );
7404  
7405          if ( ! $comments ) {
7406              return array();
7407          }
7408  
7409          $pingbacks = array();
7410          foreach ( $comments as $comment ) {
7411              if ( 'pingback' === $comment->comment_type ) {
7412                  $pingbacks[] = $comment->comment_author_url;
7413              }
7414          }
7415  
7416          return $pingbacks;
7417      }
7418  
7419      /**
7420       * Sends a pingback error based on the given error code and message.
7421       *
7422       * @since 3.6.0
7423       *
7424       * @param int    $code    Error code.
7425       * @param string $message Error message.
7426       * @return IXR_Error Error object.
7427       */
7428  	protected function pingback_error( $code, $message ) {
7429          /**
7430           * Filters the XML-RPC pingback error return.
7431           *
7432           * @since 3.5.1
7433           *
7434           * @param IXR_Error $error An IXR_Error object containing the error code and message.
7435           */
7436          return apply_filters( 'xmlrpc_pingback_error', new IXR_Error( $code, $message ) );
7437      }
7438  }


Generated : Fri Nov 27 08:20:01 2026 Cross-referenced by PHPXref