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