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