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