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