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