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