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