WordPress.org

Make WordPress Core

Ticket #22540: class-wp-xmlrpc-server.php

File class-wp-xmlrpc-server.php, 148.1 KB (added by nidhi.patel, 7 months ago)

with updated patch to filter posts via category

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