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