]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-xmlrpc-server.php
WordPress 4.7-scripts
[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         public function initialise_blog_option_info() {
409                 $this->blog_options = array(
410                         // Read only options
411                         'software_name'     => array(
412                                 'desc'          => __( 'Software Name' ),
413                                 'readonly'      => true,
414                                 'value'         => 'WordPress'
415                         ),
416                         'software_version'  => array(
417                                 'desc'          => __( 'Software Version' ),
418                                 'readonly'      => true,
419                                 'value'         => get_bloginfo( 'version' )
420                         ),
421                         'blog_url'          => array(
422                                 'desc'          => __( 'WordPress Address (URL)' ),
423                                 'readonly'      => true,
424                                 'option'        => 'siteurl'
425                         ),
426                         'home_url'          => array(
427                                 'desc'          => __( 'Site Address (URL)' ),
428                                 'readonly'      => true,
429                                 'option'        => 'home'
430                         ),
431                         'login_url'          => array(
432                                 'desc'          => __( 'Login Address (URL)' ),
433                                 'readonly'      => true,
434                                 'value'         => wp_login_url( )
435                         ),
436                         'admin_url'          => array(
437                                 'desc'          => __( 'The URL to the admin area' ),
438                                 'readonly'      => true,
439                                 'value'         => get_admin_url( )
440                         ),
441                         'image_default_link_type' => array(
442                                 'desc'          => __( 'Image default link type' ),
443                                 'readonly'      => true,
444                                 'option'        => 'image_default_link_type'
445                         ),
446                         'image_default_size' => array(
447                                 'desc'          => __( 'Image default size' ),
448                                 'readonly'      => true,
449                                 'option'        => 'image_default_size'
450                         ),
451                         'image_default_align' => array(
452                                 'desc'          => __( 'Image default align' ),
453                                 'readonly'      => true,
454                                 'option'        => 'image_default_align'
455                         ),
456                         'template'          => array(
457                                 'desc'          => __( 'Template' ),
458                                 'readonly'      => true,
459                                 'option'        => 'template'
460                         ),
461                         'stylesheet'        => array(
462                                 'desc'          => __( 'Stylesheet' ),
463                                 'readonly'      => true,
464                                 'option'        => 'stylesheet'
465                         ),
466                         'post_thumbnail'    => array(
467                                 'desc'          => __('Post Thumbnail'),
468                                 'readonly'      => true,
469                                 'value'         => current_theme_supports( 'post-thumbnails' )
470                         ),
471
472                         // Updatable options
473                         'time_zone'         => array(
474                                 'desc'          => __( 'Time Zone' ),
475                                 'readonly'      => false,
476                                 'option'        => 'gmt_offset'
477                         ),
478                         'blog_title'        => array(
479                                 'desc'          => __( 'Site Title' ),
480                                 'readonly'      => false,
481                                 'option'        => 'blogname'
482                         ),
483                         'blog_tagline'      => array(
484                                 'desc'          => __( 'Site Tagline' ),
485                                 'readonly'      => false,
486                                 'option'        => 'blogdescription'
487                         ),
488                         'date_format'       => array(
489                                 'desc'          => __( 'Date Format' ),
490                                 'readonly'      => false,
491                                 'option'        => 'date_format'
492                         ),
493                         'time_format'       => array(
494                                 'desc'          => __( 'Time Format' ),
495                                 'readonly'      => false,
496                                 'option'        => 'time_format'
497                         ),
498                         'users_can_register' => array(
499                                 'desc'          => __( 'Allow new users to sign up' ),
500                                 'readonly'      => false,
501                                 'option'        => 'users_can_register'
502                         ),
503                         'thumbnail_size_w'  => array(
504                                 'desc'          => __( 'Thumbnail Width' ),
505                                 'readonly'      => false,
506                                 'option'        => 'thumbnail_size_w'
507                         ),
508                         'thumbnail_size_h'  => array(
509                                 'desc'          => __( 'Thumbnail Height' ),
510                                 'readonly'      => false,
511                                 'option'        => 'thumbnail_size_h'
512                         ),
513                         'thumbnail_crop'    => array(
514                                 'desc'          => __( 'Crop thumbnail to exact dimensions' ),
515                                 'readonly'      => false,
516                                 'option'        => 'thumbnail_crop'
517                         ),
518                         'medium_size_w'     => array(
519                                 'desc'          => __( 'Medium size image width' ),
520                                 'readonly'      => false,
521                                 'option'        => 'medium_size_w'
522                         ),
523                         'medium_size_h'     => array(
524                                 'desc'          => __( 'Medium size image height' ),
525                                 'readonly'      => false,
526                                 'option'        => 'medium_size_h'
527                         ),
528                         'medium_large_size_w'   => array(
529                                 'desc'          => __( 'Medium-Large size image width' ),
530                                 'readonly'      => false,
531                                 'option'        => 'medium_large_size_w'
532                         ),
533                         'medium_large_size_h'   => array(
534                                 'desc'          => __( 'Medium-Large size image height' ),
535                                 'readonly'      => false,
536                                 'option'        => 'medium_large_size_h'
537                         ),
538                         'large_size_w'      => array(
539                                 'desc'          => __( 'Large size image width' ),
540                                 'readonly'      => false,
541                                 'option'        => 'large_size_w'
542                         ),
543                         'large_size_h'      => array(
544                                 'desc'          => __( 'Large size image height' ),
545                                 'readonly'      => false,
546                                 'option'        => 'large_size_h'
547                         ),
548                         'default_comment_status' => array(
549                                 'desc'          => __( 'Allow people to post comments on new articles' ),
550                                 'readonly'      => false,
551                                 'option'        => 'default_comment_status'
552                         ),
553                         'default_ping_status' => array(
554                                 'desc'          => __( 'Allow link notifications from other blogs (pingbacks and trackbacks) on new articles' ),
555                                 'readonly'      => false,
556                                 'option'        => 'default_ping_status'
557                         )
558                 );
559
560                 /**
561                  * Filters the XML-RPC blog options property.
562                  *
563                  * @since 2.6.0
564                  *
565                  * @param array $blog_options An array of XML-RPC blog options.
566                  */
567                 $this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options );
568         }
569
570         /**
571          * Retrieve the blogs of the user.
572          *
573          * @since 2.6.0
574          *
575          * @param array $args {
576          *     Method arguments. Note: arguments must be ordered as documented.
577          *
578          *     @type string $username Username.
579          *     @type string $password Password.
580          * }
581          * @return array|IXR_Error Array contains:
582          *  - 'isAdmin'
583          *  - 'isPrimary' - whether the blog is the user's primary blog
584          *  - 'url'
585          *  - 'blogid'
586          *  - 'blogName'
587          *  - 'xmlrpc' - url of xmlrpc endpoint
588          */
589         public function wp_getUsersBlogs( $args ) {
590                 if ( ! $this->minimum_args( $args, 2 ) ) {
591                         return $this->error;
592                 }
593
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_network_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 WP_Taxonomy $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 make posts sticky.' ) );
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.' ) );
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, __( 'Invalid post type.' ) );
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->edit_terms ) ) {
1881                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to create terms in this taxonomy.' ) );
1882                 }
1883
1884                 $taxonomy = (array) $taxonomy;
1885
1886                 // hold the data of the term
1887                 $term_data = array();
1888
1889                 $term_data['name'] = trim( $content_struct['name'] );
1890                 if ( empty( $term_data['name'] ) )
1891                         return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
1892
1893                 if ( isset( $content_struct['parent'] ) ) {
1894                         if ( ! $taxonomy['hierarchical'] )
1895                                 return new IXR_Error( 403, __( 'This taxonomy is not hierarchical.' ) );
1896
1897                         $parent_term_id = (int) $content_struct['parent'];
1898                         $parent_term = get_term( $parent_term_id , $taxonomy['name'] );
1899
1900                         if ( is_wp_error( $parent_term ) )
1901                                 return new IXR_Error( 500, $parent_term->get_error_message() );
1902
1903                         if ( ! $parent_term )
1904                                 return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
1905
1906                         $term_data['parent'] = $content_struct['parent'];
1907                 }
1908
1909                 if ( isset( $content_struct['description'] ) )
1910                         $term_data['description'] = $content_struct['description'];
1911
1912                 if ( isset( $content_struct['slug'] ) )
1913                         $term_data['slug'] = $content_struct['slug'];
1914
1915                 $term = wp_insert_term( $term_data['name'] , $taxonomy['name'] , $term_data );
1916
1917                 if ( is_wp_error( $term ) )
1918                         return new IXR_Error( 500, $term->get_error_message() );
1919
1920                 if ( ! $term )
1921                         return new IXR_Error( 500, __( 'Sorry, your term could not be created.' ) );
1922
1923                 return strval( $term['term_id'] );
1924         }
1925
1926         /**
1927          * Edit a term.
1928          *
1929          * @since 3.4.0
1930          *
1931          * @see wp_update_term()
1932          *
1933          * @param array $args {
1934          *     Method arguments. Note: arguments must be ordered as documented.
1935          *
1936          *     @type int    $blog_id        Blog ID (unused).
1937          *     @type string $username       Username.
1938          *     @type string $password       Password.
1939          *     @type int    $term_id        Term ID.
1940          *     @type array  $content_struct Content struct for editing a term. The struct must contain the
1941          *                                  term ''taxonomy'. Optional accepted values include 'name', 'parent',
1942          *                                  'description', and 'slug'.
1943          * }
1944          * @return true|IXR_Error True on success, IXR_Error instance on failure.
1945          */
1946         public function wp_editTerm( $args ) {
1947                 if ( ! $this->minimum_args( $args, 5 ) )
1948                         return $this->error;
1949
1950                 $this->escape( $args );
1951
1952                 $username       = $args[1];
1953                 $password       = $args[2];
1954                 $term_id        = (int) $args[3];
1955                 $content_struct = $args[4];
1956
1957                 if ( ! $user = $this->login( $username, $password ) )
1958                         return $this->error;
1959
1960                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
1961                 do_action( 'xmlrpc_call', 'wp.editTerm' );
1962
1963                 if ( ! taxonomy_exists( $content_struct['taxonomy'] ) )
1964                         return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
1965
1966                 $taxonomy = get_taxonomy( $content_struct['taxonomy'] );
1967
1968                 $taxonomy = (array) $taxonomy;
1969
1970                 // hold the data of the term
1971                 $term_data = array();
1972
1973                 $term = get_term( $term_id , $content_struct['taxonomy'] );
1974
1975                 if ( is_wp_error( $term ) )
1976                         return new IXR_Error( 500, $term->get_error_message() );
1977
1978                 if ( ! $term )
1979                         return new IXR_Error( 404, __( 'Invalid term ID.' ) );
1980
1981                 if ( ! current_user_can( 'edit_term', $term_id ) ) {
1982                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this term.' ) );
1983                 }
1984
1985                 if ( isset( $content_struct['name'] ) ) {
1986                         $term_data['name'] = trim( $content_struct['name'] );
1987
1988                         if ( empty( $term_data['name'] ) )
1989                                 return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
1990                 }
1991
1992                 if ( ! empty( $content_struct['parent'] ) ) {
1993                         if ( ! $taxonomy['hierarchical'] )
1994                                 return new IXR_Error( 403, __( "This taxonomy is not hierarchical so you can't set a parent." ) );
1995
1996                         $parent_term_id = (int) $content_struct['parent'];
1997                         $parent_term = get_term( $parent_term_id , $taxonomy['name'] );
1998
1999                         if ( is_wp_error( $parent_term ) )
2000                                 return new IXR_Error( 500, $parent_term->get_error_message() );
2001
2002                         if ( ! $parent_term )
2003                                 return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
2004
2005                         $term_data['parent'] = $content_struct['parent'];
2006                 }
2007
2008                 if ( isset( $content_struct['description'] ) )
2009                         $term_data['description'] = $content_struct['description'];
2010
2011                 if ( isset( $content_struct['slug'] ) )
2012                         $term_data['slug'] = $content_struct['slug'];
2013
2014                 $term = wp_update_term( $term_id , $taxonomy['name'] , $term_data );
2015
2016                 if ( is_wp_error( $term ) )
2017                         return new IXR_Error( 500, $term->get_error_message() );
2018
2019                 if ( ! $term )
2020                         return new IXR_Error( 500, __( 'Sorry, editing the term failed.' ) );
2021
2022                 return true;
2023         }
2024
2025         /**
2026          * Delete a term.
2027          *
2028          * @since 3.4.0
2029          *
2030          * @see wp_delete_term()
2031          *
2032          * @param array  $args {
2033          *     Method arguments. Note: arguments must be ordered as documented.
2034          *
2035          *     @type int    $blog_id      Blog ID (unused).
2036          *     @type string $username     Username.
2037          *     @type string $password     Password.
2038          *     @type string $taxnomy_name Taxonomy name.
2039          *     @type int    $term_id      Term ID.
2040          * }
2041          * @return bool|IXR_Error True on success, IXR_Error instance on failure.
2042          */
2043         public function wp_deleteTerm( $args ) {
2044                 if ( ! $this->minimum_args( $args, 5 ) )
2045                         return $this->error;
2046
2047                 $this->escape( $args );
2048
2049                 $username           = $args[1];
2050                 $password           = $args[2];
2051                 $taxonomy           = $args[3];
2052                 $term_id            = (int) $args[4];
2053
2054                 if ( ! $user = $this->login( $username, $password ) )
2055                         return $this->error;
2056
2057                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2058                 do_action( 'xmlrpc_call', 'wp.deleteTerm' );
2059
2060                 if ( ! taxonomy_exists( $taxonomy ) )
2061                         return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2062
2063                 $taxonomy = get_taxonomy( $taxonomy );
2064                 $term = get_term( $term_id, $taxonomy->name );
2065
2066                 if ( is_wp_error( $term ) )
2067                         return new IXR_Error( 500, $term->get_error_message() );
2068
2069                 if ( ! $term )
2070                         return new IXR_Error( 404, __( 'Invalid term ID.' ) );
2071
2072                 if ( ! current_user_can( 'delete_term', $term_id ) ) {
2073                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this term.' ) );
2074                 }
2075
2076                 $result = wp_delete_term( $term_id, $taxonomy->name );
2077
2078                 if ( is_wp_error( $result ) )
2079                         return new IXR_Error( 500, $term->get_error_message() );
2080
2081                 if ( ! $result )
2082                         return new IXR_Error( 500, __( 'Sorry, deleting the term failed.' ) );
2083
2084                 return $result;
2085         }
2086
2087         /**
2088          * Retrieve a term.
2089          *
2090          * @since 3.4.0
2091          *
2092          * @see get_term()
2093          *
2094          * @param array  $args {
2095          *     Method arguments. Note: arguments must be ordered as documented.
2096          *
2097          *     @type int    $blog_id  Blog ID (unused).
2098          *     @type string $username Username.
2099          *     @type string $password Password.
2100          *     @type string $taxnomy  Taxonomy name.
2101          *     @type string $term_id  Term ID.
2102          * }
2103          * @return array|IXR_Error IXR_Error on failure, array on success, containing:
2104          *  - 'term_id'
2105          *  - 'name'
2106          *  - 'slug'
2107          *  - 'term_group'
2108          *  - 'term_taxonomy_id'
2109          *  - 'taxonomy'
2110          *  - 'description'
2111          *  - 'parent'
2112          *  - 'count'
2113          */
2114         public function wp_getTerm( $args ) {
2115                 if ( ! $this->minimum_args( $args, 5 ) )
2116                         return $this->error;
2117
2118                 $this->escape( $args );
2119
2120                 $username           = $args[1];
2121                 $password           = $args[2];
2122                 $taxonomy           = $args[3];
2123                 $term_id            = (int) $args[4];
2124
2125                 if ( ! $user = $this->login( $username, $password ) )
2126                         return $this->error;
2127
2128                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2129                 do_action( 'xmlrpc_call', 'wp.getTerm' );
2130
2131                 if ( ! taxonomy_exists( $taxonomy ) )
2132                         return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2133
2134                 $taxonomy = get_taxonomy( $taxonomy );
2135
2136                 $term = get_term( $term_id , $taxonomy->name, ARRAY_A );
2137
2138                 if ( is_wp_error( $term ) )
2139                         return new IXR_Error( 500, $term->get_error_message() );
2140
2141                 if ( ! $term )
2142                         return new IXR_Error( 404, __( 'Invalid term ID.' ) );
2143
2144                 if ( ! current_user_can( 'assign_term', $term_id ) ) {
2145                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign this term.' ) );
2146                 }
2147
2148                 return $this->_prepare_term( $term );
2149         }
2150
2151         /**
2152          * Retrieve all terms for a taxonomy.
2153          *
2154          * @since 3.4.0
2155          *
2156          * The optional $filter parameter modifies the query used to retrieve terms.
2157          * Accepted keys are 'number', 'offset', 'orderby', 'order', 'hide_empty', and 'search'.
2158          *
2159          * @see get_terms()
2160          *
2161          * @param array  $args {
2162          *     Method arguments. Note: arguments must be ordered as documented.
2163          *
2164          *     @type int    $blog_id  Blog ID (unused).
2165          *     @type string $username Username.
2166          *     @type string $password Password.
2167          *     @type string $taxnomy  Taxonomy name.
2168          *     @type array  $filter   Optional. Modifies the query used to retrieve posts. Accepts 'number',
2169          *                            'offset', 'orderby', 'order', 'hide_empty', and 'search'. Default empty array.
2170          * }
2171          * @return array|IXR_Error An associative array of terms data on success, IXR_Error instance otherwise.
2172          */
2173         public function wp_getTerms( $args ) {
2174                 if ( ! $this->minimum_args( $args, 4 ) )
2175                         return $this->error;
2176
2177                 $this->escape( $args );
2178
2179                 $username       = $args[1];
2180                 $password       = $args[2];
2181                 $taxonomy       = $args[3];
2182                 $filter         = isset( $args[4] ) ? $args[4] : array();
2183
2184                 if ( ! $user = $this->login( $username, $password ) )
2185                         return $this->error;
2186
2187                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2188                 do_action( 'xmlrpc_call', 'wp.getTerms' );
2189
2190                 if ( ! taxonomy_exists( $taxonomy ) )
2191                         return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2192
2193                 $taxonomy = get_taxonomy( $taxonomy );
2194
2195                 if ( ! current_user_can( $taxonomy->cap->assign_terms ) )
2196                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
2197
2198                 $query = array();
2199
2200                 if ( isset( $filter['number'] ) )
2201                         $query['number'] = absint( $filter['number'] );
2202
2203                 if ( isset( $filter['offset'] ) )
2204                         $query['offset'] = absint( $filter['offset'] );
2205
2206                 if ( isset( $filter['orderby'] ) ) {
2207                         $query['orderby'] = $filter['orderby'];
2208
2209                         if ( isset( $filter['order'] ) )
2210                                 $query['order'] = $filter['order'];
2211                 }
2212
2213                 if ( isset( $filter['hide_empty'] ) )
2214                         $query['hide_empty'] = $filter['hide_empty'];
2215                 else
2216                         $query['get'] = 'all';
2217
2218                 if ( isset( $filter['search'] ) )
2219                         $query['search'] = $filter['search'];
2220
2221                 $terms = get_terms( $taxonomy->name, $query );
2222
2223                 if ( is_wp_error( $terms ) )
2224                         return new IXR_Error( 500, $terms->get_error_message() );
2225
2226                 $struct = array();
2227
2228                 foreach ( $terms as $term ) {
2229                         $struct[] = $this->_prepare_term( $term );
2230                 }
2231
2232                 return $struct;
2233         }
2234
2235         /**
2236          * Retrieve a taxonomy.
2237          *
2238          * @since 3.4.0
2239          *
2240          * @see get_taxonomy()
2241          *
2242          * @param array  $args {
2243          *     Method arguments. Note: arguments must be ordered as documented.
2244          *
2245          *     @type int    $blog_id  Blog ID (unused).
2246          *     @type string $username Username.
2247          *     @type string $password Password.
2248          *     @type string $taxnomy  Taxonomy name.
2249          *     @type array  $fields   Optional. Array of taxonomy fields to limit to in the return.
2250          *                            Accepts 'labels', 'cap', 'menu', and 'object_type'.
2251          *                            Default empty array.
2252          * }
2253          * @return array|IXR_Error An array of taxonomy data on success, IXR_Error instance otherwise.
2254          */
2255         public function wp_getTaxonomy( $args ) {
2256                 if ( ! $this->minimum_args( $args, 4 ) )
2257                         return $this->error;
2258
2259                 $this->escape( $args );
2260
2261                 $username = $args[1];
2262                 $password = $args[2];
2263                 $taxonomy = $args[3];
2264
2265                 if ( isset( $args[4] ) ) {
2266                         $fields = $args[4];
2267                 } else {
2268                         /**
2269                          * Filters the taxonomy query fields used by the given XML-RPC method.
2270                          *
2271                          * @since 3.4.0
2272                          *
2273                          * @param array  $fields An array of taxonomy fields to retrieve.
2274                          * @param string $method The method name.
2275                          */
2276                         $fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomy' );
2277                 }
2278
2279                 if ( ! $user = $this->login( $username, $password ) )
2280                         return $this->error;
2281
2282                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2283                 do_action( 'xmlrpc_call', 'wp.getTaxonomy' );
2284
2285                 if ( ! taxonomy_exists( $taxonomy ) )
2286                         return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
2287
2288                 $taxonomy = get_taxonomy( $taxonomy );
2289
2290                 if ( ! current_user_can( $taxonomy->cap->assign_terms ) )
2291                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
2292
2293                 return $this->_prepare_taxonomy( $taxonomy, $fields );
2294         }
2295
2296         /**
2297          * Retrieve all taxonomies.
2298          *
2299          * @since 3.4.0
2300          *
2301          * @see get_taxonomies()
2302          *
2303          * @param array  $args {
2304          *     Method arguments. Note: arguments must be ordered as documented.
2305          *
2306          *     @type int    $blog_id  Blog ID (unused).
2307          *     @type string $username Username.
2308          *     @type string $password Password.
2309          *     @type array  $filter   Optional. An array of arguments for retrieving taxonomies.
2310          *     @type array  $fields   Optional. The subset of taxonomy fields to return.
2311          * }
2312          * @return array|IXR_Error An associative array of taxonomy data with returned fields determined
2313          *                         by `$fields`, or an IXR_Error instance on failure.
2314          */
2315         public function wp_getTaxonomies( $args ) {
2316                 if ( ! $this->minimum_args( $args, 3 ) )
2317                         return $this->error;
2318
2319                 $this->escape( $args );
2320
2321                 $username = $args[1];
2322                 $password = $args[2];
2323                 $filter   = isset( $args[3] ) ? $args[3] : array( 'public' => true );
2324
2325                 if ( isset( $args[4] ) ) {
2326                         $fields = $args[4];
2327                 } else {
2328                         /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2329                         $fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomies' );
2330                 }
2331
2332                 if ( ! $user = $this->login( $username, $password ) )
2333                         return $this->error;
2334
2335                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2336                 do_action( 'xmlrpc_call', 'wp.getTaxonomies' );
2337
2338                 $taxonomies = get_taxonomies( $filter, 'objects' );
2339
2340                 // holds all the taxonomy data
2341                 $struct = array();
2342
2343                 foreach ( $taxonomies as $taxonomy ) {
2344                         // capability check for post_types
2345                         if ( ! current_user_can( $taxonomy->cap->assign_terms ) )
2346                                 continue;
2347
2348                         $struct[] = $this->_prepare_taxonomy( $taxonomy, $fields );
2349                 }
2350
2351                 return $struct;
2352         }
2353
2354         /**
2355          * Retrieve a user.
2356          *
2357          * The optional $fields parameter specifies what fields will be included
2358          * in the response array. This should be a list of field names. 'user_id' will
2359          * always be included in the response regardless of the value of $fields.
2360          *
2361          * Instead of, or in addition to, individual field names, conceptual group
2362          * names can be used to specify multiple fields. The available conceptual
2363          * groups are 'basic' and 'all'.
2364          *
2365          * @uses get_userdata()
2366          *
2367          * @param array  $args {
2368          *     Method arguments. Note: arguments must be ordered as documented.
2369          *
2370          *     @type int    $blog_id (unused)
2371          *     @type string $username
2372          *     @type string $password
2373          *     @type int    $user_id
2374          *     @type array  $fields (optional)
2375          * }
2376          * @return array|IXR_Error Array contains (based on $fields parameter):
2377          *  - 'user_id'
2378          *  - 'username'
2379          *  - 'first_name'
2380          *  - 'last_name'
2381          *  - 'registered'
2382          *  - 'bio'
2383          *  - 'email'
2384          *  - 'nickname'
2385          *  - 'nicename'
2386          *  - 'url'
2387          *  - 'display_name'
2388          *  - 'roles'
2389          */
2390         public function wp_getUser( $args ) {
2391                 if ( ! $this->minimum_args( $args, 4 ) )
2392                         return $this->error;
2393
2394                 $this->escape( $args );
2395
2396                 $username = $args[1];
2397                 $password = $args[2];
2398                 $user_id  = (int) $args[3];
2399
2400                 if ( isset( $args[4] ) ) {
2401                         $fields = $args[4];
2402                 } else {
2403                         /**
2404                          * Filters the default user query fields used by the given XML-RPC method.
2405                          *
2406                          * @since 3.5.0
2407                          *
2408                          * @param array  $fields User query fields for given method. Default 'all'.
2409                          * @param string $method The method name.
2410                          */
2411                         $fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUser' );
2412                 }
2413
2414                 if ( ! $user = $this->login( $username, $password ) )
2415                         return $this->error;
2416
2417                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2418                 do_action( 'xmlrpc_call', 'wp.getUser' );
2419
2420                 if ( ! current_user_can( 'edit_user', $user_id ) )
2421                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this user.' ) );
2422
2423                 $user_data = get_userdata( $user_id );
2424
2425                 if ( ! $user_data )
2426                         return new IXR_Error( 404, __( 'Invalid user ID.' ) );
2427
2428                 return $this->_prepare_user( $user_data, $fields );
2429         }
2430
2431         /**
2432          * Retrieve users.
2433          *
2434          * The optional $filter parameter modifies the query used to retrieve users.
2435          * Accepted keys are 'number' (default: 50), 'offset' (default: 0), 'role',
2436          * 'who', 'orderby', and 'order'.
2437          *
2438          * The optional $fields parameter specifies what fields will be included
2439          * in the response array.
2440          *
2441          * @uses get_users()
2442          * @see wp_getUser() for more on $fields and return values
2443          *
2444          * @param array  $args {
2445          *     Method arguments. Note: arguments must be ordered as documented.
2446          *
2447          *     @type int    $blog_id (unused)
2448          *     @type string $username
2449          *     @type string $password
2450          *     @type array  $filter (optional)
2451          *     @type array  $fields (optional)
2452          * }
2453          * @return array|IXR_Error users data
2454          */
2455         public function wp_getUsers( $args ) {
2456                 if ( ! $this->minimum_args( $args, 3 ) )
2457                         return $this->error;
2458
2459                 $this->escape( $args );
2460
2461                 $username = $args[1];
2462                 $password = $args[2];
2463                 $filter   = isset( $args[3] ) ? $args[3] : array();
2464
2465                 if ( isset( $args[4] ) ) {
2466                         $fields = $args[4];
2467                 } else {
2468                         /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2469                         $fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUsers' );
2470                 }
2471
2472                 if ( ! $user = $this->login( $username, $password ) )
2473                         return $this->error;
2474
2475                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2476                 do_action( 'xmlrpc_call', 'wp.getUsers' );
2477
2478                 if ( ! current_user_can( 'list_users' ) )
2479                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to list users.' ) );
2480
2481                 $query = array( 'fields' => 'all_with_meta' );
2482
2483                 $query['number'] = ( isset( $filter['number'] ) ) ? absint( $filter['number'] ) : 50;
2484                 $query['offset'] = ( isset( $filter['offset'] ) ) ? absint( $filter['offset'] ) : 0;
2485
2486                 if ( isset( $filter['orderby'] ) ) {
2487                         $query['orderby'] = $filter['orderby'];
2488
2489                         if ( isset( $filter['order'] ) )
2490                                 $query['order'] = $filter['order'];
2491                 }
2492
2493                 if ( isset( $filter['role'] ) ) {
2494                         if ( get_role( $filter['role'] ) === null )
2495                                 return new IXR_Error( 403, __( 'Invalid role.' ) );
2496
2497                         $query['role'] = $filter['role'];
2498                 }
2499
2500                 if ( isset( $filter['who'] ) ) {
2501                         $query['who'] = $filter['who'];
2502                 }
2503
2504                 $users = get_users( $query );
2505
2506                 $_users = array();
2507                 foreach ( $users as $user_data ) {
2508                         if ( current_user_can( 'edit_user', $user_data->ID ) )
2509                                 $_users[] = $this->_prepare_user( $user_data, $fields );
2510                 }
2511                 return $_users;
2512         }
2513
2514         /**
2515          * Retrieve information about the requesting user.
2516          *
2517          * @uses get_userdata()
2518          *
2519          * @param array  $args {
2520          *     Method arguments. Note: arguments must be ordered as documented.
2521          *
2522          *     @type int    $blog_id (unused)
2523          *     @type string $username
2524          *     @type string $password
2525          *     @type array  $fields (optional)
2526          * }
2527          * @return array|IXR_Error (@see wp_getUser)
2528          */
2529         public function wp_getProfile( $args ) {
2530                 if ( ! $this->minimum_args( $args, 3 ) )
2531                         return $this->error;
2532
2533                 $this->escape( $args );
2534
2535                 $username = $args[1];
2536                 $password = $args[2];
2537
2538                 if ( isset( $args[3] ) ) {
2539                         $fields = $args[3];
2540                 } else {
2541                         /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2542                         $fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getProfile' );
2543                 }
2544
2545                 if ( ! $user = $this->login( $username, $password ) )
2546                         return $this->error;
2547
2548                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2549                 do_action( 'xmlrpc_call', 'wp.getProfile' );
2550
2551                 if ( ! current_user_can( 'edit_user', $user->ID ) )
2552                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
2553
2554                 $user_data = get_userdata( $user->ID );
2555
2556                 return $this->_prepare_user( $user_data, $fields );
2557         }
2558
2559         /**
2560          * Edit user's profile.
2561          *
2562          * @uses wp_update_user()
2563          *
2564          * @param array  $args {
2565          *     Method arguments. Note: arguments must be ordered as documented.
2566          *
2567          *     @type int    $blog_id (unused)
2568          *     @type string $username
2569          *     @type string $password
2570          *     @type array  $content_struct It can optionally contain:
2571          *      - 'first_name'
2572          *      - 'last_name'
2573          *      - 'website'
2574          *      - 'display_name'
2575          *      - 'nickname'
2576          *      - 'nicename'
2577          *      - 'bio'
2578          * }
2579          * @return true|IXR_Error True, on success.
2580          */
2581         public function wp_editProfile( $args ) {
2582                 if ( ! $this->minimum_args( $args, 4 ) )
2583                         return $this->error;
2584
2585                 $this->escape( $args );
2586
2587                 $username       = $args[1];
2588                 $password       = $args[2];
2589                 $content_struct = $args[3];
2590
2591                 if ( ! $user = $this->login( $username, $password ) )
2592                         return $this->error;
2593
2594                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2595                 do_action( 'xmlrpc_call', 'wp.editProfile' );
2596
2597                 if ( ! current_user_can( 'edit_user', $user->ID ) )
2598                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
2599
2600                 // holds data of the user
2601                 $user_data = array();
2602                 $user_data['ID'] = $user->ID;
2603
2604                 // only set the user details if it was given
2605                 if ( isset( $content_struct['first_name'] ) )
2606                         $user_data['first_name'] = $content_struct['first_name'];
2607
2608                 if ( isset( $content_struct['last_name'] ) )
2609                         $user_data['last_name'] = $content_struct['last_name'];
2610
2611                 if ( isset( $content_struct['url'] ) )
2612                         $user_data['user_url'] = $content_struct['url'];
2613
2614                 if ( isset( $content_struct['display_name'] ) )
2615                         $user_data['display_name'] = $content_struct['display_name'];
2616
2617                 if ( isset( $content_struct['nickname'] ) )
2618                         $user_data['nickname'] = $content_struct['nickname'];
2619
2620                 if ( isset( $content_struct['nicename'] ) )
2621                         $user_data['user_nicename'] = $content_struct['nicename'];
2622
2623                 if ( isset( $content_struct['bio'] ) )
2624                         $user_data['description'] = $content_struct['bio'];
2625
2626                 $result = wp_update_user( $user_data );
2627
2628                 if ( is_wp_error( $result ) )
2629                         return new IXR_Error( 500, $result->get_error_message() );
2630
2631                 if ( ! $result )
2632                         return new IXR_Error( 500, __( 'Sorry, the user cannot be updated.' ) );
2633
2634                 return true;
2635         }
2636
2637         /**
2638          * Retrieve page.
2639          *
2640          * @since 2.2.0
2641          *
2642          * @param array  $args {
2643          *     Method arguments. Note: arguments must be ordered as documented.
2644          *
2645          *     @type int    $blog_id (unused)
2646          *     @type int    $page_id
2647          *     @type string $username
2648          *     @type string $password
2649          * }
2650          * @return array|IXR_Error
2651          */
2652         public function wp_getPage( $args ) {
2653                 $this->escape( $args );
2654
2655                 $page_id  = (int) $args[1];
2656                 $username = $args[2];
2657                 $password = $args[3];
2658
2659                 if ( !$user = $this->login($username, $password) ) {
2660                         return $this->error;
2661                 }
2662
2663                 $page = get_post($page_id);
2664                 if ( ! $page )
2665                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
2666
2667                 if ( !current_user_can( 'edit_page', $page_id ) )
2668                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
2669
2670                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2671                 do_action( 'xmlrpc_call', 'wp.getPage' );
2672
2673                 // If we found the page then format the data.
2674                 if ( $page->ID && ($page->post_type == 'page') ) {
2675                         return $this->_prepare_page( $page );
2676                 }
2677                 // If the page doesn't exist indicate that.
2678                 else {
2679                         return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
2680                 }
2681         }
2682
2683         /**
2684          * Retrieve Pages.
2685          *
2686          * @since 2.2.0
2687          *
2688          * @param array  $args {
2689          *     Method arguments. Note: arguments must be ordered as documented.
2690          *
2691          *     @type int    $blog_id (unused)
2692          *     @type string $username
2693          *     @type string $password
2694          *     @type int    $num_pages
2695          * }
2696          * @return array|IXR_Error
2697          */
2698         public function wp_getPages( $args ) {
2699                 $this->escape( $args );
2700
2701                 $username  = $args[1];
2702                 $password  = $args[2];
2703                 $num_pages = isset($args[3]) ? (int) $args[3] : 10;
2704
2705                 if ( !$user = $this->login($username, $password) )
2706                         return $this->error;
2707
2708                 if ( !current_user_can( 'edit_pages' ) )
2709                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
2710
2711                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2712                 do_action( 'xmlrpc_call', 'wp.getPages' );
2713
2714                 $pages = get_posts( array('post_type' => 'page', 'post_status' => 'any', 'numberposts' => $num_pages) );
2715                 $num_pages = count($pages);
2716
2717                 // If we have pages, put together their info.
2718                 if ( $num_pages >= 1 ) {
2719                         $pages_struct = array();
2720
2721                         foreach ($pages as $page) {
2722                                 if ( current_user_can( 'edit_page', $page->ID ) )
2723                                         $pages_struct[] = $this->_prepare_page( $page );
2724                         }
2725
2726                         return $pages_struct;
2727                 }
2728
2729                 return array();
2730         }
2731
2732         /**
2733          * Create new page.
2734          *
2735          * @since 2.2.0
2736          *
2737          * @see wp_xmlrpc_server::mw_newPost()
2738          *
2739          * @param array  $args {
2740          *     Method arguments. Note: arguments must be ordered as documented.
2741          *
2742          *     @type int    $blog_id (unused)
2743          *     @type string $username
2744          *     @type string $password
2745          *     @type array  $content_struct
2746          * }
2747          * @return int|IXR_Error
2748          */
2749         public function wp_newPage( $args ) {
2750                 // Items not escaped here will be escaped in newPost.
2751                 $username = $this->escape( $args[1] );
2752                 $password = $this->escape( $args[2] );
2753
2754                 if ( !$user = $this->login($username, $password) )
2755                         return $this->error;
2756
2757                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2758                 do_action( 'xmlrpc_call', 'wp.newPage' );
2759
2760                 // Mark this as content for a page.
2761                 $args[3]["post_type"] = 'page';
2762
2763                 // Let mw_newPost do all of the heavy lifting.
2764                 return $this->mw_newPost( $args );
2765         }
2766
2767         /**
2768          * Delete page.
2769          *
2770          * @since 2.2.0
2771          *
2772          * @param array  $args {
2773          *     Method arguments. Note: arguments must be ordered as documented.
2774          *
2775          *     @type int    $blog_id (unused)
2776          *     @type string $username
2777          *     @type string $password
2778          *     @type int    $page_id
2779          * }
2780          * @return true|IXR_Error True, if success.
2781          */
2782         public function wp_deletePage( $args ) {
2783                 $this->escape( $args );
2784
2785                 $username = $args[1];
2786                 $password = $args[2];
2787                 $page_id  = (int) $args[3];
2788
2789                 if ( !$user = $this->login($username, $password) )
2790                         return $this->error;
2791
2792                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2793                 do_action( 'xmlrpc_call', 'wp.deletePage' );
2794
2795                 // Get the current page based on the page_id and
2796                 // make sure it is a page and not a post.
2797                 $actual_page = get_post($page_id, ARRAY_A);
2798                 if ( !$actual_page || ($actual_page['post_type'] != 'page') )
2799                         return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
2800
2801                 // Make sure the user can delete pages.
2802                 if ( !current_user_can('delete_page', $page_id) )
2803                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this page.' ) );
2804
2805                 // Attempt to delete the page.
2806                 $result = wp_delete_post($page_id);
2807                 if ( !$result )
2808                         return new IXR_Error( 500, __( 'Failed to delete the page.' ) );
2809
2810                 /**
2811                  * Fires after a page has been successfully deleted via XML-RPC.
2812                  *
2813                  * @since 3.4.0
2814                  *
2815                  * @param int   $page_id ID of the deleted page.
2816                  * @param array $args    An array of arguments to delete the page.
2817                  */
2818                 do_action( 'xmlrpc_call_success_wp_deletePage', $page_id, $args );
2819
2820                 return true;
2821         }
2822
2823         /**
2824          * Edit page.
2825          *
2826          * @since 2.2.0
2827          *
2828          * @param array  $args {
2829          *     Method arguments. Note: arguments must be ordered as documented.
2830          *
2831          *     @type int    $blog_id (unused)
2832          *     @type int    $page_id
2833          *     @type string $username
2834          *     @type string $password
2835          *     @type string $content
2836          *     @type string $publish
2837          * }
2838          * @return array|IXR_Error
2839          */
2840         public function wp_editPage( $args ) {
2841                 // Items will be escaped in mw_editPost.
2842                 $page_id  = (int) $args[1];
2843                 $username = $args[2];
2844                 $password = $args[3];
2845                 $content  = $args[4];
2846                 $publish  = $args[5];
2847
2848                 $escaped_username = $this->escape( $username );
2849                 $escaped_password = $this->escape( $password );
2850
2851                 if ( !$user = $this->login( $escaped_username, $escaped_password ) ) {
2852                         return $this->error;
2853                 }
2854
2855                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2856                 do_action( 'xmlrpc_call', 'wp.editPage' );
2857
2858                 // Get the page data and make sure it is a page.
2859                 $actual_page = get_post($page_id, ARRAY_A);
2860                 if ( !$actual_page || ($actual_page['post_type'] != 'page') )
2861                         return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
2862
2863                 // Make sure the user is allowed to edit pages.
2864                 if ( !current_user_can('edit_page', $page_id) )
2865                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
2866
2867                 // Mark this as content for a page.
2868                 $content['post_type'] = 'page';
2869
2870                 // Arrange args in the way mw_editPost understands.
2871                 $args = array(
2872                         $page_id,
2873                         $username,
2874                         $password,
2875                         $content,
2876                         $publish
2877                 );
2878
2879                 // Let mw_editPost do all of the heavy lifting.
2880                 return $this->mw_editPost( $args );
2881         }
2882
2883         /**
2884          * Retrieve page list.
2885          *
2886          * @since 2.2.0
2887          *
2888          * @global wpdb $wpdb WordPress database abstraction object.
2889          *
2890          * @param array  $args {
2891          *     Method arguments. Note: arguments must be ordered as documented.
2892          *
2893          *     @type int    $blog_id (unused)
2894          *     @type string $username
2895          *     @type string $password
2896          * }
2897          * @return array|IXR_Error
2898          */
2899         public function wp_getPageList( $args ) {
2900                 global $wpdb;
2901
2902                 $this->escape( $args );
2903
2904                 $username = $args[1];
2905                 $password = $args[2];
2906
2907                 if ( !$user = $this->login($username, $password) )
2908                         return $this->error;
2909
2910                 if ( !current_user_can( 'edit_pages' ) )
2911                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
2912
2913                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2914                 do_action( 'xmlrpc_call', 'wp.getPageList' );
2915
2916                 // Get list of pages ids and titles
2917                 $page_list = $wpdb->get_results("
2918                         SELECT ID page_id,
2919                                 post_title page_title,
2920                                 post_parent page_parent_id,
2921                                 post_date_gmt,
2922                                 post_date,
2923                                 post_status
2924                         FROM {$wpdb->posts}
2925                         WHERE post_type = 'page'
2926                         ORDER BY ID
2927                 ");
2928
2929                 // The date needs to be formatted properly.
2930                 $num_pages = count($page_list);
2931                 for ( $i = 0; $i < $num_pages; $i++ ) {
2932                         $page_list[$i]->dateCreated = $this->_convert_date(  $page_list[$i]->post_date );
2933                         $page_list[$i]->date_created_gmt = $this->_convert_date_gmt( $page_list[$i]->post_date_gmt, $page_list[$i]->post_date );
2934
2935                         unset($page_list[$i]->post_date_gmt);
2936                         unset($page_list[$i]->post_date);
2937                         unset($page_list[$i]->post_status);
2938                 }
2939
2940                 return $page_list;
2941         }
2942
2943         /**
2944          * Retrieve authors list.
2945          *
2946          * @since 2.2.0
2947          *
2948          * @param array  $args {
2949          *     Method arguments. Note: arguments must be ordered as documented.
2950          *
2951          *     @type int    $blog_id (unused)
2952          *     @type string $username
2953          *     @type string $password
2954          * }
2955          * @return array|IXR_Error
2956          */
2957         public function wp_getAuthors( $args ) {
2958                 $this->escape( $args );
2959
2960                 $username = $args[1];
2961                 $password = $args[2];
2962
2963                 if ( !$user = $this->login($username, $password) )
2964                         return $this->error;
2965
2966                 if ( !current_user_can('edit_posts') )
2967                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
2968
2969                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
2970                 do_action( 'xmlrpc_call', 'wp.getAuthors' );
2971
2972                 $authors = array();
2973                 foreach ( get_users( array( 'fields' => array('ID','user_login','display_name') ) ) as $user ) {
2974                         $authors[] = array(
2975                                 'user_id'       => $user->ID,
2976                                 'user_login'    => $user->user_login,
2977                                 'display_name'  => $user->display_name
2978                         );
2979                 }
2980
2981                 return $authors;
2982         }
2983
2984         /**
2985          * Get list of all tags
2986          *
2987          * @since 2.7.0
2988          *
2989          * @param array  $args {
2990          *     Method arguments. Note: arguments must be ordered as documented.
2991          *
2992          *     @type int    $blog_id (unused)
2993          *     @type string $username
2994          *     @type string $password
2995          * }
2996          * @return array|IXR_Error
2997          */
2998         public function wp_getTags( $args ) {
2999                 $this->escape( $args );
3000
3001                 $username = $args[1];
3002                 $password = $args[2];
3003
3004                 if ( !$user = $this->login($username, $password) )
3005                         return $this->error;
3006
3007                 if ( !current_user_can( 'edit_posts' ) )
3008                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view tags.' ) );
3009
3010                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3011                 do_action( 'xmlrpc_call', 'wp.getKeywords' );
3012
3013                 $tags = array();
3014
3015                 if ( $all_tags = get_tags() ) {
3016                         foreach ( (array) $all_tags as $tag ) {
3017                                 $struct = array();
3018                                 $struct['tag_id']                       = $tag->term_id;
3019                                 $struct['name']                         = $tag->name;
3020                                 $struct['count']                        = $tag->count;
3021                                 $struct['slug']                         = $tag->slug;
3022                                 $struct['html_url']                     = esc_html( get_tag_link( $tag->term_id ) );
3023                                 $struct['rss_url']                      = esc_html( get_tag_feed_link( $tag->term_id ) );
3024
3025                                 $tags[] = $struct;
3026                         }
3027                 }
3028
3029                 return $tags;
3030         }
3031
3032         /**
3033          * Create new category.
3034          *
3035          * @since 2.2.0
3036          *
3037          * @param array  $args {
3038          *     Method arguments. Note: arguments must be ordered as documented.
3039          *
3040          *     @type int    $blog_id (unused)
3041          *     @type string $username
3042          *     @type string $password
3043          *     @type array  $category
3044          * }
3045          * @return int|IXR_Error Category ID.
3046          */
3047         public function wp_newCategory( $args ) {
3048                 $this->escape( $args );
3049
3050                 $username = $args[1];
3051                 $password = $args[2];
3052                 $category = $args[3];
3053
3054                 if ( !$user = $this->login($username, $password) )
3055                         return $this->error;
3056
3057                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3058                 do_action( 'xmlrpc_call', 'wp.newCategory' );
3059
3060                 // Make sure the user is allowed to add a category.
3061                 if ( !current_user_can('manage_categories') )
3062                         return new IXR_Error(401, __('Sorry, you are not allowed to add a category.'));
3063
3064                 // If no slug was provided make it empty so that
3065                 // WordPress will generate one.
3066                 if ( empty($category['slug']) )
3067                         $category['slug'] = '';
3068
3069                 // If no parent_id was provided make it empty
3070                 // so that it will be a top level page (no parent).
3071                 if ( !isset($category['parent_id']) )
3072                         $category['parent_id'] = '';
3073
3074                 // If no description was provided make it empty.
3075                 if ( empty($category["description"]) )
3076                         $category["description"] = "";
3077
3078                 $new_category = array(
3079                         'cat_name'                              => $category['name'],
3080                         'category_nicename'             => $category['slug'],
3081                         'category_parent'               => $category['parent_id'],
3082                         'category_description'  => $category['description']
3083                 );
3084
3085                 $cat_id = wp_insert_category($new_category, true);
3086                 if ( is_wp_error( $cat_id ) ) {
3087                         if ( 'term_exists' == $cat_id->get_error_code() )
3088                                 return (int) $cat_id->get_error_data();
3089                         else
3090                                 return new IXR_Error(500, __('Sorry, the new category failed.'));
3091                 } elseif ( ! $cat_id ) {
3092                         return new IXR_Error(500, __('Sorry, the new category failed.'));
3093                 }
3094
3095                 /**
3096                  * Fires after a new category has been successfully created via XML-RPC.
3097                  *
3098                  * @since 3.4.0
3099                  *
3100                  * @param int   $cat_id ID of the new category.
3101                  * @param array $args   An array of new category arguments.
3102                  */
3103                 do_action( 'xmlrpc_call_success_wp_newCategory', $cat_id, $args );
3104
3105                 return $cat_id;
3106         }
3107
3108         /**
3109          * Remove category.
3110          *
3111          * @since 2.5.0
3112          *
3113          * @param array  $args {
3114          *     Method arguments. Note: arguments must be ordered as documented.
3115          *
3116          *     @type int    $blog_id (unused)
3117          *     @type string $username
3118          *     @type string $password
3119          *     @type int    $category_id
3120          * }
3121          * @return bool|IXR_Error See wp_delete_term() for return info.
3122          */
3123         public function wp_deleteCategory( $args ) {
3124                 $this->escape( $args );
3125
3126                 $username    = $args[1];
3127                 $password    = $args[2];
3128                 $category_id = (int) $args[3];
3129
3130                 if ( !$user = $this->login($username, $password) )
3131                         return $this->error;
3132
3133                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3134                 do_action( 'xmlrpc_call', 'wp.deleteCategory' );
3135
3136                 if ( !current_user_can('manage_categories') )
3137                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete a category.' ) );
3138
3139                 $status = wp_delete_term( $category_id, 'category' );
3140
3141                 if ( true == $status ) {
3142                         /**
3143                          * Fires after a category has been successfully deleted via XML-RPC.
3144                          *
3145                          * @since 3.4.0
3146                          *
3147                          * @param int   $category_id ID of the deleted category.
3148                          * @param array $args        An array of arguments to delete the category.
3149                          */
3150                         do_action( 'xmlrpc_call_success_wp_deleteCategory', $category_id, $args );
3151                 }
3152
3153                 return $status;
3154         }
3155
3156         /**
3157          * Retrieve category list.
3158          *
3159          * @since 2.2.0
3160          *
3161          * @param array  $args {
3162          *     Method arguments. Note: arguments must be ordered as documented.
3163          *
3164          *     @type int    $blog_id (unused)
3165          *     @type string $username
3166          *     @type string $password
3167          *     @type array  $category
3168          *     @type int    $max_results
3169          * }
3170          * @return array|IXR_Error
3171          */
3172         public function wp_suggestCategories( $args ) {
3173                 $this->escape( $args );
3174
3175                 $username    = $args[1];
3176                 $password    = $args[2];
3177                 $category    = $args[3];
3178                 $max_results = (int) $args[4];
3179
3180                 if ( !$user = $this->login($username, $password) )
3181                         return $this->error;
3182
3183                 if ( !current_user_can( 'edit_posts' ) )
3184                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
3185
3186                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3187                 do_action( 'xmlrpc_call', 'wp.suggestCategories' );
3188
3189                 $category_suggestions = array();
3190                 $args = array('get' => 'all', 'number' => $max_results, 'name__like' => $category);
3191                 foreach ( (array) get_categories($args) as $cat ) {
3192                         $category_suggestions[] = array(
3193                                 'category_id'   => $cat->term_id,
3194                                 'category_name' => $cat->name
3195                         );
3196                 }
3197
3198                 return $category_suggestions;
3199         }
3200
3201         /**
3202          * Retrieve comment.
3203          *
3204          * @since 2.7.0
3205          *
3206          * @param array  $args {
3207          *     Method arguments. Note: arguments must be ordered as documented.
3208          *
3209          *     @type int    $blog_id (unused)
3210          *     @type string $username
3211          *     @type string $password
3212          *     @type int    $comment_id
3213          * }
3214          * @return array|IXR_Error
3215          */
3216         public function wp_getComment($args) {
3217                 $this->escape($args);
3218
3219                 $username       = $args[1];
3220                 $password       = $args[2];
3221                 $comment_id     = (int) $args[3];
3222
3223                 if ( ! $user = $this->login( $username, $password ) ) {
3224                         return $this->error;
3225                 }
3226
3227                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3228                 do_action( 'xmlrpc_call', 'wp.getComment' );
3229
3230                 if ( ! $comment = get_comment( $comment_id ) ) {
3231                         return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
3232                 }
3233
3234                 if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
3235                         return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
3236                 }
3237
3238                 return $this->_prepare_comment( $comment );
3239         }
3240
3241         /**
3242          * Retrieve comments.
3243          *
3244          * Besides the common blog_id (unused), username, and password arguments, it takes a filter
3245          * array as last argument.
3246          *
3247          * Accepted 'filter' keys are 'status', 'post_id', 'offset', and 'number'.
3248          *
3249          * The defaults are as follows:
3250          * - 'status' - Default is ''. Filter by status (e.g., 'approve', 'hold')
3251          * - 'post_id' - Default is ''. The post where the comment is posted. Empty string shows all comments.
3252          * - 'number' - Default is 10. Total number of media items to retrieve.
3253          * - 'offset' - Default is 0. See WP_Query::query() for more.
3254          *
3255          * @since 2.7.0
3256          *
3257          * @param array  $args {
3258          *     Method arguments. Note: arguments must be ordered as documented.
3259          *
3260          *     @type int    $blog_id (unused)
3261          *     @type string $username
3262          *     @type string $password
3263          *     @type array  $struct
3264          * }
3265          * @return array|IXR_Error Contains a collection of comments. See wp_xmlrpc_server::wp_getComment() for a description of each item contents
3266          */
3267         public function wp_getComments( $args ) {
3268                 $this->escape( $args );
3269
3270                 $username = $args[1];
3271                 $password = $args[2];
3272                 $struct   = isset( $args[3] ) ? $args[3] : array();
3273
3274                 if ( ! $user = $this->login( $username, $password ) ) {
3275                         return $this->error;
3276                 }
3277
3278                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3279                 do_action( 'xmlrpc_call', 'wp.getComments' );
3280
3281                 if ( isset( $struct['status'] ) ) {
3282                         $status = $struct['status'];
3283                 } else {
3284                         $status = '';
3285                 }
3286
3287                 if ( ! current_user_can( 'moderate_comments' ) && 'approve' !== $status ) {
3288                         return new IXR_Error( 401, __( 'Invalid comment status.' ) );
3289                 }
3290
3291                 $post_id = '';
3292                 if ( isset( $struct['post_id'] ) ) {
3293                         $post_id = absint( $struct['post_id'] );
3294                 }
3295
3296                 $post_type = '';
3297                 if ( isset( $struct['post_type'] ) ) {
3298                         $post_type_object = get_post_type_object( $struct['post_type'] );
3299                         if ( ! $post_type_object || ! post_type_supports( $post_type_object->name, 'comments' ) ) {
3300                                 return new IXR_Error( 404, __( 'Invalid post type.' ) );
3301                         }
3302                         $post_type = $struct['post_type'];
3303                 }
3304
3305                 $offset = 0;
3306                 if ( isset( $struct['offset'] ) ) {
3307                         $offset = absint( $struct['offset'] );
3308                 }
3309
3310                 $number = 10;
3311                 if ( isset( $struct['number'] ) ) {
3312                         $number = absint( $struct['number'] );
3313                 }
3314
3315                 $comments = get_comments( array(
3316                         'status' => $status,
3317                         'post_id' => $post_id,
3318                         'offset' => $offset,
3319                         'number' => $number,
3320                         'post_type' => $post_type,
3321                 ) );
3322
3323                 $comments_struct = array();
3324                 if ( is_array( $comments ) ) {
3325                         foreach ( $comments as $comment ) {
3326                                 $comments_struct[] = $this->_prepare_comment( $comment );
3327                         }
3328                 }
3329
3330                 return $comments_struct;
3331         }
3332
3333         /**
3334          * Delete a comment.
3335          *
3336          * By default, the comment will be moved to the trash instead of deleted.
3337          * See wp_delete_comment() for more information on this behavior.
3338          *
3339          * @since 2.7.0
3340          *
3341          * @param array  $args {
3342          *     Method arguments. Note: arguments must be ordered as documented.
3343          *
3344          *     @type int    $blog_id (unused)
3345          *     @type string $username
3346          *     @type string $password
3347          *     @type int    $comment_ID
3348          * }
3349          * @return bool|IXR_Error See wp_delete_comment().
3350          */
3351         public function wp_deleteComment( $args ) {
3352                 $this->escape($args);
3353
3354                 $username       = $args[1];
3355                 $password       = $args[2];
3356                 $comment_ID     = (int) $args[3];
3357
3358                 if ( ! $user = $this->login( $username, $password ) ) {
3359                         return $this->error;
3360                 }
3361
3362                 if ( ! get_comment( $comment_ID ) ) {
3363                         return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
3364                 }
3365
3366                 if ( !current_user_can( 'edit_comment', $comment_ID ) ) {
3367                         return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
3368                 }
3369
3370                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3371                 do_action( 'xmlrpc_call', 'wp.deleteComment' );
3372
3373                 $status = wp_delete_comment( $comment_ID );
3374
3375                 if ( $status ) {
3376                         /**
3377                          * Fires after a comment has been successfully deleted via XML-RPC.
3378                          *
3379                          * @since 3.4.0
3380                          *
3381                          * @param int   $comment_ID ID of the deleted comment.
3382                          * @param array $args       An array of arguments to delete the comment.
3383                          */
3384                         do_action( 'xmlrpc_call_success_wp_deleteComment', $comment_ID, $args );
3385                 }
3386
3387                 return $status;
3388         }
3389
3390         /**
3391          * Edit comment.
3392          *
3393          * Besides the common blog_id (unused), username, and password arguments, it takes a
3394          * comment_id integer and a content_struct array as last argument.
3395          *
3396          * The allowed keys in the content_struct array are:
3397          *  - 'author'
3398          *  - 'author_url'
3399          *  - 'author_email'
3400          *  - 'content'
3401          *  - 'date_created_gmt'
3402          *  - 'status'. Common statuses are 'approve', 'hold', 'spam'. See get_comment_statuses() for more details
3403          *
3404          * @since 2.7.0
3405          *
3406          * @param array  $args {
3407          *     Method arguments. Note: arguments must be ordered as documented.
3408          *
3409          *     @type int    $blog_id (unused)
3410          *     @type string $username
3411          *     @type string $password
3412          *     @type int    $comment_ID
3413          *     @type array  $content_struct
3414          * }
3415          * @return true|IXR_Error True, on success.
3416          */
3417         public function wp_editComment( $args ) {
3418                 $this->escape( $args );
3419
3420                 $username       = $args[1];
3421                 $password       = $args[2];
3422                 $comment_ID     = (int) $args[3];
3423                 $content_struct = $args[4];
3424
3425                 if ( !$user = $this->login( $username, $password ) ) {
3426                         return $this->error;
3427                 }
3428
3429                 if ( ! get_comment( $comment_ID ) ) {
3430                         return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
3431                 }
3432
3433                 if ( ! current_user_can( 'edit_comment', $comment_ID ) ) {
3434                         return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
3435                 }
3436
3437                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3438                 do_action( 'xmlrpc_call', 'wp.editComment' );
3439
3440                 if ( isset($content_struct['status']) ) {
3441                         $statuses = get_comment_statuses();
3442                         $statuses = array_keys($statuses);
3443
3444                         if ( ! in_array($content_struct['status'], $statuses) )
3445                                 return new IXR_Error( 401, __( 'Invalid comment status.' ) );
3446                         $comment_approved = $content_struct['status'];
3447                 }
3448
3449                 // Do some timestamp voodoo
3450                 if ( !empty( $content_struct['date_created_gmt'] ) ) {
3451                         // We know this is supposed to be GMT, so we're going to slap that Z on there by force
3452                         $dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
3453                         $comment_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
3454                         $comment_date_gmt = iso8601_to_datetime($dateCreated, 'GMT');
3455                 }
3456
3457                 if ( isset($content_struct['content']) )
3458                         $comment_content = $content_struct['content'];
3459
3460                 if ( isset($content_struct['author']) )
3461                         $comment_author = $content_struct['author'];
3462
3463                 if ( isset($content_struct['author_url']) )
3464                         $comment_author_url = $content_struct['author_url'];
3465
3466                 if ( isset($content_struct['author_email']) )
3467                         $comment_author_email = $content_struct['author_email'];
3468
3469                 // We've got all the data -- post it:
3470                 $comment = compact('comment_ID', 'comment_content', 'comment_approved', 'comment_date', 'comment_date_gmt', 'comment_author', 'comment_author_email', 'comment_author_url');
3471
3472                 $result = wp_update_comment($comment);
3473                 if ( is_wp_error( $result ) )
3474                         return new IXR_Error(500, $result->get_error_message());
3475
3476                 if ( !$result )
3477                         return new IXR_Error(500, __('Sorry, the comment could not be edited.'));
3478
3479                 /**
3480                  * Fires after a comment has been successfully updated via XML-RPC.
3481                  *
3482                  * @since 3.4.0
3483                  *
3484                  * @param int   $comment_ID ID of the updated comment.
3485                  * @param array $args       An array of arguments to update the comment.
3486                  */
3487                 do_action( 'xmlrpc_call_success_wp_editComment', $comment_ID, $args );
3488
3489                 return true;
3490         }
3491
3492         /**
3493          * Create new comment.
3494          *
3495          * @since 2.7.0
3496          *
3497          * @param array  $args {
3498          *     Method arguments. Note: arguments must be ordered as documented.
3499          *
3500          *     @type int        $blog_id (unused)
3501          *     @type string     $username
3502          *     @type string     $password
3503          *     @type string|int $post
3504          *     @type array      $content_struct
3505          * }
3506          * @return int|IXR_Error See wp_new_comment().
3507          */
3508         public function wp_newComment($args) {
3509                 $this->escape($args);
3510
3511                 $username       = $args[1];
3512                 $password       = $args[2];
3513                 $post           = $args[3];
3514                 $content_struct = $args[4];
3515
3516                 /**
3517                  * Filters whether to allow anonymous comments over XML-RPC.
3518                  *
3519                  * @since 2.7.0
3520                  *
3521                  * @param bool $allow Whether to allow anonymous commenting via XML-RPC.
3522                  *                    Default false.
3523                  */
3524                 $allow_anon = apply_filters( 'xmlrpc_allow_anonymous_comments', false );
3525
3526                 $user = $this->login($username, $password);
3527
3528                 if ( !$user ) {
3529                         $logged_in = false;
3530                         if ( $allow_anon && get_option('comment_registration') ) {
3531                                 return new IXR_Error( 403, __( 'You must be registered to comment.' ) );
3532                         } elseif ( ! $allow_anon ) {
3533                                 return $this->error;
3534                         }
3535                 } else {
3536                         $logged_in = true;
3537                 }
3538
3539                 if ( is_numeric($post) )
3540                         $post_id = absint($post);
3541                 else
3542                         $post_id = url_to_postid($post);
3543
3544                 if ( ! $post_id ) {
3545                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
3546                 }
3547
3548                 if ( ! get_post( $post_id ) ) {
3549                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
3550                 }
3551
3552                 if ( ! comments_open( $post_id ) ) {
3553                         return new IXR_Error( 403, __( 'Sorry, comments are closed for this item.' ) );
3554                 }
3555
3556                 if ( empty( $content_struct['content'] ) ) {
3557                         return new IXR_Error( 403, __( 'Comment is required.' ) );
3558                 }
3559
3560                 $comment = array(
3561                         'comment_post_ID' => $post_id,
3562                         'comment_content' => $content_struct['content'],
3563                 );
3564
3565                 if ( $logged_in ) {
3566                         $display_name = $user->display_name;
3567                         $user_email = $user->user_email;
3568                         $user_url = $user->user_url;
3569
3570                         $comment['comment_author'] = $this->escape( $display_name );
3571                         $comment['comment_author_email'] = $this->escape( $user_email );
3572                         $comment['comment_author_url'] = $this->escape( $user_url );
3573                         $comment['user_ID'] = $user->ID;
3574                 } else {
3575                         $comment['comment_author'] = '';
3576                         if ( isset($content_struct['author']) )
3577                                 $comment['comment_author'] = $content_struct['author'];
3578
3579                         $comment['comment_author_email'] = '';
3580                         if ( isset($content_struct['author_email']) )
3581                                 $comment['comment_author_email'] = $content_struct['author_email'];
3582
3583                         $comment['comment_author_url'] = '';
3584                         if ( isset($content_struct['author_url']) )
3585                                 $comment['comment_author_url'] = $content_struct['author_url'];
3586
3587                         $comment['user_ID'] = 0;
3588
3589                         if ( get_option('require_name_email') ) {
3590                                 if ( 6 > strlen($comment['comment_author_email']) || '' == $comment['comment_author'] )
3591                                         return new IXR_Error( 403, __( 'Comment author name and email are required.' ) );
3592                                 elseif ( !is_email($comment['comment_author_email']) )
3593                                         return new IXR_Error( 403, __( 'A valid email address is required.' ) );
3594                         }
3595                 }
3596
3597                 $comment['comment_parent'] = isset($content_struct['comment_parent']) ? absint($content_struct['comment_parent']) : 0;
3598
3599                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3600                 do_action( 'xmlrpc_call', 'wp.newComment' );
3601
3602                 $comment_ID = wp_new_comment( $comment, true );
3603                 if ( is_wp_error( $comment_ID ) ) {
3604                         return new IXR_Error( 403, $comment_ID->get_error_message() );
3605                 }
3606
3607                 if ( ! $comment_ID ) {
3608                         return new IXR_Error( 403, __( 'An unknown error occurred' ) );
3609                 }
3610
3611                 /**
3612                  * Fires after a new comment has been successfully created via XML-RPC.
3613                  *
3614                  * @since 3.4.0
3615                  *
3616                  * @param int   $comment_ID ID of the new comment.
3617                  * @param array $args       An array of new comment arguments.
3618                  */
3619                 do_action( 'xmlrpc_call_success_wp_newComment', $comment_ID, $args );
3620
3621                 return $comment_ID;
3622         }
3623
3624         /**
3625          * Retrieve all of the comment status.
3626          *
3627          * @since 2.7.0
3628          *
3629          * @param array  $args {
3630          *     Method arguments. Note: arguments must be ordered as documented.
3631          *
3632          *     @type int    $blog_id (unused)
3633          *     @type string $username
3634          *     @type string $password
3635          * }
3636          * @return array|IXR_Error
3637          */
3638         public function wp_getCommentStatusList( $args ) {
3639                 $this->escape( $args );
3640
3641                 $username = $args[1];
3642                 $password = $args[2];
3643
3644                 if ( ! $user = $this->login( $username, $password ) ) {
3645                         return $this->error;
3646                 }
3647
3648                 if ( ! current_user_can( 'publish_posts' ) ) {
3649                         return new IXR_Error( 403, __( 'Sorry, you are not allowed access to details about this site.' ) );
3650                 }
3651
3652                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3653                 do_action( 'xmlrpc_call', 'wp.getCommentStatusList' );
3654
3655                 return get_comment_statuses();
3656         }
3657
3658         /**
3659          * Retrieve comment count.
3660          *
3661          * @since 2.5.0
3662          *
3663          * @param array  $args {
3664          *     Method arguments. Note: arguments must be ordered as documented.
3665          *
3666          *     @type int    $blog_id (unused)
3667          *     @type string $username
3668          *     @type string $password
3669          *     @type int    $post_id
3670          * }
3671          * @return array|IXR_Error
3672          */
3673         public function wp_getCommentCount( $args ) {
3674                 $this->escape( $args );
3675
3676                 $username       = $args[1];
3677                 $password       = $args[2];
3678                 $post_id        = (int) $args[3];
3679
3680                 if ( ! $user = $this->login( $username, $password ) ) {
3681                         return $this->error;
3682                 }
3683
3684                 $post = get_post( $post_id, ARRAY_A );
3685                 if ( empty( $post['ID'] ) ) {
3686                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
3687                 }
3688
3689                 if ( ! current_user_can( 'edit_post', $post_id ) ) {
3690                         return new IXR_Error( 403, __( 'Sorry, you are not allowed access to details of this post.' ) );
3691                 }
3692
3693                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3694                 do_action( 'xmlrpc_call', 'wp.getCommentCount' );
3695
3696                 $count = wp_count_comments( $post_id );
3697
3698                 return array(
3699                         'approved' => $count->approved,
3700                         'awaiting_moderation' => $count->moderated,
3701                         'spam' => $count->spam,
3702                         'total_comments' => $count->total_comments
3703                 );
3704         }
3705
3706         /**
3707          * Retrieve post statuses.
3708          *
3709          * @since 2.5.0
3710          *
3711          * @param array  $args {
3712          *     Method arguments. Note: arguments must be ordered as documented.
3713          *
3714          *     @type int    $blog_id (unused)
3715          *     @type string $username
3716          *     @type string $password
3717          * }
3718          * @return array|IXR_Error
3719          */
3720         public function wp_getPostStatusList( $args ) {
3721                 $this->escape( $args );
3722
3723                 $username = $args[1];
3724                 $password = $args[2];
3725
3726                 if ( !$user = $this->login($username, $password) )
3727                         return $this->error;
3728
3729                 if ( !current_user_can( 'edit_posts' ) )
3730                         return new IXR_Error( 403, __( 'Sorry, you are not allowed access to details about this site.' ) );
3731
3732                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3733                 do_action( 'xmlrpc_call', 'wp.getPostStatusList' );
3734
3735                 return get_post_statuses();
3736         }
3737
3738         /**
3739          * Retrieve page statuses.
3740          *
3741          * @since 2.5.0
3742          *
3743          * @param array  $args {
3744          *     Method arguments. Note: arguments must be ordered as documented.
3745          *
3746          *     @type int    $blog_id (unused)
3747          *     @type string $username
3748          *     @type string $password
3749          * }
3750          * @return array|IXR_Error
3751          */
3752         public function wp_getPageStatusList( $args ) {
3753                 $this->escape( $args );
3754
3755                 $username = $args[1];
3756                 $password = $args[2];
3757
3758                 if ( !$user = $this->login($username, $password) )
3759                         return $this->error;
3760
3761                 if ( !current_user_can( 'edit_pages' ) )
3762                         return new IXR_Error( 403, __( 'Sorry, you are not allowed access to details about this site.' ) );
3763
3764                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3765                 do_action( 'xmlrpc_call', 'wp.getPageStatusList' );
3766
3767                 return get_page_statuses();
3768         }
3769
3770         /**
3771          * Retrieve page templates.
3772          *
3773          * @since 2.6.0
3774          *
3775          * @param array  $args {
3776          *     Method arguments. Note: arguments must be ordered as documented.
3777          *
3778          *     @type int    $blog_id (unused)
3779          *     @type string $username
3780          *     @type string $password
3781          * }
3782          * @return array|IXR_Error
3783          */
3784         public function wp_getPageTemplates( $args ) {
3785                 $this->escape( $args );
3786
3787                 $username = $args[1];
3788                 $password = $args[2];
3789
3790                 if ( !$user = $this->login($username, $password) )
3791                         return $this->error;
3792
3793                 if ( !current_user_can( 'edit_pages' ) )
3794                         return new IXR_Error( 403, __( 'Sorry, you are not allowed access to details about this site.' ) );
3795
3796                 $templates = get_page_templates();
3797                 $templates['Default'] = 'default';
3798
3799                 return $templates;
3800         }
3801
3802         /**
3803          * Retrieve blog options.
3804          *
3805          * @since 2.6.0
3806          *
3807          * @param array  $args {
3808          *     Method arguments. Note: arguments must be ordered as documented.
3809          *
3810          *     @type int    $blog_id (unused)
3811          *     @type string $username
3812          *     @type string $password
3813          *     @type array  $options
3814          * }
3815          * @return array|IXR_Error
3816          */
3817         public function wp_getOptions( $args ) {
3818                 $this->escape( $args );
3819
3820                 $username       = $args[1];
3821                 $password       = $args[2];
3822                 $options        = isset( $args[3] ) ? (array) $args[3] : array();
3823
3824                 if ( !$user = $this->login($username, $password) )
3825                         return $this->error;
3826
3827                 // If no specific options where asked for, return all of them
3828                 if ( count( $options ) == 0 )
3829                         $options = array_keys($this->blog_options);
3830
3831                 return $this->_getOptions($options);
3832         }
3833
3834         /**
3835          * Retrieve blog options value from list.
3836          *
3837          * @since 2.6.0
3838          *
3839          * @param array $options Options to retrieve.
3840          * @return array
3841          */
3842         public function _getOptions($options) {
3843                 $data = array();
3844                 $can_manage = current_user_can( 'manage_options' );
3845                 foreach ( $options as $option ) {
3846                         if ( array_key_exists( $option, $this->blog_options ) ) {
3847                                 $data[$option] = $this->blog_options[$option];
3848                                 //Is the value static or dynamic?
3849                                 if ( isset( $data[$option]['option'] ) ) {
3850                                         $data[$option]['value'] = get_option( $data[$option]['option'] );
3851                                         unset($data[$option]['option']);
3852                                 }
3853
3854                                 if ( ! $can_manage )
3855                                         $data[$option]['readonly'] = true;
3856                         }
3857                 }
3858
3859                 return $data;
3860         }
3861
3862         /**
3863          * Update blog options.
3864          *
3865          * @since 2.6.0
3866          *
3867          * @param array  $args {
3868          *     Method arguments. Note: arguments must be ordered as documented.
3869          *
3870          *     @type int    $blog_id (unused)
3871          *     @type string $username
3872          *     @type string $password
3873          *     @type array  $options
3874          * }
3875          * @return array|IXR_Error
3876          */
3877         public function wp_setOptions( $args ) {
3878                 $this->escape( $args );
3879
3880                 $username       = $args[1];
3881                 $password       = $args[2];
3882                 $options        = (array) $args[3];
3883
3884                 if ( !$user = $this->login($username, $password) )
3885                         return $this->error;
3886
3887                 if ( !current_user_can( 'manage_options' ) )
3888                         return new IXR_Error( 403, __( 'Sorry, you are not allowed to update options.' ) );
3889
3890                 $option_names = array();
3891                 foreach ( $options as $o_name => $o_value ) {
3892                         $option_names[] = $o_name;
3893                         if ( !array_key_exists( $o_name, $this->blog_options ) )
3894                                 continue;
3895
3896                         if ( $this->blog_options[$o_name]['readonly'] == true )
3897                                 continue;
3898
3899                         update_option( $this->blog_options[$o_name]['option'], wp_unslash( $o_value ) );
3900                 }
3901
3902                 //Now return the updated values
3903                 return $this->_getOptions($option_names);
3904         }
3905
3906         /**
3907          * Retrieve a media item by ID
3908          *
3909          * @since 3.1.0
3910          *
3911          * @param array  $args {
3912          *     Method arguments. Note: arguments must be ordered as documented.
3913          *
3914          *     @type int    $blog_id (unused)
3915          *     @type string $username
3916          *     @type string $password
3917          *     @type int    $attachment_id
3918          * }
3919          * @return array|IXR_Error Associative array contains:
3920          *  - 'date_created_gmt'
3921          *  - 'parent'
3922          *  - 'link'
3923          *  - 'thumbnail'
3924          *  - 'title'
3925          *  - 'caption'
3926          *  - 'description'
3927          *  - 'metadata'
3928          */
3929         public function wp_getMediaItem( $args ) {
3930                 $this->escape( $args );
3931
3932                 $username               = $args[1];
3933                 $password               = $args[2];
3934                 $attachment_id  = (int) $args[3];
3935
3936                 if ( !$user = $this->login($username, $password) )
3937                         return $this->error;
3938
3939                 if ( !current_user_can( 'upload_files' ) )
3940                         return new IXR_Error( 403, __( 'Sorry, you are not allowed to upload files.' ) );
3941
3942                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3943                 do_action( 'xmlrpc_call', 'wp.getMediaItem' );
3944
3945                 if ( ! $attachment = get_post($attachment_id) )
3946                         return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
3947
3948                 return $this->_prepare_media_item( $attachment );
3949         }
3950
3951         /**
3952          * Retrieves a collection of media library items (or attachments)
3953          *
3954          * Besides the common blog_id (unused), username, and password arguments, it takes a filter
3955          * array as last argument.
3956          *
3957          * Accepted 'filter' keys are 'parent_id', 'mime_type', 'offset', and 'number'.
3958          *
3959          * The defaults are as follows:
3960          * - 'number' - Default is 5. Total number of media items to retrieve.
3961          * - 'offset' - Default is 0. See WP_Query::query() for more.
3962          * - 'parent_id' - Default is ''. The post where the media item is attached. Empty string shows all media items. 0 shows unattached media items.
3963          * - 'mime_type' - Default is ''. Filter by mime type (e.g., 'image/jpeg', 'application/pdf')
3964          *
3965          * @since 3.1.0
3966          *
3967          * @param array  $args {
3968          *     Method arguments. Note: arguments must be ordered as documented.
3969          *
3970          *     @type int    $blog_id (unused)
3971          *     @type string $username
3972          *     @type string $password
3973          *     @type array  $struct
3974          * }
3975          * @return array|IXR_Error Contains a collection of media items. See wp_xmlrpc_server::wp_getMediaItem() for a description of each item contents
3976          */
3977         public function wp_getMediaLibrary($args) {
3978                 $this->escape($args);
3979
3980                 $username       = $args[1];
3981                 $password       = $args[2];
3982                 $struct         = isset( $args[3] ) ? $args[3] : array() ;
3983
3984                 if ( !$user = $this->login($username, $password) )
3985                         return $this->error;
3986
3987                 if ( !current_user_can( 'upload_files' ) )
3988                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
3989
3990                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
3991                 do_action( 'xmlrpc_call', 'wp.getMediaLibrary' );
3992
3993                 $parent_id = ( isset($struct['parent_id']) ) ? absint($struct['parent_id']) : '' ;
3994                 $mime_type = ( isset($struct['mime_type']) ) ? $struct['mime_type'] : '' ;
3995                 $offset = ( isset($struct['offset']) ) ? absint($struct['offset']) : 0 ;
3996                 $number = ( isset($struct['number']) ) ? absint($struct['number']) : -1 ;
3997
3998                 $attachments = get_posts( array('post_type' => 'attachment', 'post_parent' => $parent_id, 'offset' => $offset, 'numberposts' => $number, 'post_mime_type' => $mime_type ) );
3999
4000                 $attachments_struct = array();
4001
4002                 foreach ($attachments as $attachment )
4003                         $attachments_struct[] = $this->_prepare_media_item( $attachment );
4004
4005                 return $attachments_struct;
4006         }
4007
4008         /**
4009          * Retrieves a list of post formats used by the site.
4010          *
4011          * @since 3.1.0
4012          *
4013          * @param array  $args {
4014          *     Method arguments. Note: arguments must be ordered as documented.
4015          *
4016          *     @type int    $blog_id (unused)
4017          *     @type string $username
4018          *     @type string $password
4019          * }
4020          * @return array|IXR_Error List of post formats, otherwise IXR_Error object.
4021          */
4022         public function wp_getPostFormats( $args ) {
4023                 $this->escape( $args );
4024
4025                 $username = $args[1];
4026                 $password = $args[2];
4027
4028                 if ( !$user = $this->login( $username, $password ) )
4029                         return $this->error;
4030
4031                 if ( !current_user_can( 'edit_posts' ) )
4032                         return new IXR_Error( 403, __( 'Sorry, you are not allowed access to details about this site.' ) );
4033
4034                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4035                 do_action( 'xmlrpc_call', 'wp.getPostFormats' );
4036
4037                 $formats = get_post_format_strings();
4038
4039                 // find out if they want a list of currently supports formats
4040                 if ( isset( $args[3] ) && is_array( $args[3] ) ) {
4041                         if ( $args[3]['show-supported'] ) {
4042                                 if ( current_theme_supports( 'post-formats' ) ) {
4043                                         $supported = get_theme_support( 'post-formats' );
4044
4045                                         $data = array();
4046                                         $data['all'] = $formats;
4047                                         $data['supported'] = $supported[0];
4048
4049                                         $formats = $data;
4050                                 }
4051                         }
4052                 }
4053
4054                 return $formats;
4055         }
4056
4057         /**
4058          * Retrieves a post type
4059          *
4060          * @since 3.4.0
4061          *
4062          * @see get_post_type_object()
4063          *
4064          * @param array  $args {
4065          *     Method arguments. Note: arguments must be ordered as documented.
4066          *
4067          *     @type int    $blog_id (unused)
4068          *     @type string $username
4069          *     @type string $password
4070          *     @type string $post_type_name
4071          *     @type array  $fields (optional)
4072          * }
4073          * @return array|IXR_Error Array contains:
4074          *  - 'labels'
4075          *  - 'description'
4076          *  - 'capability_type'
4077          *  - 'cap'
4078          *  - 'map_meta_cap'
4079          *  - 'hierarchical'
4080          *  - 'menu_position'
4081          *  - 'taxonomies'
4082          *  - 'supports'
4083          */
4084         public function wp_getPostType( $args ) {
4085                 if ( ! $this->minimum_args( $args, 4 ) )
4086                         return $this->error;
4087
4088                 $this->escape( $args );
4089
4090                 $username       = $args[1];
4091                 $password       = $args[2];
4092                 $post_type_name = $args[3];
4093
4094                 if ( isset( $args[4] ) ) {
4095                         $fields = $args[4];
4096                 } else {
4097                         /**
4098                          * Filters the default query fields used by the given XML-RPC method.
4099                          *
4100                          * @since 3.4.0
4101                          *
4102                          * @param array  $fields An array of post type query fields for the given method.
4103                          * @param string $method The method name.
4104                          */
4105                         $fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostType' );
4106                 }
4107
4108                 if ( !$user = $this->login( $username, $password ) )
4109                         return $this->error;
4110
4111                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4112                 do_action( 'xmlrpc_call', 'wp.getPostType' );
4113
4114                 if ( ! post_type_exists( $post_type_name ) )
4115                         return new IXR_Error( 403, __( 'Invalid post type.' ) );
4116
4117                 $post_type = get_post_type_object( $post_type_name );
4118
4119                 if ( ! current_user_can( $post_type->cap->edit_posts ) )
4120                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
4121
4122                 return $this->_prepare_post_type( $post_type, $fields );
4123         }
4124
4125         /**
4126          * Retrieves a post types
4127          *
4128          * @since 3.4.0
4129          *
4130          * @see get_post_types()
4131          *
4132          * @param array  $args {
4133          *     Method arguments. Note: arguments must be ordered as documented.
4134          *
4135          *     @type int    $blog_id (unused)
4136          *     @type string $username
4137          *     @type string $password
4138          *     @type array  $filter (optional)
4139          *     @type array  $fields (optional)
4140          * }
4141          * @return array|IXR_Error
4142          */
4143         public function wp_getPostTypes( $args ) {
4144                 if ( ! $this->minimum_args( $args, 3 ) )
4145                         return $this->error;
4146
4147                 $this->escape( $args );
4148
4149                 $username = $args[1];
4150                 $password = $args[2];
4151                 $filter   = isset( $args[3] ) ? $args[3] : array( 'public' => true );
4152
4153                 if ( isset( $args[4] ) ) {
4154                         $fields = $args[4];
4155                 } else {
4156                         /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4157                         $fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostTypes' );
4158                 }
4159
4160                 if ( ! $user = $this->login( $username, $password ) )
4161                         return $this->error;
4162
4163                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4164                 do_action( 'xmlrpc_call', 'wp.getPostTypes' );
4165
4166                 $post_types = get_post_types( $filter, 'objects' );
4167
4168                 $struct = array();
4169
4170                 foreach ( $post_types as $post_type ) {
4171                         if ( ! current_user_can( $post_type->cap->edit_posts ) )
4172                                 continue;
4173
4174                         $struct[$post_type->name] = $this->_prepare_post_type( $post_type, $fields );
4175                 }
4176
4177                 return $struct;
4178         }
4179
4180         /**
4181          * Retrieve revisions for a specific post.
4182          *
4183          * @since 3.5.0
4184          *
4185          * The optional $fields parameter specifies what fields will be included
4186          * in the response array.
4187          *
4188          * @uses wp_get_post_revisions()
4189          * @see wp_getPost() for more on $fields
4190          *
4191          * @param array  $args {
4192          *     Method arguments. Note: arguments must be ordered as documented.
4193          *
4194          *     @type int    $blog_id (unused)
4195          *     @type string $username
4196          *     @type string $password
4197          *     @type int    $post_id
4198          *     @type array  $fields (optional)
4199          * }
4200          * @return array|IXR_Error contains a collection of posts.
4201          */
4202         public function wp_getRevisions( $args ) {
4203                 if ( ! $this->minimum_args( $args, 4 ) )
4204                         return $this->error;
4205
4206                 $this->escape( $args );
4207
4208                 $username = $args[1];
4209                 $password = $args[2];
4210                 $post_id  = (int) $args[3];
4211
4212                 if ( isset( $args[4] ) ) {
4213                         $fields = $args[4];
4214                 } else {
4215                         /**
4216                          * Filters the default revision query fields used by the given XML-RPC method.
4217                          *
4218                          * @since 3.5.0
4219                          *
4220                          * @param array  $field  An array of revision query fields.
4221                          * @param string $method The method name.
4222                          */
4223                         $fields = apply_filters( 'xmlrpc_default_revision_fields', array( 'post_date', 'post_date_gmt' ), 'wp.getRevisions' );
4224                 }
4225
4226                 if ( ! $user = $this->login( $username, $password ) )
4227                         return $this->error;
4228
4229                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4230                 do_action( 'xmlrpc_call', 'wp.getRevisions' );
4231
4232                 if ( ! $post = get_post( $post_id ) )
4233                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4234
4235                 if ( ! current_user_can( 'edit_post', $post_id ) )
4236                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
4237
4238                 // Check if revisions are enabled.
4239                 if ( ! wp_revisions_enabled( $post ) )
4240                         return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
4241
4242                 $revisions = wp_get_post_revisions( $post_id );
4243
4244                 if ( ! $revisions )
4245                         return array();
4246
4247                 $struct = array();
4248
4249                 foreach ( $revisions as $revision ) {
4250                         if ( ! current_user_can( 'read_post', $revision->ID ) )
4251                                 continue;
4252
4253                         // Skip autosaves
4254                         if ( wp_is_post_autosave( $revision ) )
4255                                 continue;
4256
4257                         $struct[] = $this->_prepare_post( get_object_vars( $revision ), $fields );
4258                 }
4259
4260                 return $struct;
4261         }
4262
4263         /**
4264          * Restore a post revision
4265          *
4266          * @since 3.5.0
4267          *
4268          * @uses wp_restore_post_revision()
4269          *
4270          * @param array  $args {
4271          *     Method arguments. Note: arguments must be ordered as documented.
4272          *
4273          *     @type int    $blog_id (unused)
4274          *     @type string $username
4275          *     @type string $password
4276          *     @type int    $revision_id
4277          * }
4278          * @return bool|IXR_Error false if there was an error restoring, true if success.
4279          */
4280         public function wp_restoreRevision( $args ) {
4281                 if ( ! $this->minimum_args( $args, 3 ) )
4282                         return $this->error;
4283
4284                 $this->escape( $args );
4285
4286                 $username    = $args[1];
4287                 $password    = $args[2];
4288                 $revision_id = (int) $args[3];
4289
4290                 if ( ! $user = $this->login( $username, $password ) )
4291                         return $this->error;
4292
4293                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4294                 do_action( 'xmlrpc_call', 'wp.restoreRevision' );
4295
4296                 if ( ! $revision = wp_get_post_revision( $revision_id ) )
4297                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4298
4299                 if ( wp_is_post_autosave( $revision ) )
4300                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4301
4302                 if ( ! $post = get_post( $revision->post_parent ) )
4303                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4304
4305                 if ( ! current_user_can( 'edit_post', $revision->post_parent ) )
4306                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
4307
4308                 // Check if revisions are disabled.
4309                 if ( ! wp_revisions_enabled( $post ) )
4310                         return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
4311
4312                 $post = wp_restore_post_revision( $revision_id );
4313
4314                 return (bool) $post;
4315         }
4316
4317         /* Blogger API functions.
4318          * specs on http://plant.blogger.com/api and https://groups.yahoo.com/group/bloggerDev/
4319          */
4320
4321         /**
4322          * Retrieve blogs that user owns.
4323          *
4324          * Will make more sense once we support multiple blogs.
4325          *
4326          * @since 1.5.0
4327          *
4328          * @param array  $args {
4329          *     Method arguments. Note: arguments must be ordered as documented.
4330          *
4331          *     @type int    $blog_id (unused)
4332          *     @type string $username
4333          *     @type string $password
4334          * }
4335          * @return array|IXR_Error
4336          */
4337         public function blogger_getUsersBlogs($args) {
4338                 if ( ! $this->minimum_args( $args, 3 ) ) {
4339                         return $this->error;
4340                 }
4341
4342                 if ( is_multisite() ) {
4343                         return $this->_multisite_getUsersBlogs($args);
4344                 }
4345
4346                 $this->escape($args);
4347
4348                 $username = $args[1];
4349                 $password = $args[2];
4350
4351                 if ( !$user = $this->login($username, $password) )
4352                         return $this->error;
4353
4354                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4355                 do_action( 'xmlrpc_call', 'blogger.getUsersBlogs' );
4356
4357                 $is_admin = current_user_can('manage_options');
4358
4359                 $struct = array(
4360                         'isAdmin'  => $is_admin,
4361                         'url'      => get_option('home') . '/',
4362                         'blogid'   => '1',
4363                         'blogName' => get_option('blogname'),
4364                         'xmlrpc'   => site_url( 'xmlrpc.php', 'rpc' ),
4365                 );
4366
4367                 return array($struct);
4368         }
4369
4370         /**
4371          * Private function for retrieving a users blogs for multisite setups
4372          *
4373          * @since 3.0.0
4374          * @access protected
4375          *
4376          * @param array $args {
4377          *     Method arguments. Note: arguments must be ordered as documented.
4378          *
4379          *     @type string $username Username.
4380          *     @type string $password Password.
4381          * }
4382          * @return array|IXR_Error
4383          */
4384         protected function _multisite_getUsersBlogs( $args ) {
4385                 $current_blog = get_site();
4386
4387                 $domain = $current_blog->domain;
4388                 $path = $current_blog->path . 'xmlrpc.php';
4389
4390                 $rpc = new IXR_Client( set_url_scheme( "http://{$domain}{$path}" ) );
4391                 $rpc->query('wp.getUsersBlogs', $args[1], $args[2]);
4392                 $blogs = $rpc->getResponse();
4393
4394                 if ( isset($blogs['faultCode']) )
4395                         return new IXR_Error($blogs['faultCode'], $blogs['faultString']);
4396
4397                 if ( $_SERVER['HTTP_HOST'] == $domain && $_SERVER['REQUEST_URI'] == $path ) {
4398                         return $blogs;
4399                 } else {
4400                         foreach ( (array) $blogs as $blog ) {
4401                                 if ( strpos($blog['url'], $_SERVER['HTTP_HOST']) )
4402                                         return array($blog);
4403                         }
4404                         return array();
4405                 }
4406         }
4407
4408         /**
4409          * Retrieve user's data.
4410          *
4411          * Gives your client some info about you, so you don't have to.
4412          *
4413          * @since 1.5.0
4414          *
4415          * @param array  $args {
4416          *     Method arguments. Note: arguments must be ordered as documented.
4417          *
4418          *     @type int    $blog_id (unused)
4419          *     @type string $username
4420          *     @type string $password
4421          * }
4422          * @return array|IXR_Error
4423          */
4424         public function blogger_getUserInfo( $args ) {
4425                 $this->escape( $args );
4426
4427                 $username = $args[1];
4428                 $password = $args[2];
4429
4430                 if ( !$user = $this->login($username, $password) )
4431                         return $this->error;
4432
4433                 if ( !current_user_can( 'edit_posts' ) )
4434                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to access user data on this site.' ) );
4435
4436                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4437                 do_action( 'xmlrpc_call', 'blogger.getUserInfo' );
4438
4439                 $struct = array(
4440                         'nickname'  => $user->nickname,
4441                         'userid'    => $user->ID,
4442                         'url'       => $user->user_url,
4443                         'lastname'  => $user->last_name,
4444                         'firstname' => $user->first_name
4445                 );
4446
4447                 return $struct;
4448         }
4449
4450         /**
4451          * Retrieve post.
4452          *
4453          * @since 1.5.0
4454          *
4455          * @param array  $args {
4456          *     Method arguments. Note: arguments must be ordered as documented.
4457          *
4458          *     @type int    $blog_id (unused)
4459          *     @type int    $post_ID
4460          *     @type string $username
4461          *     @type string $password
4462          * }
4463          * @return array|IXR_Error
4464          */
4465         public function blogger_getPost( $args ) {
4466                 $this->escape( $args );
4467
4468                 $post_ID  = (int) $args[1];
4469                 $username = $args[2];
4470                 $password = $args[3];
4471
4472                 if ( !$user = $this->login($username, $password) )
4473                         return $this->error;
4474
4475                 $post_data = get_post($post_ID, ARRAY_A);
4476                 if ( ! $post_data )
4477                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
4478
4479                 if ( !current_user_can( 'edit_post', $post_ID ) )
4480                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
4481
4482                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4483                 do_action( 'xmlrpc_call', 'blogger.getPost' );
4484
4485                 $categories = implode(',', wp_get_post_categories($post_ID));
4486
4487                 $content  = '<title>'.wp_unslash($post_data['post_title']).'</title>';
4488                 $content .= '<category>'.$categories.'</category>';
4489                 $content .= wp_unslash($post_data['post_content']);
4490
4491                 $struct = array(
4492                         'userid'    => $post_data['post_author'],
4493                         'dateCreated' => $this->_convert_date( $post_data['post_date'] ),
4494                         'content'     => $content,
4495                         'postid'  => (string) $post_data['ID']
4496                 );
4497
4498                 return $struct;
4499         }
4500
4501         /**
4502          * Retrieve list of recent posts.
4503          *
4504          * @since 1.5.0
4505          *
4506          * @param array  $args {
4507          *     Method arguments. Note: arguments must be ordered as documented.
4508          *
4509          *     @type string $appkey (unused)
4510          *     @type int    $blog_id (unused)
4511          *     @type string $username
4512          *     @type string $password
4513          *     @type int    $numberposts (optional)
4514          * }
4515          * @return array|IXR_Error
4516          */
4517         public function blogger_getRecentPosts( $args ) {
4518
4519                 $this->escape($args);
4520
4521                 // $args[0] = appkey - ignored
4522                 $username = $args[2];
4523                 $password = $args[3];
4524                 if ( isset( $args[4] ) )
4525                         $query = array( 'numberposts' => absint( $args[4] ) );
4526                 else
4527                         $query = array();
4528
4529                 if ( !$user = $this->login($username, $password) )
4530                         return $this->error;
4531
4532                 if ( ! current_user_can( 'edit_posts' ) )
4533                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
4534
4535                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4536                 do_action( 'xmlrpc_call', 'blogger.getRecentPosts' );
4537
4538                 $posts_list = wp_get_recent_posts( $query );
4539
4540                 if ( !$posts_list ) {
4541                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
4542                         return $this->error;
4543                 }
4544
4545                 $recent_posts = array();
4546                 foreach ($posts_list as $entry) {
4547                         if ( !current_user_can( 'edit_post', $entry['ID'] ) )
4548                                 continue;
4549
4550                         $post_date  = $this->_convert_date( $entry['post_date'] );
4551                         $categories = implode(',', wp_get_post_categories($entry['ID']));
4552
4553                         $content  = '<title>'.wp_unslash($entry['post_title']).'</title>';
4554                         $content .= '<category>'.$categories.'</category>';
4555                         $content .= wp_unslash($entry['post_content']);
4556
4557                         $recent_posts[] = array(
4558                                 'userid' => $entry['post_author'],
4559                                 'dateCreated' => $post_date,
4560                                 'content' => $content,
4561                                 'postid' => (string) $entry['ID'],
4562                         );
4563                 }
4564
4565                 return $recent_posts;
4566         }
4567
4568         /**
4569          * Deprecated.
4570          *
4571          * @since 1.5.0
4572          * @deprecated 3.5.0
4573          *
4574          * @param array $args Unused.
4575          * @return IXR_Error Error object.
4576          */
4577         public function blogger_getTemplate($args) {
4578                 return new IXR_Error( 403, __('Sorry, that file cannot be edited.' ) );
4579         }
4580
4581         /**
4582          * Deprecated.
4583          *
4584          * @since 1.5.0
4585          * @deprecated 3.5.0
4586          *
4587          * @param array $args Unused.
4588          * @return IXR_Error Error object.
4589          */
4590         public function blogger_setTemplate($args) {
4591                 return new IXR_Error( 403, __('Sorry, that file cannot be edited.' ) );
4592         }
4593
4594         /**
4595          * Creates new post.
4596          *
4597          * @since 1.5.0
4598          *
4599          * @param array $args {
4600          *     Method arguments. Note: arguments must be ordered as documented.
4601          *
4602          *     @type string $appkey (unused)
4603          *     @type int    $blog_id (unused)
4604          *     @type string $username
4605          *     @type string $password
4606          *     @type string $content
4607          *     @type string $publish
4608          * }
4609          * @return int|IXR_Error
4610          */
4611         public function blogger_newPost( $args ) {
4612                 $this->escape( $args );
4613
4614                 $username = $args[2];
4615                 $password = $args[3];
4616                 $content  = $args[4];
4617                 $publish  = $args[5];
4618
4619                 if ( !$user = $this->login($username, $password) )
4620                         return $this->error;
4621
4622                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4623                 do_action( 'xmlrpc_call', 'blogger.newPost' );
4624
4625                 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
4626                 if ( ! current_user_can( get_post_type_object( 'post' )->cap->create_posts ) || !current_user_can($cap) )
4627                         return new IXR_Error(401, __('Sorry, you are not allowed to post on this site.'));
4628
4629                 $post_status = ($publish) ? 'publish' : 'draft';
4630
4631                 $post_author = $user->ID;
4632
4633                 $post_title = xmlrpc_getposttitle($content);
4634                 $post_category = xmlrpc_getpostcategory($content);
4635                 $post_content = xmlrpc_removepostdata($content);
4636
4637                 $post_date = current_time('mysql');
4638                 $post_date_gmt = current_time('mysql', 1);
4639
4640                 $post_data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status');
4641
4642                 $post_ID = wp_insert_post($post_data);
4643                 if ( is_wp_error( $post_ID ) )
4644                         return new IXR_Error(500, $post_ID->get_error_message());
4645
4646                 if ( !$post_ID )
4647                         return new IXR_Error(500, __('Sorry, your entry could not be posted.'));
4648
4649                 $this->attach_uploads( $post_ID, $post_content );
4650
4651                 /**
4652                  * Fires after a new post has been successfully created via the XML-RPC Blogger API.
4653                  *
4654                  * @since 3.4.0
4655                  *
4656                  * @param int   $post_ID ID of the new post.
4657                  * @param array $args    An array of new post arguments.
4658                  */
4659                 do_action( 'xmlrpc_call_success_blogger_newPost', $post_ID, $args );
4660
4661                 return $post_ID;
4662         }
4663
4664         /**
4665          * Edit a post.
4666          *
4667          * @since 1.5.0
4668          *
4669          * @param array  $args {
4670          *     Method arguments. Note: arguments must be ordered as documented.
4671          *
4672          *     @type int    $blog_id (unused)
4673          *     @type int    $post_ID
4674          *     @type string $username
4675          *     @type string $password
4676          *     @type string $content
4677          *     @type bool   $publish
4678          * }
4679          * @return true|IXR_Error true when done.
4680          */
4681         public function blogger_editPost( $args ) {
4682
4683                 $this->escape($args);
4684
4685                 $post_ID  = (int) $args[1];
4686                 $username = $args[2];
4687                 $password = $args[3];
4688                 $content  = $args[4];
4689                 $publish  = $args[5];
4690
4691                 if ( ! $user = $this->login( $username, $password ) ) {
4692                         return $this->error;
4693                 }
4694
4695                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4696                 do_action( 'xmlrpc_call', 'blogger.editPost' );
4697
4698                 $actual_post = get_post( $post_ID, ARRAY_A );
4699
4700                 if ( ! $actual_post || $actual_post['post_type'] != 'post' ) {
4701                         return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
4702                 }
4703
4704                 $this->escape($actual_post);
4705
4706                 if ( ! current_user_can( 'edit_post', $post_ID ) ) {
4707                         return new IXR_Error(401, __('Sorry, you are not allowed to edit this post.'));
4708                 }
4709                 if ( 'publish' == $actual_post['post_status'] && ! current_user_can( 'publish_posts' ) ) {
4710                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
4711                 }
4712
4713                 $postdata = array();
4714                 $postdata['ID'] = $actual_post['ID'];
4715                 $postdata['post_content'] = xmlrpc_removepostdata( $content );
4716                 $postdata['post_title'] = xmlrpc_getposttitle( $content );
4717                 $postdata['post_category'] = xmlrpc_getpostcategory( $content );
4718                 $postdata['post_status'] = $actual_post['post_status'];
4719                 $postdata['post_excerpt'] = $actual_post['post_excerpt'];
4720                 $postdata['post_status'] = $publish ? 'publish' : 'draft';
4721
4722                 $result = wp_update_post( $postdata );
4723
4724                 if ( ! $result ) {
4725                         return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be edited.'));
4726                 }
4727                 $this->attach_uploads( $actual_post['ID'], $postdata['post_content'] );
4728
4729                 /**
4730                  * Fires after a post has been successfully updated via the XML-RPC Blogger API.
4731                  *
4732                  * @since 3.4.0
4733                  *
4734                  * @param int   $post_ID ID of the updated post.
4735                  * @param array $args    An array of arguments for the post to edit.
4736                  */
4737                 do_action( 'xmlrpc_call_success_blogger_editPost', $post_ID, $args );
4738
4739                 return true;
4740         }
4741
4742         /**
4743          * Remove a post.
4744          *
4745          * @since 1.5.0
4746          *
4747          * @param array  $args {
4748          *     Method arguments. Note: arguments must be ordered as documented.
4749          *
4750          *     @type int    $blog_id (unused)
4751          *     @type int    $post_ID
4752          *     @type string $username
4753          *     @type string $password
4754          * }
4755          * @return true|IXR_Error True when post is deleted.
4756          */
4757         public function blogger_deletePost( $args ) {
4758                 $this->escape( $args );
4759
4760                 $post_ID  = (int) $args[1];
4761                 $username = $args[2];
4762                 $password = $args[3];
4763
4764                 if ( !$user = $this->login($username, $password) )
4765                         return $this->error;
4766
4767                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4768                 do_action( 'xmlrpc_call', 'blogger.deletePost' );
4769
4770                 $actual_post = get_post( $post_ID, ARRAY_A );
4771
4772                 if ( ! $actual_post || $actual_post['post_type'] != 'post' ) {
4773                         return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
4774                 }
4775
4776                 if ( ! current_user_can( 'delete_post', $post_ID ) ) {
4777                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
4778                 }
4779
4780                 $result = wp_delete_post( $post_ID );
4781
4782                 if ( ! $result ) {
4783                         return new IXR_Error( 500, __( 'The post cannot be deleted.' ) );
4784                 }
4785
4786                 /**
4787                  * Fires after a post has been successfully deleted via the XML-RPC Blogger API.
4788                  *
4789                  * @since 3.4.0
4790                  *
4791                  * @param int   $post_ID ID of the deleted post.
4792                  * @param array $args    An array of arguments to delete the post.
4793                  */
4794                 do_action( 'xmlrpc_call_success_blogger_deletePost', $post_ID, $args );
4795
4796                 return true;
4797         }
4798
4799         /* MetaWeblog API functions
4800          * specs on wherever Dave Winer wants them to be
4801          */
4802
4803         /**
4804          * Create a new post.
4805          *
4806          * The 'content_struct' argument must contain:
4807          *  - title
4808          *  - description
4809          *  - mt_excerpt
4810          *  - mt_text_more
4811          *  - mt_keywords
4812          *  - mt_tb_ping_urls
4813          *  - categories
4814          *
4815          * Also, it can optionally contain:
4816          *  - wp_slug
4817          *  - wp_password
4818          *  - wp_page_parent_id
4819          *  - wp_page_order
4820          *  - wp_author_id
4821          *  - post_status | page_status - can be 'draft', 'private', 'publish', or 'pending'
4822          *  - mt_allow_comments - can be 'open' or 'closed'
4823          *  - mt_allow_pings - can be 'open' or 'closed'
4824          *  - date_created_gmt
4825          *  - dateCreated
4826          *  - wp_post_thumbnail
4827          *
4828          * @since 1.5.0
4829          *
4830          * @param array  $args {
4831          *     Method arguments. Note: arguments must be ordered as documented.
4832          *
4833          *     @type int    $blog_id (unused)
4834          *     @type string $username
4835          *     @type string $password
4836          *     @type array  $content_struct
4837          *     @type int    $publish
4838          * }
4839          * @return int|IXR_Error
4840          */
4841         public function mw_newPost($args) {
4842                 $this->escape($args);
4843
4844                 $username       = $args[1];
4845                 $password       = $args[2];
4846                 $content_struct = $args[3];
4847                 $publish        = isset( $args[4] ) ? $args[4] : 0;
4848
4849                 if ( !$user = $this->login($username, $password) )
4850                         return $this->error;
4851
4852                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
4853                 do_action( 'xmlrpc_call', 'metaWeblog.newPost' );
4854
4855                 $page_template = '';
4856                 if ( !empty( $content_struct['post_type'] ) ) {
4857                         if ( $content_struct['post_type'] == 'page' ) {
4858                                 if ( $publish )
4859                                         $cap  = 'publish_pages';
4860                                 elseif ( isset( $content_struct['page_status'] ) && 'publish' == $content_struct['page_status'] )
4861                                         $cap  = 'publish_pages';
4862                                 else
4863                                         $cap = 'edit_pages';
4864                                 $error_message = __( 'Sorry, you are not allowed to publish pages on this site.' );
4865                                 $post_type = 'page';
4866                                 if ( !empty( $content_struct['wp_page_template'] ) )
4867                                         $page_template = $content_struct['wp_page_template'];
4868                         } elseif ( $content_struct['post_type'] == 'post' ) {
4869                                 if ( $publish )
4870                                         $cap  = 'publish_posts';
4871                                 elseif ( isset( $content_struct['post_status'] ) && 'publish' == $content_struct['post_status'] )
4872                                         $cap  = 'publish_posts';
4873                                 else
4874                                         $cap = 'edit_posts';
4875                                 $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
4876                                 $post_type = 'post';
4877                         } else {
4878                                 // No other post_type values are allowed here
4879                                 return new IXR_Error( 401, __( 'Invalid post type.' ) );
4880                         }
4881                 } else {
4882                         if ( $publish )
4883                                 $cap  = 'publish_posts';
4884                         elseif ( isset( $content_struct['post_status'] ) && 'publish' == $content_struct['post_status'])
4885                                 $cap  = 'publish_posts';
4886                         else
4887                                 $cap = 'edit_posts';
4888                         $error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
4889                         $post_type = 'post';
4890                 }
4891
4892                 if ( ! current_user_can( get_post_type_object( $post_type )->cap->create_posts ) )
4893                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts on this site.' ) );
4894                 if ( !current_user_can( $cap ) )
4895                         return new IXR_Error( 401, $error_message );
4896
4897                 // Check for a valid post format if one was given
4898                 if ( isset( $content_struct['wp_post_format'] ) ) {
4899                         $content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
4900                         if ( !array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
4901                                 return new IXR_Error( 404, __( 'Invalid post format.' ) );
4902                         }
4903                 }
4904
4905                 // Let WordPress generate the post_name (slug) unless
4906                 // one has been provided.
4907                 $post_name = "";
4908                 if ( isset($content_struct['wp_slug']) )
4909                         $post_name = $content_struct['wp_slug'];
4910
4911                 // Only use a password if one was given.
4912                 if ( isset($content_struct['wp_password']) )
4913                         $post_password = $content_struct['wp_password'];
4914
4915                 // Only set a post parent if one was provided.
4916                 if ( isset($content_struct['wp_page_parent_id']) )
4917                         $post_parent = $content_struct['wp_page_parent_id'];
4918
4919                 // Only set the menu_order if it was provided.
4920                 if ( isset($content_struct['wp_page_order']) )
4921                         $menu_order = $content_struct['wp_page_order'];
4922
4923                 $post_author = $user->ID;
4924
4925                 // If an author id was provided then use it instead.
4926                 if ( isset( $content_struct['wp_author_id'] ) && ( $user->ID != $content_struct['wp_author_id'] ) ) {
4927                         switch ( $post_type ) {
4928                                 case "post":
4929                                         if ( !current_user_can( 'edit_others_posts' ) )
4930                                                 return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
4931                                         break;
4932                                 case "page":
4933                                         if ( !current_user_can( 'edit_others_pages' ) )
4934                                                 return new IXR_Error( 401, __( 'Sorry, you are not allowed to create pages as this user.' ) );
4935                                         break;
4936                                 default:
4937                                         return new IXR_Error( 401, __( 'Invalid post type.' ) );
4938                         }
4939                         $author = get_userdata( $content_struct['wp_author_id'] );
4940                         if ( ! $author )
4941                                 return new IXR_Error( 404, __( 'Invalid author ID.' ) );
4942                         $post_author = $content_struct['wp_author_id'];
4943                 }
4944
4945                 $post_title = isset( $content_struct['title'] ) ? $content_struct['title'] : null;
4946                 $post_content = isset( $content_struct['description'] ) ? $content_struct['description'] : null;
4947
4948                 $post_status = $publish ? 'publish' : 'draft';
4949
4950                 if ( isset( $content_struct["{$post_type}_status"] ) ) {
4951                         switch ( $content_struct["{$post_type}_status"] ) {
4952                                 case 'draft':
4953                                 case 'pending':
4954                                 case 'private':
4955                                 case 'publish':
4956                                         $post_status = $content_struct["{$post_type}_status"];
4957                                         break;
4958                                 default:
4959                                         $post_status = $publish ? 'publish' : 'draft';
4960                                         break;
4961                         }
4962                 }
4963
4964                 $post_excerpt = isset($content_struct['mt_excerpt']) ? $content_struct['mt_excerpt'] : null;
4965                 $post_more = isset($content_struct['mt_text_more']) ? $content_struct['mt_text_more'] : null;
4966
4967                 $tags_input = isset($content_struct['mt_keywords']) ? $content_struct['mt_keywords'] : null;
4968
4969                 if ( isset($content_struct['mt_allow_comments']) ) {
4970                         if ( !is_numeric($content_struct['mt_allow_comments']) ) {
4971                                 switch ( $content_struct['mt_allow_comments'] ) {
4972                                         case 'closed':
4973                                                 $comment_status = 'closed';
4974                                                 break;
4975                                         case 'open':
4976                                                 $comment_status = 'open';
4977                                                 break;
4978                                         default:
4979                                                 $comment_status = get_default_comment_status( $post_type );
4980                                                 break;
4981                                 }
4982                         } else {
4983                                 switch ( (int) $content_struct['mt_allow_comments'] ) {
4984                                         case 0:
4985                                         case 2:
4986                                                 $comment_status = 'closed';
4987                                                 break;
4988                                         case 1:
4989                                                 $comment_status = 'open';
4990                                                 break;
4991                                         default:
4992                                                 $comment_status = get_default_comment_status( $post_type );
4993                                                 break;
4994                                 }
4995                         }
4996                 } else {
4997                         $comment_status = get_default_comment_status( $post_type );
4998                 }
4999
5000                 if ( isset($content_struct['mt_allow_pings']) ) {
5001                         if ( !is_numeric($content_struct['mt_allow_pings']) ) {
5002                                 switch ( $content_struct['mt_allow_pings'] ) {
5003                                         case 'closed':
5004                                                 $ping_status = 'closed';
5005                                                 break;
5006                                         case 'open':
5007                                                 $ping_status = 'open';
5008                                                 break;
5009                                         default:
5010                                                 $ping_status = get_default_comment_status( $post_type, 'pingback' );
5011                                                 break;
5012                                 }
5013                         } else {
5014                                 switch ( (int) $content_struct['mt_allow_pings'] ) {
5015                                         case 0:
5016                                                 $ping_status = 'closed';
5017                                                 break;
5018                                         case 1:
5019                                                 $ping_status = 'open';
5020                                                 break;
5021                                         default:
5022                                                 $ping_status = get_default_comment_status( $post_type, 'pingback' );
5023                                                 break;
5024                                 }
5025                         }
5026                 } else {
5027                         $ping_status = get_default_comment_status( $post_type, 'pingback' );
5028                 }
5029
5030                 if ( $post_more )
5031                         $post_content = $post_content . '<!--more-->' . $post_more;
5032
5033                 $to_ping = null;
5034                 if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
5035                         $to_ping = $content_struct['mt_tb_ping_urls'];
5036                         if ( is_array($to_ping) )
5037                                 $to_ping = implode(' ', $to_ping);
5038                 }
5039
5040                 // Do some timestamp voodoo
5041                 if ( !empty( $content_struct['date_created_gmt'] ) )
5042                         // We know this is supposed to be GMT, so we're going to slap that Z on there by force
5043                         $dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
5044                 elseif ( !empty( $content_struct['dateCreated']) )
5045                         $dateCreated = $content_struct['dateCreated']->getIso();
5046
5047                 if ( !empty( $dateCreated ) ) {
5048                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
5049                         $post_date_gmt = iso8601_to_datetime($dateCreated, 'GMT');
5050                 } else {
5051                         $post_date = '';
5052                         $post_date_gmt = '';
5053                 }
5054
5055                 $post_category = array();
5056                 if ( isset( $content_struct['categories'] ) ) {
5057                         $catnames = $content_struct['categories'];
5058
5059                         if ( is_array($catnames) ) {
5060                                 foreach ($catnames as $cat) {
5061                                         $post_category[] = get_cat_ID($cat);
5062                                 }
5063                         }
5064                 }
5065
5066                 $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');
5067
5068                 $post_ID = $postdata['ID'] = get_default_post_to_edit( $post_type, true )->ID;
5069
5070                 // Only posts can be sticky
5071                 if ( $post_type == 'post' && isset( $content_struct['sticky'] ) ) {
5072                         $data = $postdata;
5073                         $data['sticky'] = $content_struct['sticky'];
5074                         $error = $this->_toggle_sticky( $data );
5075                         if ( $error ) {
5076                                 return $error;
5077                         }
5078                 }
5079
5080                 if ( isset($content_struct['custom_fields']) )
5081                         $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
5082
5083                 if ( isset ( $content_struct['wp_post_thumbnail'] ) ) {
5084                         if ( set_post_thumbnail( $post_ID, $content_struct['wp_post_thumbnail'] ) === false )
5085                                 return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
5086
5087                         unset( $content_struct['wp_post_thumbnail'] );
5088                 }
5089
5090                 // Handle enclosures
5091                 $thisEnclosure = isset($content_struct['enclosure']) ? $content_struct['enclosure'] : null;
5092                 $this->add_enclosure_if_new($post_ID, $thisEnclosure);
5093
5094                 $this->attach_uploads( $post_ID, $post_content );
5095
5096                 // Handle post formats if assigned, value is validated earlier
5097                 // in this function
5098                 if ( isset( $content_struct['wp_post_format'] ) )
5099                         set_post_format( $post_ID, $content_struct['wp_post_format'] );
5100
5101                 $post_ID = wp_insert_post( $postdata, true );
5102                 if ( is_wp_error( $post_ID ) )
5103                         return new IXR_Error(500, $post_ID->get_error_message());
5104
5105                 if ( !$post_ID )
5106                         return new IXR_Error(500, __('Sorry, your entry could not be posted.'));
5107
5108                 /**
5109                  * Fires after a new post has been successfully created via the XML-RPC MovableType API.
5110                  *
5111                  * @since 3.4.0
5112                  *
5113                  * @param int   $post_ID ID of the new post.
5114                  * @param array $args    An array of arguments to create the new post.
5115                  */
5116                 do_action( 'xmlrpc_call_success_mw_newPost', $post_ID, $args );
5117
5118                 return strval($post_ID);
5119         }
5120
5121         /**
5122          * Adds an enclosure to a post if it's new.
5123          *
5124          * @since 2.8.0
5125          *
5126          * @param integer $post_ID   Post ID.
5127          * @param array   $enclosure Enclosure data.
5128          */
5129         public function add_enclosure_if_new( $post_ID, $enclosure ) {
5130                 if ( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
5131                         $encstring = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'] . "\n";
5132                         $found = false;
5133                         if ( $enclosures = get_post_meta( $post_ID, 'enclosure' ) ) {
5134                                 foreach ( $enclosures as $enc ) {
5135                                         // This method used to omit the trailing new line. #23219
5136                                         if ( rtrim( $enc, "\n" ) == rtrim( $encstring, "\n" ) ) {
5137                                                 $found = true;
5138                                                 break;
5139                                         }
5140                                 }
5141                         }
5142                         if ( ! $found )
5143                                 add_post_meta( $post_ID, 'enclosure', $encstring );
5144                 }
5145         }
5146
5147         /**
5148          * Attach upload to a post.
5149          *
5150          * @since 2.1.0
5151          *
5152          * @global wpdb $wpdb WordPress database abstraction object.
5153          *
5154          * @param int $post_ID Post ID.
5155          * @param string $post_content Post Content for attachment.
5156          */
5157         public function attach_uploads( $post_ID, $post_content ) {
5158                 global $wpdb;
5159
5160                 // find any unattached files
5161                 $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '0' AND post_type = 'attachment'" );
5162                 if ( is_array( $attachments ) ) {
5163                         foreach ( $attachments as $file ) {
5164                                 if ( ! empty( $file->guid ) && strpos( $post_content, $file->guid ) !== false )
5165                                         $wpdb->update($wpdb->posts, array('post_parent' => $post_ID), array('ID' => $file->ID) );
5166                         }
5167                 }
5168         }
5169
5170         /**
5171          * Edit a post.
5172          *
5173          * @since 1.5.0
5174          *
5175          * @param array  $args {
5176          *     Method arguments. Note: arguments must be ordered as documented.
5177          *
5178          *     @type int    $blog_id (unused)
5179          *     @type string $username
5180          *     @type string $password
5181          *     @type array  $content_struct
5182          *     @type int    $publish
5183          * }
5184          * @return bool|IXR_Error True on success.
5185          */
5186         public function mw_editPost( $args ) {
5187                 $this->escape( $args );
5188
5189                 $post_ID        = (int) $args[0];
5190                 $username       = $args[1];
5191                 $password       = $args[2];
5192                 $content_struct = $args[3];
5193                 $publish        = isset( $args[4] ) ? $args[4] : 0;
5194
5195                 if ( ! $user = $this->login($username, $password) )
5196                         return $this->error;
5197
5198                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5199                 do_action( 'xmlrpc_call', 'metaWeblog.editPost' );
5200
5201                 $postdata = get_post( $post_ID, ARRAY_A );
5202
5203                 /*
5204                  * If there is no post data for the give post id, stop now and return an error.
5205                  * Otherwise a new post will be created (which was the old behavior).
5206                  */
5207                 if ( ! $postdata || empty( $postdata[ 'ID' ] ) )
5208                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
5209
5210                 if ( ! current_user_can( 'edit_post', $post_ID ) )
5211                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
5212
5213                 // Use wp.editPost to edit post types other than post and page.
5214                 if ( ! in_array( $postdata[ 'post_type' ], array( 'post', 'page' ) ) )
5215                         return new IXR_Error( 401, __( 'Invalid post type.' ) );
5216
5217                 // Thwart attempt to change the post type.
5218                 if ( ! empty( $content_struct[ 'post_type' ] ) && ( $content_struct['post_type'] != $postdata[ 'post_type' ] ) )
5219                         return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
5220
5221                 // Check for a valid post format if one was given
5222                 if ( isset( $content_struct['wp_post_format'] ) ) {
5223                         $content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
5224                         if ( !array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
5225                                 return new IXR_Error( 404, __( 'Invalid post format.' ) );
5226                         }
5227                 }
5228
5229                 $this->escape($postdata);
5230
5231                 $ID = $postdata['ID'];
5232                 $post_content = $postdata['post_content'];
5233                 $post_title = $postdata['post_title'];
5234                 $post_excerpt = $postdata['post_excerpt'];
5235                 $post_password = $postdata['post_password'];
5236                 $post_parent = $postdata['post_parent'];
5237                 $post_type = $postdata['post_type'];
5238                 $menu_order = $postdata['menu_order'];
5239
5240                 // Let WordPress manage slug if none was provided.
5241                 $post_name = $postdata['post_name'];
5242                 if ( isset($content_struct['wp_slug']) )
5243                         $post_name = $content_struct['wp_slug'];
5244
5245                 // Only use a password if one was given.
5246                 if ( isset($content_struct['wp_password']) )
5247                         $post_password = $content_struct['wp_password'];
5248
5249                 // Only set a post parent if one was given.
5250                 if ( isset($content_struct['wp_page_parent_id']) )
5251                         $post_parent = $content_struct['wp_page_parent_id'];
5252
5253                 // Only set the menu_order if it was given.
5254                 if ( isset($content_struct['wp_page_order']) )
5255                         $menu_order = $content_struct['wp_page_order'];
5256
5257                 $page_template = null;
5258                 if ( ! empty( $content_struct['wp_page_template'] ) && 'page' == $post_type )
5259                         $page_template = $content_struct['wp_page_template'];
5260
5261                 $post_author = $postdata['post_author'];
5262
5263                 // Only set the post_author if one is set.
5264                 if ( isset( $content_struct['wp_author_id'] ) ) {
5265                         // Check permissions if attempting to switch author to or from another user.
5266                         if ( $user->ID != $content_struct['wp_author_id'] || $user->ID != $post_author ) {
5267                                 switch ( $post_type ) {
5268                                         case 'post':
5269                                                 if ( ! current_user_can( 'edit_others_posts' ) ) {
5270                                                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the post author as this user.' ) );
5271                                                 }
5272                                                 break;
5273                                         case 'page':
5274                                                 if ( ! current_user_can( 'edit_others_pages' ) ) {
5275                                                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the page author as this user.' ) );
5276                                                 }
5277                                                 break;
5278                                         default:
5279                                                 return new IXR_Error( 401, __( 'Invalid post type.' ) );
5280                                 }
5281                                 $post_author = $content_struct['wp_author_id'];
5282                         }
5283                 }
5284
5285                 if ( isset($content_struct['mt_allow_comments']) ) {
5286                         if ( !is_numeric($content_struct['mt_allow_comments']) ) {
5287                                 switch ( $content_struct['mt_allow_comments'] ) {
5288                                         case 'closed':
5289                                                 $comment_status = 'closed';
5290                                                 break;
5291                                         case 'open':
5292                                                 $comment_status = 'open';
5293                                                 break;
5294                                         default:
5295                                                 $comment_status = get_default_comment_status( $post_type );
5296                                                 break;
5297                                 }
5298                         } else {
5299                                 switch ( (int) $content_struct['mt_allow_comments'] ) {
5300                                         case 0:
5301                                         case 2:
5302                                                 $comment_status = 'closed';
5303                                                 break;
5304                                         case 1:
5305                                                 $comment_status = 'open';
5306                                                 break;
5307                                         default:
5308                                                 $comment_status = get_default_comment_status( $post_type );
5309                                                 break;
5310                                 }
5311                         }
5312                 }
5313
5314                 if ( isset($content_struct['mt_allow_pings']) ) {
5315                         if ( !is_numeric($content_struct['mt_allow_pings']) ) {
5316                                 switch ( $content_struct['mt_allow_pings'] ) {
5317                                         case 'closed':
5318                                                 $ping_status = 'closed';
5319                                                 break;
5320                                         case 'open':
5321                                                 $ping_status = 'open';
5322                                                 break;
5323                                         default:
5324                                                 $ping_status = get_default_comment_status( $post_type, 'pingback' );
5325                                                 break;
5326                                 }
5327                         } else {
5328                                 switch ( (int) $content_struct["mt_allow_pings"] ) {
5329                                         case 0:
5330                                                 $ping_status = 'closed';
5331                                                 break;
5332                                         case 1:
5333                                                 $ping_status = 'open';
5334                                                 break;
5335                                         default:
5336                                                 $ping_status = get_default_comment_status( $post_type, 'pingback' );
5337                                                 break;
5338                                 }
5339                         }
5340                 }
5341
5342                 if ( isset( $content_struct['title'] ) )
5343                         $post_title =  $content_struct['title'];
5344
5345                 if ( isset( $content_struct['description'] ) )
5346                         $post_content = $content_struct['description'];
5347
5348                 $post_category = array();
5349                 if ( isset( $content_struct['categories'] ) ) {
5350                         $catnames = $content_struct['categories'];
5351                         if ( is_array($catnames) ) {
5352                                 foreach ($catnames as $cat) {
5353                                         $post_category[] = get_cat_ID($cat);
5354                                 }
5355                         }
5356                 }
5357
5358                 if ( isset( $content_struct['mt_excerpt'] ) )
5359                         $post_excerpt =  $content_struct['mt_excerpt'];
5360
5361                 $post_more = isset( $content_struct['mt_text_more'] ) ? $content_struct['mt_text_more'] : null;
5362
5363                 $post_status = $publish ? 'publish' : 'draft';
5364                 if ( isset( $content_struct["{$post_type}_status"] ) ) {
5365                         switch( $content_struct["{$post_type}_status"] ) {
5366                                 case 'draft':
5367                                 case 'pending':
5368                                 case 'private':
5369                                 case 'publish':
5370                                         $post_status = $content_struct["{$post_type}_status"];
5371                                         break;
5372                                 default:
5373                                         $post_status = $publish ? 'publish' : 'draft';
5374                                         break;
5375                         }
5376                 }
5377
5378                 $tags_input = isset( $content_struct['mt_keywords'] ) ? $content_struct['mt_keywords'] : null;
5379
5380                 if ( 'publish' == $post_status || 'private' == $post_status ) {
5381                         if ( 'page' == $post_type && ! current_user_can( 'publish_pages' ) ) {
5382                                 return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this page.' ) );
5383                         } elseif ( ! current_user_can( 'publish_posts' ) ) {
5384                                 return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
5385                         }
5386                 }
5387
5388                 if ( $post_more )
5389                         $post_content = $post_content . "<!--more-->" . $post_more;
5390
5391                 $to_ping = null;
5392                 if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
5393                         $to_ping = $content_struct['mt_tb_ping_urls'];
5394                         if ( is_array($to_ping) )
5395                                 $to_ping = implode(' ', $to_ping);
5396                 }
5397
5398                 // Do some timestamp voodoo.
5399                 if ( !empty( $content_struct['date_created_gmt'] ) )
5400                         // We know this is supposed to be GMT, so we're going to slap that Z on there by force.
5401                         $dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
5402                 elseif ( !empty( $content_struct['dateCreated']) )
5403                         $dateCreated = $content_struct['dateCreated']->getIso();
5404
5405                 // Default to not flagging the post date to be edited unless it's intentional.
5406                 $edit_date = false;
5407
5408                 if ( !empty( $dateCreated ) ) {
5409                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
5410                         $post_date_gmt = iso8601_to_datetime($dateCreated, 'GMT');
5411
5412                         // Flag the post date to be edited.
5413                         $edit_date = true;
5414                 } else {
5415                         $post_date     = $postdata['post_date'];
5416                         $post_date_gmt = $postdata['post_date_gmt'];
5417                 }
5418
5419                 // We've got all the data -- post it.
5420                 $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');
5421
5422                 $result = wp_update_post($newpost, true);
5423                 if ( is_wp_error( $result ) )
5424                         return new IXR_Error(500, $result->get_error_message());
5425
5426                 if ( !$result )
5427                         return new IXR_Error(500, __('Sorry, your entry could not be edited.'));
5428
5429                 // Only posts can be sticky
5430                 if ( $post_type == 'post' && isset( $content_struct['sticky'] ) ) {
5431                         $data = $newpost;
5432                         $data['sticky'] = $content_struct['sticky'];
5433                         $data['post_type'] = 'post';
5434                         $error = $this->_toggle_sticky( $data, true );
5435                         if ( $error ) {
5436                                 return $error;
5437                         }
5438                 }
5439
5440                 if ( isset($content_struct['custom_fields']) )
5441                         $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
5442
5443                 if ( isset ( $content_struct['wp_post_thumbnail'] ) ) {
5444
5445                         // Empty value deletes, non-empty value adds/updates.
5446                         if ( empty( $content_struct['wp_post_thumbnail'] ) ) {
5447                                 delete_post_thumbnail( $post_ID );
5448                         } else {
5449                                 if ( set_post_thumbnail( $post_ID, $content_struct['wp_post_thumbnail'] ) === false )
5450                                         return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
5451                         }
5452                         unset( $content_struct['wp_post_thumbnail'] );
5453                 }
5454
5455                 // Handle enclosures.
5456                 $thisEnclosure = isset($content_struct['enclosure']) ? $content_struct['enclosure'] : null;
5457                 $this->add_enclosure_if_new($post_ID, $thisEnclosure);
5458
5459                 $this->attach_uploads( $ID, $post_content );
5460
5461                 // Handle post formats if assigned, validation is handled earlier in this function.
5462                 if ( isset( $content_struct['wp_post_format'] ) )
5463                         set_post_format( $post_ID, $content_struct['wp_post_format'] );
5464
5465                 /**
5466                  * Fires after a post has been successfully updated via the XML-RPC MovableType API.
5467                  *
5468                  * @since 3.4.0
5469                  *
5470                  * @param int   $post_ID ID of the updated post.
5471                  * @param array $args    An array of arguments to update the post.
5472                  */
5473                 do_action( 'xmlrpc_call_success_mw_editPost', $post_ID, $args );
5474
5475                 return true;
5476         }
5477
5478         /**
5479          * Retrieve post.
5480          *
5481          * @since 1.5.0
5482          *
5483          * @param array  $args {
5484          *     Method arguments. Note: arguments must be ordered as documented.
5485          *
5486          *     @type int    $blog_id (unused)
5487          *     @type int    $post_ID
5488          *     @type string $username
5489          *     @type string $password
5490          * }
5491          * @return array|IXR_Error
5492          */
5493         public function mw_getPost( $args ) {
5494                 $this->escape( $args );
5495
5496                 $post_ID  = (int) $args[0];
5497                 $username = $args[1];
5498                 $password = $args[2];
5499
5500                 if ( !$user = $this->login($username, $password) )
5501                         return $this->error;
5502
5503                 $postdata = get_post($post_ID, ARRAY_A);
5504                 if ( ! $postdata )
5505                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
5506
5507                 if ( !current_user_can( 'edit_post', $post_ID ) )
5508                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
5509
5510                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5511                 do_action( 'xmlrpc_call', 'metaWeblog.getPost' );
5512
5513                 if ($postdata['post_date'] != '') {
5514                         $post_date = $this->_convert_date( $postdata['post_date'] );
5515                         $post_date_gmt = $this->_convert_date_gmt( $postdata['post_date_gmt'],  $postdata['post_date'] );
5516                         $post_modified = $this->_convert_date( $postdata['post_modified'] );
5517                         $post_modified_gmt = $this->_convert_date_gmt( $postdata['post_modified_gmt'], $postdata['post_modified'] );
5518
5519                         $categories = array();
5520                         $catids = wp_get_post_categories($post_ID);
5521                         foreach ($catids as $catid)
5522                                 $categories[] = get_cat_name($catid);
5523
5524                         $tagnames = array();
5525                         $tags = wp_get_post_tags( $post_ID );
5526                         if ( !empty( $tags ) ) {
5527                                 foreach ( $tags as $tag )
5528                                         $tagnames[] = $tag->name;
5529                                 $tagnames = implode( ', ', $tagnames );
5530                         } else {
5531                                 $tagnames = '';
5532                         }
5533
5534                         $post = get_extended($postdata['post_content']);
5535                         $link = get_permalink($postdata['ID']);
5536
5537                         // Get the author info.
5538                         $author = get_userdata($postdata['post_author']);
5539
5540                         $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
5541                         $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0;
5542
5543                         // Consider future posts as published
5544                         if ( $postdata['post_status'] === 'future' )
5545                                 $postdata['post_status'] = 'publish';
5546
5547                         // Get post format
5548                         $post_format = get_post_format( $post_ID );
5549                         if ( empty( $post_format ) )
5550                                 $post_format = 'standard';
5551
5552                         $sticky = false;
5553                         if ( is_sticky( $post_ID ) )
5554                                 $sticky = true;
5555
5556                         $enclosure = array();
5557                         foreach ( (array) get_post_custom($post_ID) as $key => $val) {
5558                                 if ($key == 'enclosure') {
5559                                         foreach ( (array) $val as $enc ) {
5560                                                 $encdata = explode("\n", $enc);
5561                                                 $enclosure['url'] = trim(htmlspecialchars($encdata[0]));
5562                                                 $enclosure['length'] = (int) trim($encdata[1]);
5563                                                 $enclosure['type'] = trim($encdata[2]);
5564                                                 break 2;
5565                                         }
5566                                 }
5567                         }
5568
5569                         $resp = array(
5570                                 'dateCreated' => $post_date,
5571                                 'userid' => $postdata['post_author'],
5572                                 'postid' => $postdata['ID'],
5573                                 'description' => $post['main'],
5574                                 'title' => $postdata['post_title'],
5575                                 'link' => $link,
5576                                 'permaLink' => $link,
5577                                 // commented out because no other tool seems to use this
5578                                 //            'content' => $entry['post_content'],
5579                                 'categories' => $categories,
5580                                 'mt_excerpt' => $postdata['post_excerpt'],
5581                                 'mt_text_more' => $post['extended'],
5582                                 'wp_more_text' => $post['more_text'],
5583                                 'mt_allow_comments' => $allow_comments,
5584                                 'mt_allow_pings' => $allow_pings,
5585                                 'mt_keywords' => $tagnames,
5586                                 'wp_slug' => $postdata['post_name'],
5587                                 'wp_password' => $postdata['post_password'],
5588                                 'wp_author_id' => (string) $author->ID,
5589                                 'wp_author_display_name' => $author->display_name,
5590                                 'date_created_gmt' => $post_date_gmt,
5591                                 'post_status' => $postdata['post_status'],
5592                                 'custom_fields' => $this->get_custom_fields($post_ID),
5593                                 'wp_post_format' => $post_format,
5594                                 'sticky' => $sticky,
5595                                 'date_modified' => $post_modified,
5596                                 'date_modified_gmt' => $post_modified_gmt
5597                         );
5598
5599                         if ( !empty($enclosure) ) $resp['enclosure'] = $enclosure;
5600
5601                         $resp['wp_post_thumbnail'] = get_post_thumbnail_id( $postdata['ID'] );
5602
5603                         return $resp;
5604                 } else {
5605                         return new IXR_Error(404, __('Sorry, no such post.'));
5606                 }
5607         }
5608
5609         /**
5610          * Retrieve list of recent posts.
5611          *
5612          * @since 1.5.0
5613          *
5614          * @param array  $args {
5615          *     Method arguments. Note: arguments must be ordered as documented.
5616          *
5617          *     @type int    $blog_id (unused)
5618          *     @type string $username
5619          *     @type string $password
5620          *     @type int    $numberposts
5621          * }
5622          * @return array|IXR_Error
5623          */
5624         public function mw_getRecentPosts( $args ) {
5625                 $this->escape( $args );
5626
5627                 $username = $args[1];
5628                 $password = $args[2];
5629                 if ( isset( $args[3] ) )
5630                         $query = array( 'numberposts' => absint( $args[3] ) );
5631                 else
5632                         $query = array();
5633
5634                 if ( !$user = $this->login($username, $password) )
5635                         return $this->error;
5636
5637                 if ( ! current_user_can( 'edit_posts' ) )
5638                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
5639
5640                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5641                 do_action( 'xmlrpc_call', 'metaWeblog.getRecentPosts' );
5642
5643                 $posts_list = wp_get_recent_posts( $query );
5644
5645                 if ( !$posts_list )
5646                         return array();
5647
5648                 $recent_posts = array();
5649                 foreach ($posts_list as $entry) {
5650                         if ( !current_user_can( 'edit_post', $entry['ID'] ) )
5651                                 continue;
5652
5653                         $post_date = $this->_convert_date( $entry['post_date'] );
5654                         $post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
5655                         $post_modified = $this->_convert_date( $entry['post_modified'] );
5656                         $post_modified_gmt = $this->_convert_date_gmt( $entry['post_modified_gmt'], $entry['post_modified'] );
5657
5658                         $categories = array();
5659                         $catids = wp_get_post_categories($entry['ID']);
5660                         foreach ( $catids as $catid )
5661                                 $categories[] = get_cat_name($catid);
5662
5663                         $tagnames = array();
5664                         $tags = wp_get_post_tags( $entry['ID'] );
5665                         if ( !empty( $tags ) ) {
5666                                 foreach ( $tags as $tag ) {
5667                                         $tagnames[] = $tag->name;
5668                                 }
5669                                 $tagnames = implode( ', ', $tagnames );
5670                         } else {
5671                                 $tagnames = '';
5672                         }
5673
5674                         $post = get_extended($entry['post_content']);
5675                         $link = get_permalink($entry['ID']);
5676
5677                         // Get the post author info.
5678                         $author = get_userdata($entry['post_author']);
5679
5680                         $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
5681                         $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0;
5682
5683                         // Consider future posts as published
5684                         if ( $entry['post_status'] === 'future' )
5685                                 $entry['post_status'] = 'publish';
5686
5687                         // Get post format
5688                         $post_format = get_post_format( $entry['ID'] );
5689                         if ( empty( $post_format ) )
5690                                 $post_format = 'standard';
5691
5692                         $recent_posts[] = array(
5693                                 'dateCreated' => $post_date,
5694                                 'userid' => $entry['post_author'],
5695                                 'postid' => (string) $entry['ID'],
5696                                 'description' => $post['main'],
5697                                 'title' => $entry['post_title'],
5698                                 'link' => $link,
5699                                 'permaLink' => $link,
5700                                 // commented out because no other tool seems to use this
5701                                 // 'content' => $entry['post_content'],
5702                                 'categories' => $categories,
5703                                 'mt_excerpt' => $entry['post_excerpt'],
5704                                 'mt_text_more' => $post['extended'],
5705                                 'wp_more_text' => $post['more_text'],
5706                                 'mt_allow_comments' => $allow_comments,
5707                                 'mt_allow_pings' => $allow_pings,
5708                                 'mt_keywords' => $tagnames,
5709                                 'wp_slug' => $entry['post_name'],
5710                                 'wp_password' => $entry['post_password'],
5711                                 'wp_author_id' => (string) $author->ID,
5712                                 'wp_author_display_name' => $author->display_name,
5713                                 'date_created_gmt' => $post_date_gmt,
5714                                 'post_status' => $entry['post_status'],
5715                                 'custom_fields' => $this->get_custom_fields($entry['ID']),
5716                                 'wp_post_format' => $post_format,
5717                                 'date_modified' => $post_modified,
5718                                 'date_modified_gmt' => $post_modified_gmt,
5719                                 'sticky' => ( $entry['post_type'] === 'post' && is_sticky( $entry['ID'] ) ),
5720                                 'wp_post_thumbnail' => get_post_thumbnail_id( $entry['ID'] )
5721                         );
5722                 }
5723
5724                 return $recent_posts;
5725         }
5726
5727         /**
5728          * Retrieve the list of categories on a given blog.
5729          *
5730          * @since 1.5.0
5731          *
5732          * @param array  $args {
5733          *     Method arguments. Note: arguments must be ordered as documented.
5734          *
5735          *     @type int    $blog_id (unused)
5736          *     @type string $username
5737          *     @type string $password
5738          * }
5739          * @return array|IXR_Error
5740          */
5741         public function mw_getCategories( $args ) {
5742                 $this->escape( $args );
5743
5744                 $username = $args[1];
5745                 $password = $args[2];
5746
5747                 if ( !$user = $this->login($username, $password) )
5748                         return $this->error;
5749
5750                 if ( !current_user_can( 'edit_posts' ) )
5751                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
5752
5753                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5754                 do_action( 'xmlrpc_call', 'metaWeblog.getCategories' );
5755
5756                 $categories_struct = array();
5757
5758                 if ( $cats = get_categories(array('get' => 'all')) ) {
5759                         foreach ( $cats as $cat ) {
5760                                 $struct = array();
5761                                 $struct['categoryId'] = $cat->term_id;
5762                                 $struct['parentId'] = $cat->parent;
5763                                 $struct['description'] = $cat->name;
5764                                 $struct['categoryDescription'] = $cat->description;
5765                                 $struct['categoryName'] = $cat->name;
5766                                 $struct['htmlUrl'] = esc_html(get_category_link($cat->term_id));
5767                                 $struct['rssUrl'] = esc_html(get_category_feed_link($cat->term_id, 'rss2'));
5768
5769                                 $categories_struct[] = $struct;
5770                         }
5771                 }
5772
5773                 return $categories_struct;
5774         }
5775
5776         /**
5777          * Uploads a file, following your settings.
5778          *
5779          * Adapted from a patch by Johann Richard.
5780          *
5781          * @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
5782          *
5783          * @since 1.5.0
5784          *
5785          * @global wpdb $wpdb WordPress database abstraction object.
5786          *
5787          * @param array  $args {
5788          *     Method arguments. Note: arguments must be ordered as documented.
5789          *
5790          *     @type int    $blog_id (unused)
5791          *     @type string $username
5792          *     @type string $password
5793          *     @type array  $data
5794          * }
5795          * @return array|IXR_Error
5796          */
5797         public function mw_newMediaObject( $args ) {
5798                 global $wpdb;
5799
5800                 $username = $this->escape( $args[1] );
5801                 $password = $this->escape( $args[2] );
5802                 $data     = $args[3];
5803
5804                 $name = sanitize_file_name( $data['name'] );
5805                 $type = $data['type'];
5806                 $bits = $data['bits'];
5807
5808                 if ( !$user = $this->login($username, $password) )
5809                         return $this->error;
5810
5811                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5812                 do_action( 'xmlrpc_call', 'metaWeblog.newMediaObject' );
5813
5814                 if ( !current_user_can('upload_files') ) {
5815                         $this->error = new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
5816                         return $this->error;
5817                 }
5818
5819                 if ( is_multisite() && upload_is_user_over_quota( false ) ) {
5820                         $this->error = new IXR_Error( 401, __( 'Sorry, you have used your space allocation.' ) );
5821                         return $this->error;
5822                 }
5823
5824                 /**
5825                  * Filters whether to preempt the XML-RPC media upload.
5826                  *
5827                  * Passing a truthy value will effectively short-circuit the media upload,
5828                  * returning that value as a 500 error instead.
5829                  *
5830                  * @since 2.1.0
5831                  *
5832                  * @param bool $error Whether to pre-empt the media upload. Default false.
5833                  */
5834                 if ( $upload_err = apply_filters( 'pre_upload_error', false ) ) {
5835                         return new IXR_Error( 500, $upload_err );
5836                 }
5837
5838                 $upload = wp_upload_bits($name, null, $bits);
5839                 if ( ! empty($upload['error']) ) {
5840                         /* translators: 1: file name, 2: error message */
5841                         $errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
5842                         return new IXR_Error( 500, $errorString );
5843                 }
5844                 // Construct the attachment array
5845                 $post_id = 0;
5846                 if ( ! empty( $data['post_id'] ) ) {
5847                         $post_id = (int) $data['post_id'];
5848
5849                         if ( ! current_user_can( 'edit_post', $post_id ) )
5850                                 return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
5851                 }
5852                 $attachment = array(
5853                         'post_title' => $name,
5854                         'post_content' => '',
5855                         'post_type' => 'attachment',
5856                         'post_parent' => $post_id,
5857                         'post_mime_type' => $type,
5858                         'guid' => $upload[ 'url' ]
5859                 );
5860
5861                 // Save the data
5862                 $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
5863                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
5864
5865                 /**
5866                  * Fires after a new attachment has been added via the XML-RPC MovableType API.
5867                  *
5868                  * @since 3.4.0
5869                  *
5870                  * @param int   $id   ID of the new attachment.
5871                  * @param array $args An array of arguments to add the attachment.
5872                  */
5873                 do_action( 'xmlrpc_call_success_mw_newMediaObject', $id, $args );
5874
5875                 $struct = $this->_prepare_media_item( get_post( $id ) );
5876
5877                 // Deprecated values
5878                 $struct['id']   = $struct['attachment_id'];
5879                 $struct['file'] = $struct['title'];
5880                 $struct['url']  = $struct['link'];
5881
5882                 return $struct;
5883         }
5884
5885         /* MovableType API functions
5886          * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
5887          */
5888
5889         /**
5890          * Retrieve the post titles of recent posts.
5891          *
5892          * @since 1.5.0
5893          *
5894          * @param array  $args {
5895          *     Method arguments. Note: arguments must be ordered as documented.
5896          *
5897          *     @type int    $blog_id (unused)
5898          *     @type string $username
5899          *     @type string $password
5900          *     @type int    $numberposts
5901          * }
5902          * @return array|IXR_Error
5903          */
5904         public function mt_getRecentPostTitles( $args ) {
5905                 $this->escape( $args );
5906
5907                 $username = $args[1];
5908                 $password = $args[2];
5909                 if ( isset( $args[3] ) )
5910                         $query = array( 'numberposts' => absint( $args[3] ) );
5911                 else
5912                         $query = array();
5913
5914                 if ( !$user = $this->login($username, $password) )
5915                         return $this->error;
5916
5917                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5918                 do_action( 'xmlrpc_call', 'mt.getRecentPostTitles' );
5919
5920                 $posts_list = wp_get_recent_posts( $query );
5921
5922                 if ( !$posts_list ) {
5923                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
5924                         return $this->error;
5925                 }
5926
5927                 $recent_posts = array();
5928
5929                 foreach ($posts_list as $entry) {
5930                         if ( !current_user_can( 'edit_post', $entry['ID'] ) )
5931                                 continue;
5932
5933                         $post_date = $this->_convert_date( $entry['post_date'] );
5934                         $post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
5935
5936                         $recent_posts[] = array(
5937                                 'dateCreated' => $post_date,
5938                                 'userid' => $entry['post_author'],
5939                                 'postid' => (string) $entry['ID'],
5940                                 'title' => $entry['post_title'],
5941                                 'post_status' => $entry['post_status'],
5942                                 'date_created_gmt' => $post_date_gmt
5943                         );
5944                 }
5945
5946                 return $recent_posts;
5947         }
5948
5949         /**
5950          * Retrieve list of all categories on blog.
5951          *
5952          * @since 1.5.0
5953          *
5954          * @param array  $args {
5955          *     Method arguments. Note: arguments must be ordered as documented.
5956          *
5957          *     @type int    $blog_id (unused)
5958          *     @type string $username
5959          *     @type string $password
5960          * }
5961          * @return array|IXR_Error
5962          */
5963         public function mt_getCategoryList( $args ) {
5964                 $this->escape( $args );
5965
5966                 $username = $args[1];
5967                 $password = $args[2];
5968
5969                 if ( !$user = $this->login($username, $password) )
5970                         return $this->error;
5971
5972                 if ( !current_user_can( 'edit_posts' ) )
5973                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
5974
5975                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
5976                 do_action( 'xmlrpc_call', 'mt.getCategoryList' );
5977
5978                 $categories_struct = array();
5979
5980                 if ( $cats = get_categories(array('hide_empty' => 0, 'hierarchical' => 0)) ) {
5981                         foreach ( $cats as $cat ) {
5982                                 $struct = array();
5983                                 $struct['categoryId'] = $cat->term_id;
5984                                 $struct['categoryName'] = $cat->name;
5985
5986                                 $categories_struct[] = $struct;
5987                         }
5988                 }
5989
5990                 return $categories_struct;
5991         }
5992
5993         /**
5994          * Retrieve post categories.
5995          *
5996          * @since 1.5.0
5997          *
5998          * @param array  $args {
5999          *     Method arguments. Note: arguments must be ordered as documented.
6000          *
6001          *     @type int    $post_ID
6002          *     @type string $username
6003          *     @type string $password
6004          * }
6005          * @return array|IXR_Error
6006          */
6007         public function mt_getPostCategories( $args ) {
6008                 $this->escape( $args );
6009
6010                 $post_ID  = (int) $args[0];
6011                 $username = $args[1];
6012                 $password = $args[2];
6013
6014                 if ( !$user = $this->login($username, $password) )
6015                         return $this->error;
6016
6017                 if ( ! get_post( $post_ID ) )
6018                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
6019
6020                 if ( !current_user_can( 'edit_post', $post_ID ) )
6021                         return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
6022
6023                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6024                 do_action( 'xmlrpc_call', 'mt.getPostCategories' );
6025
6026                 $categories = array();
6027                 $catids = wp_get_post_categories(intval($post_ID));
6028                 // first listed category will be the primary category
6029                 $isPrimary = true;
6030                 foreach ( $catids as $catid ) {
6031                         $categories[] = array(
6032                                 'categoryName' => get_cat_name($catid),
6033                                 'categoryId' => (string) $catid,
6034                                 'isPrimary' => $isPrimary
6035                         );
6036                         $isPrimary = false;
6037                 }
6038
6039                 return $categories;
6040         }
6041
6042         /**
6043          * Sets categories for a post.
6044          *
6045          * @since 1.5.0
6046          *
6047          * @param array  $args {
6048          *     Method arguments. Note: arguments must be ordered as documented.
6049          *
6050          *     @type int    $post_ID
6051          *     @type string $username
6052          *     @type string $password
6053          *     @type array  $categories
6054          * }
6055          * @return true|IXR_Error True on success.
6056          */
6057         public function mt_setPostCategories( $args ) {
6058                 $this->escape( $args );
6059
6060                 $post_ID    = (int) $args[0];
6061                 $username   = $args[1];
6062                 $password   = $args[2];
6063                 $categories = $args[3];
6064
6065                 if ( !$user = $this->login($username, $password) )
6066                         return $this->error;
6067
6068                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6069                 do_action( 'xmlrpc_call', 'mt.setPostCategories' );
6070
6071                 if ( ! get_post( $post_ID ) )
6072                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
6073
6074                 if ( !current_user_can('edit_post', $post_ID) )
6075                         return new IXR_Error(401, __('Sorry, you are not allowed to edit this post.'));
6076
6077                 $catids = array();
6078                 foreach ( $categories as $cat ) {
6079                         $catids[] = $cat['categoryId'];
6080                 }
6081
6082                 wp_set_post_categories($post_ID, $catids);
6083
6084                 return true;
6085         }
6086
6087         /**
6088          * Retrieve an array of methods supported by this server.
6089          *
6090          * @since 1.5.0
6091          *
6092          * @return array
6093          */
6094         public function mt_supportedMethods() {
6095                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6096                 do_action( 'xmlrpc_call', 'mt.supportedMethods' );
6097
6098                 return array_keys( $this->methods );
6099         }
6100
6101         /**
6102          * Retrieve an empty array because we don't support per-post text filters.
6103          *
6104          * @since 1.5.0
6105          */
6106         public function mt_supportedTextFilters() {
6107                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6108                 do_action( 'xmlrpc_call', 'mt.supportedTextFilters' );
6109
6110                 /**
6111                  * Filters the MoveableType text filters list for XML-RPC.
6112                  *
6113                  * @since 2.2.0
6114                  *
6115                  * @param array $filters An array of text filters.
6116                  */
6117                 return apply_filters( 'xmlrpc_text_filters', array() );
6118         }
6119
6120         /**
6121          * Retrieve trackbacks sent to a given post.
6122          *
6123          * @since 1.5.0
6124          *
6125          * @global wpdb $wpdb WordPress database abstraction object.
6126          *
6127          * @param int $post_ID
6128          * @return array|IXR_Error
6129          */
6130         public function mt_getTrackbackPings( $post_ID ) {
6131                 global $wpdb;
6132
6133                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6134                 do_action( 'xmlrpc_call', 'mt.getTrackbackPings' );
6135
6136                 $actual_post = get_post($post_ID, ARRAY_A);
6137
6138                 if ( !$actual_post )
6139                         return new IXR_Error(404, __('Sorry, no such post.'));
6140
6141                 $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) );
6142
6143                 if ( !$comments )
6144                         return array();
6145
6146                 $trackback_pings = array();
6147                 foreach ( $comments as $comment ) {
6148                         if ( 'trackback' == $comment->comment_type ) {
6149                                 $content = $comment->comment_content;
6150                                 $title = substr($content, 8, (strpos($content, '</strong>') - 8));
6151                                 $trackback_pings[] = array(
6152                                         'pingTitle' => $title,
6153                                         'pingURL'   => $comment->comment_author_url,
6154                                         'pingIP'    => $comment->comment_author_IP
6155                                 );
6156                         }
6157                 }
6158
6159                 return $trackback_pings;
6160         }
6161
6162         /**
6163          * Sets a post's publish status to 'publish'.
6164          *
6165          * @since 1.5.0
6166          *
6167          * @param array  $args {
6168          *     Method arguments. Note: arguments must be ordered as documented.
6169          *
6170          *     @type int    $post_ID
6171          *     @type string $username
6172          *     @type string $password
6173          * }
6174          * @return int|IXR_Error
6175          */
6176         public function mt_publishPost( $args ) {
6177                 $this->escape( $args );
6178
6179                 $post_ID  = (int) $args[0];
6180                 $username = $args[1];
6181                 $password = $args[2];
6182
6183                 if ( !$user = $this->login($username, $password) )
6184                         return $this->error;
6185
6186                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6187                 do_action( 'xmlrpc_call', 'mt.publishPost' );
6188
6189                 $postdata = get_post($post_ID, ARRAY_A);
6190                 if ( ! $postdata )
6191                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
6192
6193                 if ( !current_user_can('publish_posts') || !current_user_can('edit_post', $post_ID) )
6194                         return new IXR_Error(401, __('Sorry, you are not allowed to publish this post.'));
6195
6196                 $postdata['post_status'] = 'publish';
6197
6198                 // retain old cats
6199                 $cats = wp_get_post_categories($post_ID);
6200                 $postdata['post_category'] = $cats;
6201                 $this->escape($postdata);
6202
6203                 return wp_update_post( $postdata );
6204         }
6205
6206         /* PingBack functions
6207          * specs on www.hixie.ch/specs/pingback/pingback
6208          */
6209
6210         /**
6211          * Retrieves a pingback and registers it.
6212          *
6213          * @since 1.5.0
6214          *
6215          * @param array  $args {
6216          *     Method arguments. Note: arguments must be ordered as documented.
6217          *
6218          *     @type string $pagelinkedfrom
6219          *     @type string $pagelinkedto
6220          * }
6221          * @return string|IXR_Error
6222          */
6223         public function pingback_ping( $args ) {
6224                 global $wpdb;
6225
6226                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6227                 do_action( 'xmlrpc_call', 'pingback.ping' );
6228
6229                 $this->escape( $args );
6230
6231                 $pagelinkedfrom = str_replace( '&amp;', '&', $args[0] );
6232                 $pagelinkedto = str_replace( '&amp;', '&', $args[1] );
6233                 $pagelinkedto = str_replace( '&', '&amp;', $pagelinkedto );
6234
6235                 /**
6236                  * Filters the pingback source URI.
6237                  *
6238                  * @since 3.6.0
6239                  *
6240                  * @param string $pagelinkedfrom URI of the page linked from.
6241                  * @param string $pagelinkedto   URI of the page linked to.
6242                  */
6243                 $pagelinkedfrom = apply_filters( 'pingback_ping_source_uri', $pagelinkedfrom, $pagelinkedto );
6244
6245                 if ( ! $pagelinkedfrom )
6246                         return $this->pingback_error( 0, __( 'A valid URL was not provided.' ) );
6247
6248                 // Check if the page linked to is in our site
6249                 $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
6250                 if ( !$pos1 )
6251                         return $this->pingback_error( 0, __( 'Is there no link to us?' ) );
6252
6253                 // let's find which post is linked to
6254                 // FIXME: does url_to_postid() cover all these cases already?
6255                 //        if so, then let's use it and drop the old code.
6256                 $urltest = parse_url($pagelinkedto);
6257                 if ( $post_ID = url_to_postid($pagelinkedto) ) {
6258                         // $way
6259                 } elseif ( isset( $urltest['path'] ) && preg_match('#p/[0-9]{1,}#', $urltest['path'], $match) ) {
6260                         // the path defines the post_ID (archives/p/XXXX)
6261                         $blah = explode('/', $match[0]);
6262                         $post_ID = (int) $blah[1];
6263                 } elseif ( isset( $urltest['query'] ) && preg_match('#p=[0-9]{1,}#', $urltest['query'], $match) ) {
6264                         // the querystring defines the post_ID (?p=XXXX)
6265                         $blah = explode('=', $match[0]);
6266                         $post_ID = (int) $blah[1];
6267                 } elseif ( isset($urltest['fragment']) ) {
6268                         // an #anchor is there, it's either...
6269                         if ( intval($urltest['fragment']) ) {
6270                                 // ...an integer #XXXX (simplest case)
6271                                 $post_ID = (int) $urltest['fragment'];
6272                         } elseif ( preg_match('/post-[0-9]+/',$urltest['fragment']) ) {
6273                                 // ...a post id in the form 'post-###'
6274                                 $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
6275                         } elseif ( is_string($urltest['fragment']) ) {
6276                                 // ...or a string #title, a little more complicated
6277                                 $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
6278                                 $sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title );
6279                                 if (! ($post_ID = $wpdb->get_var($sql)) ) {
6280                                         // returning unknown error '0' is better than die()ing
6281                                         return $this->pingback_error( 0, '' );
6282                                 }
6283                         }
6284                 } else {
6285                         // TODO: Attempt to extract a post ID from the given URL
6286                         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.' ) );
6287                 }
6288                 $post_ID = (int) $post_ID;
6289
6290                 $post = get_post($post_ID);
6291
6292                 if ( !$post ) // Post_ID not found
6293                         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.' ) );
6294
6295                 if ( $post_ID == url_to_postid($pagelinkedfrom) )
6296                         return $this->pingback_error( 0, __( 'The source URL and the target URL cannot both point to the same resource.' ) );
6297
6298                 // Check if pings are on
6299                 if ( !pings_open($post) )
6300                         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.' ) );
6301
6302                 // Let's check that the remote site didn't already pingback this entry
6303                 if ( $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom) ) )
6304                         return $this->pingback_error( 48, __( 'The pingback has already been registered.' ) );
6305
6306                 // very stupid, but gives time to the 'from' server to publish !
6307                 sleep(1);
6308
6309                 $remote_ip = preg_replace( '/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR'] );
6310
6311                 /** This filter is documented in wp-includes/class-http.php */
6312                 $user_agent = apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ) );
6313
6314                 // Let's check the remote site
6315                 $http_api_args = array(
6316                         'timeout' => 10,
6317                         'redirection' => 0,
6318                         'limit_response_size' => 153600, // 150 KB
6319                         'user-agent' => "$user_agent; verifying pingback from $remote_ip",
6320                         'headers' => array(
6321                                 'X-Pingback-Forwarded-For' => $remote_ip,
6322                         ),
6323                 );
6324
6325                 $request = wp_safe_remote_get( $pagelinkedfrom, $http_api_args );
6326                 $remote_source = $remote_source_original = wp_remote_retrieve_body( $request );
6327
6328                 if ( ! $remote_source ) {
6329                         return $this->pingback_error( 16, __( 'The source URL does not exist.' ) );
6330                 }
6331
6332                 /**
6333                  * Filters the pingback remote source.
6334                  *
6335                  * @since 2.5.0
6336                  *
6337                  * @param string $remote_source Response source for the page linked from.
6338                  * @param string $pagelinkedto  URL of the page linked to.
6339                  */
6340                 $remote_source = apply_filters( 'pre_remote_source', $remote_source, $pagelinkedto );
6341
6342                 // Work around bug in strip_tags():
6343                 $remote_source = str_replace( '<!DOC', '<DOC', $remote_source );
6344                 $remote_source = preg_replace( '/[\r\n\t ]+/', ' ', $remote_source ); // normalize spaces
6345                 $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 );
6346
6347                 preg_match( '|<title>([^<]*?)</title>|is', $remote_source, $matchtitle );
6348                 $title = isset( $matchtitle[1] ) ? $matchtitle[1] : '';
6349                 if ( empty( $title ) ) {
6350                         return $this->pingback_error( 32, __( 'We cannot find a title on that page.' ) );
6351                 }
6352
6353                 $remote_source = strip_tags( $remote_source, '<a>' ); // just keep the tag we need
6354
6355                 $p = explode( "\n\n", $remote_source );
6356
6357                 $preg_target = preg_quote($pagelinkedto, '|');
6358
6359                 foreach ( $p as $para ) {
6360                         if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link?
6361                                 preg_match("|<a[^>]+?".$preg_target."[^>]*>([^>]+?)</a>|", $para, $context);
6362
6363                                 // If the URL isn't in a link context, keep looking
6364                                 if ( empty($context) )
6365                                         continue;
6366
6367                                 // We're going to use this fake tag to mark the context in a bit
6368                                 // the marker is needed in case the link text appears more than once in the paragraph
6369                                 $excerpt = preg_replace('|\</?wpcontext\>|', '', $para);
6370
6371                                 // prevent really long link text
6372                                 if ( strlen($context[1]) > 100 )
6373                                         $context[1] = substr($context[1], 0, 100) . '&#8230;';
6374
6375                                 $marker = '<wpcontext>'.$context[1].'</wpcontext>';    // set up our marker
6376                                 $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
6377                                 $excerpt = strip_tags($excerpt, '<wpcontext>');        // strip all tags but our context marker
6378                                 $excerpt = trim($excerpt);
6379                                 $preg_marker = preg_quote($marker, '|');
6380                                 $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
6381                                 $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
6382                                 break;
6383                         }
6384                 }
6385
6386                 if ( empty($context) ) // Link to target not found
6387                         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.' ) );
6388
6389                 $pagelinkedfrom = str_replace('&', '&amp;', $pagelinkedfrom);
6390
6391                 $context = '[&#8230;] ' . esc_html( $excerpt ) . ' [&#8230;]';
6392                 $pagelinkedfrom = $this->escape( $pagelinkedfrom );
6393
6394                 $comment_post_ID = (int) $post_ID;
6395                 $comment_author = $title;
6396                 $comment_author_email = '';
6397                 $this->escape($comment_author);
6398                 $comment_author_url = $pagelinkedfrom;
6399                 $comment_content = $context;
6400                 $this->escape($comment_content);
6401                 $comment_type = 'pingback';
6402
6403                 $commentdata = compact(
6404                         'comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email',
6405                         'comment_content', 'comment_type', 'remote_source', 'remote_source_original'
6406                 );
6407
6408                 $comment_ID = wp_new_comment($commentdata);
6409
6410                 /**
6411                  * Fires after a post pingback has been sent.
6412                  *
6413                  * @since 0.71
6414                  *
6415                  * @param int $comment_ID Comment ID.
6416                  */
6417                 do_action( 'pingback_post', $comment_ID );
6418
6419                 /* translators: 1: URL of the page linked from, 2: URL of the page linked to */
6420                 return sprintf( __( 'Pingback from %1$s to %2$s registered. Keep the web talking! :-)' ), $pagelinkedfrom, $pagelinkedto );
6421         }
6422
6423         /**
6424          * Retrieve array of URLs that pingbacked the given URL.
6425          *
6426          * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
6427          *
6428          * @since 1.5.0
6429          *
6430          * @global wpdb $wpdb WordPress database abstraction object.
6431          *
6432          * @param string $url
6433          * @return array|IXR_Error
6434          */
6435         public function pingback_extensions_getPingbacks( $url ) {
6436                 global $wpdb;
6437
6438                 /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
6439                 do_action( 'xmlrpc_call', 'pingback.extensions.getPingbacks' );
6440
6441                 $url = $this->escape( $url );
6442
6443                 $post_ID = url_to_postid($url);
6444                 if ( !$post_ID ) {
6445                         // We aren't sure that the resource is available and/or pingback enabled
6446                         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.' ) );
6447                 }
6448
6449                 $actual_post = get_post($post_ID, ARRAY_A);
6450
6451                 if ( !$actual_post ) {
6452                         // No such post = resource not found
6453                         return $this->pingback_error( 32, __('The specified target URL does not exist.' ) );
6454                 }
6455
6456                 $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) );
6457
6458                 if ( !$comments )
6459                         return array();
6460
6461                 $pingbacks = array();
6462                 foreach ( $comments as $comment ) {
6463                         if ( 'pingback' == $comment->comment_type )
6464                                 $pingbacks[] = $comment->comment_author_url;
6465                 }
6466
6467                 return $pingbacks;
6468         }
6469
6470         /**
6471          * Sends a pingback error based on the given error code and message.
6472          *
6473          * @since 3.6.0
6474          *
6475          * @param int    $code    Error code.
6476          * @param string $message Error message.
6477          * @return IXR_Error Error object.
6478          */
6479         protected function pingback_error( $code, $message ) {
6480                 /**
6481                  * Filters the XML-RPC pingback error return.
6482                  *
6483                  * @since 3.5.1
6484                  *
6485                  * @param IXR_Error $error An IXR_Error object containing the error code and message.
6486                  */
6487                 return apply_filters( 'xmlrpc_pingback_error', new IXR_Error( $code, $message ) );
6488         }
6489 }