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