]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - xmlrpc.php
Wordpress 2.8
[autoinstalls/wordpress.git] / xmlrpc.php
1 <?php
2 /**
3  * XML-RPC protocol support for WordPress
4  *
5  * @license GPL v2 <./license.txt>
6  * @package WordPress
7  */
8
9 /**
10  * Whether this is a XMLRPC Request
11  *
12  * @var bool
13  */
14 define('XMLRPC_REQUEST', true);
15
16 // Some browser-embedded clients send cookies. We don't want them.
17 $_COOKIE = array();
18
19 // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
20 // but we can do it ourself.
21 if ( !isset( $HTTP_RAW_POST_DATA ) ) {
22         $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
23 }
24
25 // fix for mozBlog and other cases where '<?xml' isn't on the very first line
26 if ( isset($HTTP_RAW_POST_DATA) )
27         $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
28
29 /** Include the bootstrap for setting up WordPress environment */
30 include('./wp-load.php');
31
32 if ( isset( $_GET['rsd'] ) ) { // http://archipelago.phrasewise.com/rsd
33 header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true);
34 ?>
35 <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
36 <rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
37   <service>
38     <engineName>WordPress</engineName>
39     <engineLink>http://wordpress.org/</engineLink>
40     <homePageLink><?php bloginfo_rss('url') ?></homePageLink>
41     <apis>
42       <api name="WordPress" blogID="1" preferred="true" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
43       <api name="Movable Type" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
44       <api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
45       <api name="Blogger" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php') ?>" />
46       <api name="Atom" blogID="" preferred="false" apiLink="<?php echo apply_filters('atom_service_url', site_url('wp-app.php/service') ) ?>" />
47     </apis>
48   </service>
49 </rsd>
50 <?php
51 exit;
52 }
53
54 include_once(ABSPATH . 'wp-admin/includes/admin.php');
55 include_once(ABSPATH . WPINC . '/class-IXR.php');
56
57 // Turn off all warnings and errors.
58 // error_reporting(0);
59
60 /**
61  * Posts submitted via the xmlrpc interface get that title
62  * @name post_default_title
63  * @var string
64  */
65 $post_default_title = "";
66
67 /**
68  * Whether to enable XMLRPC Logging.
69  *
70  * @name xmlrpc_logging
71  * @var int|bool
72  */
73 $xmlrpc_logging = 0;
74
75 /**
76  * logIO() - Writes logging info to a file.
77  *
78  * @uses $xmlrpc_logging
79  * @package WordPress
80  * @subpackage Logging
81  *
82  * @param string $io Whether input or output
83  * @param string $msg Information describing logging reason.
84  * @return bool Always return true
85  */
86 function logIO($io,$msg) {
87         global $xmlrpc_logging;
88         if ($xmlrpc_logging) {
89                 $fp = fopen("../xmlrpc.log","a+");
90                 $date = gmdate("Y-m-d H:i:s ");
91                 $iot = ($io == "I") ? " Input: " : " Output: ";
92                 fwrite($fp, "\n\n".$date.$iot.$msg);
93                 fclose($fp);
94         }
95         return true;
96 }
97
98 if ( isset($HTTP_RAW_POST_DATA) )
99         logIO("I", $HTTP_RAW_POST_DATA);
100
101 /**
102  * WordPress XMLRPC server implementation.
103  *
104  * Implements compatability for Blogger API, MetaWeblog API, MovableType, and
105  * pingback. Additional WordPress API for managing comments, pages, posts,
106  * options, etc.
107  *
108  * Since WordPress 2.6.0, WordPress XMLRPC server can be disabled in the
109  * administration panels.
110  *
111  * @package WordPress
112  * @subpackage Publishing
113  * @since 1.5.0
114  */
115 class wp_xmlrpc_server extends IXR_Server {
116
117         /**
118          * Register all of the XMLRPC methods that XMLRPC server understands.
119          *
120          * PHP4 constructor and sets up server and method property. Passes XMLRPC
121          * methods through the 'xmlrpc_methods' filter to allow plugins to extend
122          * or replace XMLRPC methods.
123          *
124          * @since 1.5.0
125          *
126          * @return wp_xmlrpc_server
127          */
128         function wp_xmlrpc_server() {
129                 $this->methods = array(
130                         // WordPress API
131                         'wp.getUsersBlogs'              => 'this:wp_getUsersBlogs',
132                         'wp.getPage'                    => 'this:wp_getPage',
133                         'wp.getPages'                   => 'this:wp_getPages',
134                         'wp.newPage'                    => 'this:wp_newPage',
135                         'wp.deletePage'                 => 'this:wp_deletePage',
136                         'wp.editPage'                   => 'this:wp_editPage',
137                         'wp.getPageList'                => 'this:wp_getPageList',
138                         'wp.getAuthors'                 => 'this:wp_getAuthors',
139                         'wp.getCategories'              => 'this:mw_getCategories',             // Alias
140                         'wp.getTags'                    => 'this:wp_getTags',
141                         'wp.newCategory'                => 'this:wp_newCategory',
142                         'wp.deleteCategory'             => 'this:wp_deleteCategory',
143                         'wp.suggestCategories'  => 'this:wp_suggestCategories',
144                         'wp.uploadFile'                 => 'this:mw_newMediaObject',    // Alias
145                         'wp.getCommentCount'    => 'this:wp_getCommentCount',
146                         'wp.getPostStatusList'  => 'this:wp_getPostStatusList',
147                         'wp.getPageStatusList'  => 'this:wp_getPageStatusList',
148                         'wp.getPageTemplates'   => 'this:wp_getPageTemplates',
149                         'wp.getOptions'                 => 'this:wp_getOptions',
150                         'wp.setOptions'                 => 'this:wp_setOptions',
151                         'wp.getComment'                 => 'this:wp_getComment',
152                         'wp.getComments'                => 'this:wp_getComments',
153                         'wp.deleteComment'              => 'this:wp_deleteComment',
154                         'wp.editComment'                => 'this:wp_editComment',
155                         'wp.newComment'                 => 'this:wp_newComment',
156                         'wp.getCommentStatusList' => 'this:wp_getCommentStatusList',
157
158                         // Blogger API
159                         'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
160                         'blogger.getUserInfo' => 'this:blogger_getUserInfo',
161                         'blogger.getPost' => 'this:blogger_getPost',
162                         'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
163                         'blogger.getTemplate' => 'this:blogger_getTemplate',
164                         'blogger.setTemplate' => 'this:blogger_setTemplate',
165                         'blogger.newPost' => 'this:blogger_newPost',
166                         'blogger.editPost' => 'this:blogger_editPost',
167                         'blogger.deletePost' => 'this:blogger_deletePost',
168
169                         // MetaWeblog API (with MT extensions to structs)
170                         'metaWeblog.newPost' => 'this:mw_newPost',
171                         'metaWeblog.editPost' => 'this:mw_editPost',
172                         'metaWeblog.getPost' => 'this:mw_getPost',
173                         'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
174                         'metaWeblog.getCategories' => 'this:mw_getCategories',
175                         'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',
176
177                         // MetaWeblog API aliases for Blogger API
178                         // see http://www.xmlrpc.com/stories/storyReader$2460
179                         'metaWeblog.deletePost' => 'this:blogger_deletePost',
180                         'metaWeblog.getTemplate' => 'this:blogger_getTemplate',
181                         'metaWeblog.setTemplate' => 'this:blogger_setTemplate',
182                         'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',
183
184                         // MovableType API
185                         'mt.getCategoryList' => 'this:mt_getCategoryList',
186                         'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
187                         'mt.getPostCategories' => 'this:mt_getPostCategories',
188                         'mt.setPostCategories' => 'this:mt_setPostCategories',
189                         'mt.supportedMethods' => 'this:mt_supportedMethods',
190                         'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
191                         'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
192                         'mt.publishPost' => 'this:mt_publishPost',
193
194                         // PingBack
195                         'pingback.ping' => 'this:pingback_ping',
196                         'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
197
198                         'demo.sayHello' => 'this:sayHello',
199                         'demo.addTwoNumbers' => 'this:addTwoNumbers'
200                 );
201
202                 $this->initialise_blog_option_info( );
203                 $this->methods = apply_filters('xmlrpc_methods', $this->methods);
204                 $this->IXR_Server($this->methods);
205         }
206
207         /**
208          * Test XMLRPC API by saying, "Hello!" to client.
209          *
210          * @since 1.5.0
211          *
212          * @param array $args Method Parameters.
213          * @return string
214          */
215         function sayHello($args) {
216                 return 'Hello!';
217         }
218
219         /**
220          * Test XMLRPC API by adding two numbers for client.
221          *
222          * @since 1.5.0
223          *
224          * @param array $args Method Parameters.
225          * @return int
226          */
227         function addTwoNumbers($args) {
228                 $number1 = $args[0];
229                 $number2 = $args[1];
230                 return $number1 + $number2;
231         }
232
233         /**
234          * Check user's credentials.
235          *
236          * @since 1.5.0
237          *
238          * @param string $user_login User's username.
239          * @param string $user_pass User's password.
240          * @return bool Whether authentication passed.
241          * @deprecated use wp_xmlrpc_server::login
242          * @see wp_xmlrpc_server::login
243          */
244         function login_pass_ok($user_login, $user_pass) {
245                 if ( !get_option( 'enable_xmlrpc' ) ) {
246                         $this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this blog.  An admin user can enable them at %s'),  admin_url('options-writing.php') ) );
247                         return false;
248                 }
249
250                 if (!user_pass_ok($user_login, $user_pass)) {
251                         $this->error = new IXR_Error(403, __('Bad login/pass combination.'));
252                         return false;
253                 }
254                 return true;
255         }
256
257         /**
258          * Log user in.
259          *
260          * @since 2.8
261          *
262          * @param string $username User's username.
263          * @param string $password User's password.
264          * @return mixed WP_User object if authentication passed, false otherwise
265          */
266         function login($username, $password) {
267                 if ( !get_option( 'enable_xmlrpc' ) ) {
268                         $this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this blog.  An admin user can enable them at %s'),  admin_url('options-writing.php') ) );
269                         return false;
270                 }
271
272                 $user = wp_authenticate($username, $password);
273
274                 if (is_wp_error($user)) {
275                         $this->error = new IXR_Error(403, __('Bad login/pass combination.'));
276                         return false;
277                 }
278
279                 set_current_user( $user->ID );
280                 return $user;
281         }
282
283         /**
284          * Sanitize string or array of strings for database.
285          *
286          * @since 1.5.2
287          *
288          * @param string|array $array Sanitize single string or array of strings.
289          * @return string|array Type matches $array and sanitized for the database.
290          */
291         function escape(&$array) {
292                 global $wpdb;
293
294                 if(!is_array($array)) {
295                         return($wpdb->escape($array));
296                 }
297                 else {
298                         foreach ( (array) $array as $k => $v ) {
299                                 if (is_array($v)) {
300                                         $this->escape($array[$k]);
301                                 } else if (is_object($v)) {
302                                         //skip
303                                 } else {
304                                         $array[$k] = $wpdb->escape($v);
305                                 }
306                         }
307                 }
308         }
309
310         /**
311          * Retrieve custom fields for post.
312          *
313          * @since 2.5.0
314          *
315          * @param int $post_id Post ID.
316          * @return array Custom fields, if exist.
317          */
318         function get_custom_fields($post_id) {
319                 $post_id = (int) $post_id;
320
321                 $custom_fields = array();
322
323                 foreach ( (array) has_meta($post_id) as $meta ) {
324                         // Don't expose protected fields.
325                         if ( strpos($meta['meta_key'], '_wp_') === 0 ) {
326                                 continue;
327                         }
328
329                         $custom_fields[] = array(
330                                 "id"    => $meta['meta_id'],
331                                 "key"   => $meta['meta_key'],
332                                 "value" => $meta['meta_value']
333                         );
334                 }
335
336                 return $custom_fields;
337         }
338
339         /**
340          * Set custom fields for post.
341          *
342          * @since 2.5.0
343          *
344          * @param int $post_id Post ID.
345          * @param array $fields Custom fields.
346          */
347         function set_custom_fields($post_id, $fields) {
348                 $post_id = (int) $post_id;
349
350                 foreach ( (array) $fields as $meta ) {
351                         if ( isset($meta['id']) ) {
352                                 $meta['id'] = (int) $meta['id'];
353
354                                 if ( isset($meta['key']) ) {
355                                         update_meta($meta['id'], $meta['key'], $meta['value']);
356                                 }
357                                 else {
358                                         delete_meta($meta['id']);
359                                 }
360                         }
361                         else {
362                                 $_POST['metakeyinput'] = $meta['key'];
363                                 $_POST['metavalue'] = $meta['value'];
364                                 add_meta($post_id);
365                         }
366                 }
367         }
368
369         /**
370          * Setup blog options property.
371          *
372          * Passes property through 'xmlrpc_blog_options' filter.
373          *
374          * @since 2.6.0
375          */
376         function initialise_blog_option_info( ) {
377                 global $wp_version;
378
379                 $this->blog_options = array(
380                         // Read only options
381                         'software_name'         => array(
382                                 'desc'                  => __( 'Software Name' ),
383                                 'readonly'              => true,
384                                 'value'                 => 'WordPress'
385                         ),
386                         'software_version'      => array(
387                                 'desc'                  => __( 'Software Version' ),
388                                 'readonly'              => true,
389                                 'value'                 => $wp_version
390                         ),
391                         'blog_url'                      => array(
392                                 'desc'                  => __( 'Blog URL' ),
393                                 'readonly'              => true,
394                                 'option'                => 'siteurl'
395                         ),
396
397                         // Updatable options
398                         'time_zone'                     => array(
399                                 'desc'                  => __( 'Time Zone' ),
400                                 'readonly'              => false,
401                                 'option'                => 'gmt_offset'
402                         ),
403                         'blog_title'            => array(
404                                 'desc'                  => __( 'Blog Title' ),
405                                 'readonly'              => false,
406                                 'option'                        => 'blogname'
407                         ),
408                         'blog_tagline'          => array(
409                                 'desc'                  => __( 'Blog Tagline' ),
410                                 'readonly'              => false,
411                                 'option'                => 'blogdescription'
412                         ),
413                         'date_format'           => array(
414                                 'desc'                  => __( 'Date Format' ),
415                                 'readonly'              => false,
416                                 'option'                => 'date_format'
417                         ),
418                         'time_format'           => array(
419                                 'desc'                  => __( 'Time Format' ),
420                                 'readonly'              => false,
421                                 'option'                => 'time_format'
422                         )
423                 );
424
425                 $this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options );
426         }
427
428         /**
429          * Retrieve the blogs of the user.
430          *
431          * @since 2.6.0
432          *
433          * @param array $args Method parameters.
434          * @return array
435          */
436         function wp_getUsersBlogs( $args ) {
437                 // If this isn't on WPMU then just use blogger_getUsersBlogs
438                 if( !function_exists( 'is_site_admin' ) ) {
439                         array_unshift( $args, 1 );
440                         return $this->blogger_getUsersBlogs( $args );
441                 }
442
443                 $this->escape( $args );
444
445                 $username = $args[0];
446                 $password = $args[1];
447
448                 if ( !$user = $this->login($username, $password) ) {
449                         return $this->error;
450                 }
451
452                 do_action( 'xmlrpc_call', 'wp.getUsersBlogs' );
453
454                 $blogs = (array) get_blogs_of_user( $user->ID );
455                 $struct = array( );
456
457                 foreach( $blogs as $blog ) {
458                         // Don't include blogs that aren't hosted at this site
459                         if( $blog->site_id != $current_site->id )
460                                 continue;
461
462                         $blog_id = $blog->userblog_id;
463                         switch_to_blog($blog_id);
464                         $is_admin = current_user_can('level_8');
465
466                         $struct[] = array(
467                                 'isAdmin'               => $is_admin,
468                                 'url'                   => get_option( 'home' ) . '/',
469                                 'blogid'                => $blog_id,
470                                 'blogName'              => get_option( 'blogname' ),
471                                 'xmlrpc'                => site_url( 'xmlrpc.php' )
472                         );
473
474                         restore_current_blog( );
475                 }
476
477                 return $struct;
478         }
479
480         /**
481          * Retrieve page.
482          *
483          * @since 2.2.0
484          *
485          * @param array $args Method parameters.
486          * @return array
487          */
488         function wp_getPage($args) {
489                 $this->escape($args);
490
491                 $blog_id        = (int) $args[0];
492                 $page_id        = (int) $args[1];
493                 $username       = $args[2];
494                 $password       = $args[3];
495
496                 if ( !$user = $this->login($username, $password) ) {
497                         return $this->error;
498                 }
499
500                 if( !current_user_can( 'edit_page', $page_id ) )
501                         return new IXR_Error( 401, __( 'Sorry, you cannot edit this page.' ) );
502
503                 do_action('xmlrpc_call', 'wp.getPage');
504
505                 // Lookup page info.
506                 $page = get_page($page_id);
507
508                 // If we found the page then format the data.
509                 if($page->ID && ($page->post_type == "page")) {
510                         // Get all of the page content and link.
511                         $full_page = get_extended($page->post_content);
512                         $link = post_permalink($page->ID);
513
514                         // Get info the page parent if there is one.
515                         $parent_title = "";
516                         if(!empty($page->post_parent)) {
517                                 $parent = get_page($page->post_parent);
518                                 $parent_title = $parent->post_title;
519                         }
520
521                         // Determine comment and ping settings.
522                         $allow_comments = comments_open($page->ID) ? 1 : 0;
523                         $allow_pings = pings_open($page->ID) ? 1 : 0;
524
525                         // Format page date.
526                         $page_date = mysql2date("Ymd\TH:i:s", $page->post_date, false);
527                         $page_date_gmt = mysql2date("Ymd\TH:i:s", $page->post_date_gmt, false);
528
529                         // Pull the categories info together.
530                         $categories = array();
531                         foreach(wp_get_post_categories($page->ID) as $cat_id) {
532                                 $categories[] = get_cat_name($cat_id);
533                         }
534
535                         // Get the author info.
536                         $author = get_userdata($page->post_author);
537
538                         $page_template = get_post_meta( $page->ID, '_wp_page_template', true );
539                         if( empty( $page_template ) )
540                                 $page_template = 'default';
541
542                         $page_struct = array(
543                                 "dateCreated"                   => new IXR_Date($page_date),
544                                 "userid"                                => $page->post_author,
545                                 "page_id"                               => $page->ID,
546                                 "page_status"                   => $page->post_status,
547                                 "description"                   => $full_page["main"],
548                                 "title"                                 => $page->post_title,
549                                 "link"                                  => $link,
550                                 "permaLink"                             => $link,
551                                 "categories"                    => $categories,
552                                 "excerpt"                               => $page->post_excerpt,
553                                 "text_more"                             => $full_page["extended"],
554                                 "mt_allow_comments"             => $allow_comments,
555                                 "mt_allow_pings"                => $allow_pings,
556                                 "wp_slug"                               => $page->post_name,
557                                 "wp_password"                   => $page->post_password,
558                                 "wp_author"                             => $author->display_name,
559                                 "wp_page_parent_id"             => $page->post_parent,
560                                 "wp_page_parent_title"  => $parent_title,
561                                 "wp_page_order"                 => $page->menu_order,
562                                 "wp_author_id"                  => $author->ID,
563                                 "wp_author_display_name"        => $author->display_name,
564                                 "date_created_gmt"              => new IXR_Date($page_date_gmt),
565                                 "custom_fields"                 => $this->get_custom_fields($page_id),
566                                 "wp_page_template"              => $page_template
567                         );
568
569                         return($page_struct);
570                 }
571                 // If the page doesn't exist indicate that.
572                 else {
573                         return(new IXR_Error(404, __("Sorry, no such page.")));
574                 }
575         }
576
577         /**
578          * Retrieve Pages.
579          *
580          * @since 2.2.0
581          *
582          * @param array $args Method parameters.
583          * @return array
584          */
585         function wp_getPages($args) {
586                 $this->escape($args);
587
588                 $blog_id        = (int) $args[0];
589                 $username       = $args[1];
590                 $password       = $args[2];
591                 $num_pages      = (int) $args[3];
592
593                 if ( !$user = $this->login($username, $password) ) {
594                         return $this->error;
595                 }
596
597                 if( !current_user_can( 'edit_pages' ) )
598                         return new IXR_Error( 401, __( 'Sorry, you cannot edit pages.' ) );
599
600                 do_action('xmlrpc_call', 'wp.getPages');
601
602                 $page_limit = 10;
603                 if( isset( $num_pages ) ) {
604                         $page_limit = $num_pages;
605                 }
606
607                 $pages = get_posts( array('post_type' => 'page', 'post_status' => 'all', 'numberposts' => $page_limit) );
608                 $num_pages = count($pages);
609
610                 // If we have pages, put together their info.
611                 if($num_pages >= 1) {
612                         $pages_struct = array();
613
614                         for($i = 0; $i < $num_pages; $i++) {
615                                 $page = wp_xmlrpc_server::wp_getPage(array(
616                                         $blog_id, $pages[$i]->ID, $username, $password
617                                 ));
618                                 $pages_struct[] = $page;
619                         }
620
621                         return($pages_struct);
622                 }
623                 // If no pages were found return an error.
624                 else {
625                         return(array());
626                 }
627         }
628
629         /**
630          * Create new page.
631          *
632          * @since 2.2.0
633          *
634          * @param array $args Method parameters.
635          * @return unknown
636          */
637         function wp_newPage($args) {
638                 // Items not escaped here will be escaped in newPost.
639                 $username       = $this->escape($args[1]);
640                 $password       = $this->escape($args[2]);
641                 $page           = $args[3];
642                 $publish        = $args[4];
643
644                 if ( !$user = $this->login($username, $password) ) {
645                         return $this->error;
646                 }
647
648                 do_action('xmlrpc_call', 'wp.newPage');
649
650                 // Make sure the user is allowed to add new pages.
651                 if(!current_user_can("publish_pages")) {
652                         return(new IXR_Error(401, __("Sorry, you cannot add new pages.")));
653                 }
654
655                 // Mark this as content for a page.
656                 $args[3]["post_type"] = "page";
657
658                 // Let mw_newPost do all of the heavy lifting.
659                 return($this->mw_newPost($args));
660         }
661
662         /**
663          * Delete page.
664          *
665          * @since 2.2.0
666          *
667          * @param array $args Method parameters.
668          * @return bool True, if success.
669          */
670         function wp_deletePage($args) {
671                 $this->escape($args);
672
673                 $blog_id        = (int) $args[0];
674                 $username       = $args[1];
675                 $password       = $args[2];
676                 $page_id        = (int) $args[3];
677
678                 if ( !$user = $this->login($username, $password) ) {
679                         return $this->error;
680                 }
681
682                 do_action('xmlrpc_call', 'wp.deletePage');
683
684                 // Get the current page based on the page_id and
685                 // make sure it is a page and not a post.
686                 $actual_page = wp_get_single_post($page_id, ARRAY_A);
687                 if(
688                         !$actual_page
689                         || ($actual_page["post_type"] != "page")
690                 ) {
691                         return(new IXR_Error(404, __("Sorry, no such page.")));
692                 }
693
694                 // Make sure the user can delete pages.
695                 if(!current_user_can("delete_page", $page_id)) {
696                         return(new IXR_Error(401, __("Sorry, you do not have the right to delete this page.")));
697                 }
698
699                 // Attempt to delete the page.
700                 $result = wp_delete_post($page_id);
701                 if(!$result) {
702                         return(new IXR_Error(500, __("Failed to delete the page.")));
703                 }
704
705                 return(true);
706         }
707
708         /**
709          * Edit page.
710          *
711          * @since 2.2.0
712          *
713          * @param array $args Method parameters.
714          * @return unknown
715          */
716         function wp_editPage($args) {
717                 // Items not escaped here will be escaped in editPost.
718                 $blog_id        = (int) $args[0];
719                 $page_id        = (int) $this->escape($args[1]);
720                 $username       = $this->escape($args[2]);
721                 $password       = $this->escape($args[3]);
722                 $content        = $args[4];
723                 $publish        = $args[5];
724
725                 if ( !$user = $this->login($username, $password) ) {
726                         return $this->error;
727                 }
728
729                 do_action('xmlrpc_call', 'wp.editPage');
730
731                 // Get the page data and make sure it is a page.
732                 $actual_page = wp_get_single_post($page_id, ARRAY_A);
733                 if(
734                         !$actual_page
735                         || ($actual_page["post_type"] != "page")
736                 ) {
737                         return(new IXR_Error(404, __("Sorry, no such page.")));
738                 }
739
740                 // Make sure the user is allowed to edit pages.
741                 if(!current_user_can("edit_page", $page_id)) {
742                         return(new IXR_Error(401, __("Sorry, you do not have the right to edit this page.")));
743                 }
744
745                 // Mark this as content for a page.
746                 $content["post_type"] = "page";
747
748                 // Arrange args in the way mw_editPost understands.
749                 $args = array(
750                         $page_id,
751                         $username,
752                         $password,
753                         $content,
754                         $publish
755                 );
756
757                 // Let mw_editPost do all of the heavy lifting.
758                 return($this->mw_editPost($args));
759         }
760
761         /**
762          * Retrieve page list.
763          *
764          * @since 2.2.0
765          *
766          * @param array $args Method parameters.
767          * @return unknown
768          */
769         function wp_getPageList($args) {
770                 global $wpdb;
771
772                 $this->escape($args);
773
774                 $blog_id                                = (int) $args[0];
775                 $username                               = $args[1];
776                 $password                               = $args[2];
777
778                 if ( !$user = $this->login($username, $password) ) {
779                         return $this->error;
780                 }
781
782                 if( !current_user_can( 'edit_pages' ) )
783                         return new IXR_Error( 401, __( 'Sorry, you cannot edit pages.' ) );
784
785                 do_action('xmlrpc_call', 'wp.getPageList');
786
787                 // Get list of pages ids and titles
788                 $page_list = $wpdb->get_results("
789                         SELECT ID page_id,
790                                 post_title page_title,
791                                 post_parent page_parent_id,
792                                 post_date_gmt,
793                                 post_date
794                         FROM {$wpdb->posts}
795                         WHERE post_type = 'page'
796                         ORDER BY ID
797                 ");
798
799                 // The date needs to be formated properly.
800                 $num_pages = count($page_list);
801                 for($i = 0; $i < $num_pages; $i++) {
802                         $post_date = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date, false);
803                         $post_date_gmt = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date_gmt, false);
804
805                         $page_list[$i]->dateCreated = new IXR_Date($post_date);
806                         $page_list[$i]->date_created_gmt = new IXR_Date($post_date_gmt);
807
808                         unset($page_list[$i]->post_date_gmt);
809                         unset($page_list[$i]->post_date);
810                 }
811
812                 return($page_list);
813         }
814
815         /**
816          * Retrieve authors list.
817          *
818          * @since 2.2.0
819          *
820          * @param array $args Method parameters.
821          * @return array
822          */
823         function wp_getAuthors($args) {
824
825                 $this->escape($args);
826
827                 $blog_id        = (int) $args[0];
828                 $username       = $args[1];
829                 $password       = $args[2];
830
831                 if ( !$user = $this->login($username, $password) ) {
832                         return $this->error;
833                 }
834
835                 if(!current_user_can("edit_posts")) {
836                         return(new IXR_Error(401, __("Sorry, you cannot edit posts on this blog.")));
837                 }
838
839                 do_action('xmlrpc_call', 'wp.getAuthors');
840
841                 $authors = array();
842                 foreach( (array) get_users_of_blog() as $row ) {
843                         $authors[] = array(
844                                 "user_id"       => $row->user_id,
845                                 "user_login"    => $row->user_login,
846                                 "display_name"  => $row->display_name
847                         );
848                 }
849
850                 return($authors);
851         }
852
853         /**
854          * Get list of all tags
855          *
856          * @since 2.7
857          *
858          * @param array $args Method parameters.
859          * @return array
860          */
861         function wp_getTags( $args ) {
862                 $this->escape( $args );
863
864                 $blog_id                = (int) $args[0];
865                 $username               = $args[1];
866                 $password               = $args[2];
867
868                 if ( !$user = $this->login($username, $password) ) {
869                         return $this->error;
870                 }
871
872                 if( !current_user_can( 'edit_posts' ) ) {
873                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view tags.' ) );
874                 }
875
876                 do_action( 'xmlrpc_call', 'wp.getKeywords' );
877
878                 $tags = array( );
879
880                 if( $all_tags = get_tags( ) ) {
881                         foreach( (array) $all_tags as $tag ) {
882                                 $struct['tag_id']                       = $tag->term_id;
883                                 $struct['name']                         = $tag->name;
884                                 $struct['count']                        = $tag->count;
885                                 $struct['slug']                         = $tag->slug;
886                                 $struct['html_url']                     = esc_html( get_tag_link( $tag->term_id ) );
887                                 $struct['rss_url']                      = esc_html( get_tag_feed_link( $tag->term_id ) );
888
889                                 $tags[] = $struct;
890                         }
891                 }
892
893                 return $tags;
894         }
895
896         /**
897          * Create new category.
898          *
899          * @since 2.2.0
900          *
901          * @param array $args Method parameters.
902          * @return int Category ID.
903          */
904         function wp_newCategory($args) {
905                 $this->escape($args);
906
907                 $blog_id                                = (int) $args[0];
908                 $username                               = $args[1];
909                 $password                               = $args[2];
910                 $category                               = $args[3];
911
912                 if ( !$user = $this->login($username, $password) ) {
913                         return $this->error;
914                 }
915
916                 do_action('xmlrpc_call', 'wp.newCategory');
917
918                 // Make sure the user is allowed to add a category.
919                 if(!current_user_can("manage_categories")) {
920                         return(new IXR_Error(401, __("Sorry, you do not have the right to add a category.")));
921                 }
922
923                 // If no slug was provided make it empty so that
924                 // WordPress will generate one.
925                 if(empty($category["slug"])) {
926                         $category["slug"] = "";
927                 }
928
929                 // If no parent_id was provided make it empty
930                 // so that it will be a top level page (no parent).
931                 if ( !isset($category["parent_id"]) )
932                         $category["parent_id"] = "";
933
934                 // If no description was provided make it empty.
935                 if(empty($category["description"])) {
936                         $category["description"] = "";
937                 }
938
939                 $new_category = array(
940                         "cat_name"                              => $category["name"],
941                         "category_nicename"             => $category["slug"],
942                         "category_parent"               => $category["parent_id"],
943                         "category_description"  => $category["description"]
944                 );
945
946                 $cat_id = wp_insert_category($new_category);
947                 if(!$cat_id) {
948                         return(new IXR_Error(500, __("Sorry, the new category failed.")));
949                 }
950
951                 return($cat_id);
952         }
953
954         /**
955          * Remove category.
956          *
957          * @since 2.5.0
958          *
959          * @param array $args Method parameters.
960          * @return mixed See {@link wp_delete_category()} for return info.
961          */
962         function wp_deleteCategory($args) {
963                 $this->escape($args);
964
965                 $blog_id                = (int) $args[0];
966                 $username               = $args[1];
967                 $password               = $args[2];
968                 $category_id    = (int) $args[3];
969
970                 if ( !$user = $this->login($username, $password) ) {
971                         return $this->error;
972                 }
973
974                 do_action('xmlrpc_call', 'wp.deleteCategory');
975
976                 if( !current_user_can("manage_categories") ) {
977                         return new IXR_Error( 401, __( "Sorry, you do not have the right to delete a category." ) );
978                 }
979
980                 return wp_delete_category( $category_id );
981         }
982
983         /**
984          * Retrieve category list.
985          *
986          * @since 2.2.0
987          *
988          * @param array $args Method parameters.
989          * @return array
990          */
991         function wp_suggestCategories($args) {
992                 $this->escape($args);
993
994                 $blog_id                                = (int) $args[0];
995                 $username                               = $args[1];
996                 $password                               = $args[2];
997                 $category                               = $args[3];
998                 $max_results                    = (int) $args[4];
999
1000                 if ( !$user = $this->login($username, $password) ) {
1001                         return $this->error;
1002                 }
1003
1004                 if( !current_user_can( 'edit_posts' ) )
1005                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts to this blog in order to view categories.' ) );
1006
1007                 do_action('xmlrpc_call', 'wp.suggestCategories');
1008
1009                 $category_suggestions = array();
1010                 $args = array('get' => 'all', 'number' => $max_results, 'name__like' => $category);
1011                 foreach ( (array) get_categories($args) as $cat ) {
1012                         $category_suggestions[] = array(
1013                                 "category_id"   => $cat->cat_ID,
1014                                 "category_name" => $cat->cat_name
1015                         );
1016                 }
1017
1018                 return($category_suggestions);
1019         }
1020
1021         /**
1022          * Retrieve comment.
1023          *
1024          * @since 2.7.0
1025          *
1026          * @param array $args Method parameters.
1027          * @return array
1028          */
1029         function wp_getComment($args) {
1030                 $this->escape($args);
1031
1032                 $blog_id        = (int) $args[0];
1033                 $username       = $args[1];
1034                 $password       = $args[2];
1035                 $comment_id     = (int) $args[3];
1036
1037                 if ( !$user = $this->login($username, $password) ) {
1038                         return $this->error;
1039                 }
1040
1041                 if ( !current_user_can( 'moderate_comments' ) )
1042                         return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1043
1044                 do_action('xmlrpc_call', 'wp.getComment');
1045
1046                 if ( ! $comment = get_comment($comment_id) )
1047                         return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1048
1049                 // Format page date.
1050                 $comment_date = mysql2date("Ymd\TH:i:s", $comment->comment_date, false);
1051                 $comment_date_gmt = mysql2date("Ymd\TH:i:s", $comment->comment_date_gmt, false);
1052
1053                 if ( 0 == $comment->comment_approved )
1054                         $comment_status = 'hold';
1055                 else if ( 'spam' == $comment->comment_approved )
1056                         $comment_status = 'spam';
1057                 else if ( 1 == $comment->comment_approved )
1058                         $comment_status = 'approve';
1059                 else
1060                         $comment_status = $comment->comment_approved;
1061
1062                 $link = get_comment_link($comment);
1063
1064                 $comment_struct = array(
1065                         "date_created_gmt"              => new IXR_Date($comment_date_gmt),
1066                         "user_id"                               => $comment->user_id,
1067                         "comment_id"                    => $comment->comment_ID,
1068                         "parent"                                => $comment->comment_parent,
1069                         "status"                                => $comment_status,
1070                         "content"                               => $comment->comment_content,
1071                         "link"                                  => $link,
1072                         "post_id"                               => $comment->comment_post_ID,
1073                         "post_title"                    => get_the_title($comment->comment_post_ID),
1074                         "author"                                => $comment->comment_author,
1075                         "author_url"                    => $comment->comment_author_url,
1076                         "author_email"                  => $comment->comment_author_email,
1077                         "author_ip"                             => $comment->comment_author_IP,
1078                         "type"                                  => $comment->comment_type,
1079                 );
1080
1081                 return $comment_struct;
1082         }
1083
1084         /**
1085          * Retrieve comments.
1086          *
1087          * @since 2.7.0
1088          *
1089          * @param array $args Method parameters.
1090          * @return array
1091          */
1092         function wp_getComments($args) {
1093                 $this->escape($args);
1094
1095                 $blog_id        = (int) $args[0];
1096                 $username       = $args[1];
1097                 $password       = $args[2];
1098                 $struct         = $args[3];
1099
1100                 if ( !$user = $this->login($username, $password) ) {
1101                         return $this->error;
1102                 }
1103
1104                 if ( !current_user_can( 'moderate_comments' ) )
1105                         return new IXR_Error( 401, __( 'Sorry, you cannot edit comments.' ) );
1106
1107                 do_action('xmlrpc_call', 'wp.getComments');
1108
1109                 if ( isset($struct['status']) )
1110                         $status = $struct['status'];
1111                 else
1112                         $status = '';
1113
1114                 $post_id = '';
1115                 if ( isset($struct['post_id']) )
1116                         $post_id = absint($struct['post_id']);
1117
1118                 $offset = 0;
1119                 if ( isset($struct['offset']) )
1120                         $offset = absint($struct['offset']);
1121
1122                 $number = 10;
1123                 if ( isset($struct['number']) )
1124                         $number = absint($struct['number']);
1125
1126                 $comments = get_comments( array('status' => $status, 'post_id' => $post_id, 'offset' => $offset, 'number' => $number ) );
1127                 $num_comments = count($comments);
1128
1129                 if ( ! $num_comments )
1130                         return array();
1131
1132                 $comments_struct = array();
1133
1134                 for ( $i = 0; $i < $num_comments; $i++ ) {
1135                         $comment = wp_xmlrpc_server::wp_getComment(array(
1136                                 $blog_id, $username, $password, $comments[$i]->comment_ID,
1137                         ));
1138                         $comments_struct[] = $comment;
1139                 }
1140
1141                 return $comments_struct;
1142         }
1143
1144         /**
1145          * Remove comment.
1146          *
1147          * @since 2.7.0
1148          *
1149          * @param array $args Method parameters.
1150          * @return mixed {@link wp_delete_comment()}
1151          */
1152         function wp_deleteComment($args) {
1153                 $this->escape($args);
1154
1155                 $blog_id        = (int) $args[0];
1156                 $username       = $args[1];
1157                 $password       = $args[2];
1158                 $comment_ID     = (int) $args[3];
1159
1160                 if ( !$user = $this->login($username, $password) ) {
1161                         return $this->error;
1162                 }
1163
1164                 if ( !current_user_can( 'moderate_comments' ) )
1165                         return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1166
1167                 do_action('xmlrpc_call', 'wp.deleteComment');
1168
1169                 if ( ! get_comment($comment_ID) )
1170                         return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1171
1172                 return wp_delete_comment($comment_ID);
1173         }
1174
1175         /**
1176          * Edit comment.
1177          *
1178          * @since 2.7.0
1179          *
1180          * @param array $args Method parameters.
1181          * @return bool True, on success.
1182          */
1183         function wp_editComment($args) {
1184                 $this->escape($args);
1185
1186                 $blog_id        = (int) $args[0];
1187                 $username       = $args[1];
1188                 $password       = $args[2];
1189                 $comment_ID     = (int) $args[3];
1190                 $content_struct = $args[4];
1191
1192                 if ( !$user = $this->login($username, $password) ) {
1193                         return $this->error;
1194                 }
1195
1196                 if ( !current_user_can( 'moderate_comments' ) )
1197                         return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) );
1198
1199                 do_action('xmlrpc_call', 'wp.editComment');
1200
1201                 if ( ! get_comment($comment_ID) )
1202                         return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
1203
1204                 if ( isset($content_struct['status']) ) {
1205                         $statuses = get_comment_statuses();
1206                         $statuses = array_keys($statuses);
1207
1208                         if ( ! in_array($content_struct['status'], $statuses) )
1209                                 return new IXR_Error( 401, __( 'Invalid comment status.' ) );
1210                         $comment_approved = $content_struct['status'];
1211                 }
1212
1213                 // Do some timestamp voodoo
1214                 if ( !empty( $content_struct['date_created_gmt'] ) ) {
1215                         $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force
1216                         $comment_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1217                         $comment_date_gmt = iso8601_to_datetime($dateCreated, GMT);
1218                 }
1219
1220                 if ( isset($content_struct['content']) )
1221                         $comment_content = $content_struct['content'];
1222
1223                 if ( isset($content_struct['author']) )
1224                         $comment_author = $content_struct['author'];
1225
1226                 if ( isset($content_struct['author_url']) )
1227                         $comment_author_url = $content_struct['author_url'];
1228
1229                 if ( isset($content_struct['author_email']) )
1230                         $comment_author_email = $content_struct['author_email'];
1231
1232                 // We've got all the data -- post it:
1233                 $comment = compact('comment_ID', 'comment_content', 'comment_approved', 'comment_date', 'comment_date_gmt', 'comment_author', 'comment_author_email', 'comment_author_url');
1234
1235                 $result = wp_update_comment($comment);
1236                 if ( is_wp_error( $result ) )
1237                         return new IXR_Error(500, $result->get_error_message());
1238
1239                 if ( !$result )
1240                         return new IXR_Error(500, __('Sorry, the comment could not be edited. Something wrong happened.'));
1241
1242                 return true;
1243         }
1244
1245         /**
1246          * Create new comment.
1247          *
1248          * @since 2.7.0
1249          *
1250          * @param array $args Method parameters.
1251          * @return mixed {@link wp_new_comment()}
1252          */
1253         function wp_newComment($args) {
1254                 global $wpdb;
1255
1256                 $this->escape($args);
1257
1258                 $blog_id        = (int) $args[0];
1259                 $username       = $args[1];
1260                 $password       = $args[2];
1261                 $post           = $args[3];
1262                 $content_struct = $args[4];
1263
1264                 $allow_anon = apply_filters('xmlrpc_allow_anonymous_comments', false);
1265
1266                 $user = $this->login($username, $password);
1267
1268                 if ( !$user ) {
1269                         $logged_in = false;
1270                         if ( $allow_anon && get_option('comment_registration') )
1271                                 return new IXR_Error( 403, __( 'You must be registered to comment' ) );
1272                         else if ( !$allow_anon )
1273                                 return $this->error;
1274                 } else {
1275                         $logged_in = true;
1276                 }
1277
1278                 if ( is_numeric($post) )
1279                         $post_id = absint($post);
1280                 else
1281                         $post_id = url_to_postid($post);
1282
1283                 if ( ! $post_id )
1284                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1285
1286                 if ( ! get_post($post_id) )
1287                         return new IXR_Error( 404, __( 'Invalid post ID.' ) );
1288
1289                 $comment['comment_post_ID'] = $post_id;
1290
1291                 if ( $logged_in ) {
1292                         $comment['comment_author'] = $wpdb->escape( $user->display_name );
1293                         $comment['comment_author_email'] = $wpdb->escape( $user->user_email );
1294                         $comment['comment_author_url'] = $wpdb->escape( $user->user_url );
1295                         $comment['user_ID'] = $user->ID;
1296                 } else {
1297                         $comment['comment_author'] = '';
1298                         if ( isset($content_struct['author']) )
1299                                 $comment['comment_author'] = $content_struct['author'];
1300
1301                         $comment['comment_author_email'] = '';
1302                         if ( isset($content_struct['author_email']) )
1303                                 $comment['comment_author_email'] = $content_struct['author_email'];
1304
1305                         $comment['comment_author_url'] = '';
1306                         if ( isset($content_struct['author_url']) )
1307                                 $comment['comment_author_url'] = $content_struct['author_url'];
1308
1309                         $comment['user_ID'] = 0;
1310
1311                         if ( get_option('require_name_email') ) {
1312                                 if ( 6 > strlen($comment['comment_author_email']) || '' == $comment['comment_author'] )
1313                                         return new IXR_Error( 403, __( 'Comment author name and email are required' ) );
1314                                 elseif ( !is_email($comment['comment_author_email']) )
1315                                         return new IXR_Error( 403, __( 'A valid email address is required' ) );
1316                         }
1317                 }
1318
1319                 $comment['comment_parent'] = isset($content_struct['comment_parent']) ? absint($content_struct['comment_parent']) : 0;
1320
1321                 $comment['comment_content'] = $content_struct['content'];
1322
1323                 do_action('xmlrpc_call', 'wp.newComment');
1324
1325                 return wp_new_comment($comment);
1326         }
1327
1328         /**
1329          * Retrieve all of the comment status.
1330          *
1331          * @since 2.7.0
1332          *
1333          * @param array $args Method parameters.
1334          * @return array
1335          */
1336         function wp_getCommentStatusList($args) {
1337                 $this->escape( $args );
1338
1339                 $blog_id        = (int) $args[0];
1340                 $username       = $args[1];
1341                 $password       = $args[2];
1342
1343                 if ( !$user = $this->login($username, $password) ) {
1344                         return $this->error;
1345                 }
1346
1347                 if ( !current_user_can( 'moderate_comments' ) )
1348                         return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1349
1350                 do_action('xmlrpc_call', 'wp.getCommentStatusList');
1351
1352                 return get_comment_statuses( );
1353         }
1354
1355         /**
1356          * Retrieve comment count.
1357          *
1358          * @since 2.5.0
1359          *
1360          * @param array $args Method parameters.
1361          * @return array
1362          */
1363         function wp_getCommentCount( $args ) {
1364                 $this->escape($args);
1365
1366                 $blog_id        = (int) $args[0];
1367                 $username       = $args[1];
1368                 $password       = $args[2];
1369                 $post_id        = (int) $args[3];
1370
1371                 if ( !$user = $this->login($username, $password) ) {
1372                         return $this->error;
1373                 }
1374
1375                 if( !current_user_can( 'edit_posts' ) ) {
1376                         return new IXR_Error( 403, __( 'You are not allowed access to details about comments.' ) );
1377                 }
1378
1379                 do_action('xmlrpc_call', 'wp.getCommentCount');
1380
1381                 $count = wp_count_comments( $post_id );
1382                 return array(
1383                         "approved" => $count->approved,
1384                         "awaiting_moderation" => $count->moderated,
1385                         "spam" => $count->spam,
1386                         "total_comments" => $count->total_comments
1387                 );
1388         }
1389
1390         /**
1391          * Retrieve post statuses.
1392          *
1393          * @since 2.5.0
1394          *
1395          * @param array $args Method parameters.
1396          * @return array
1397          */
1398         function wp_getPostStatusList( $args ) {
1399                 $this->escape( $args );
1400
1401                 $blog_id        = (int) $args[0];
1402                 $username       = $args[1];
1403                 $password       = $args[2];
1404
1405                 if ( !$user = $this->login($username, $password) ) {
1406                         return $this->error;
1407                 }
1408
1409                 if( !current_user_can( 'edit_posts' ) ) {
1410                         return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1411                 }
1412
1413                 do_action('xmlrpc_call', 'wp.getPostStatusList');
1414
1415                 return get_post_statuses( );
1416         }
1417
1418         /**
1419          * Retrieve page statuses.
1420          *
1421          * @since 2.5.0
1422          *
1423          * @param array $args Method parameters.
1424          * @return array
1425          */
1426         function wp_getPageStatusList( $args ) {
1427                 $this->escape( $args );
1428
1429                 $blog_id        = (int) $args[0];
1430                 $username       = $args[1];
1431                 $password       = $args[2];
1432
1433                 if ( !$user = $this->login($username, $password) ) {
1434                         return $this->error;
1435                 }
1436
1437                 if( !current_user_can( 'edit_posts' ) ) {
1438                         return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1439                 }
1440
1441                 do_action('xmlrpc_call', 'wp.getPageStatusList');
1442
1443                 return get_page_statuses( );
1444         }
1445
1446         /**
1447          * Retrieve page templates.
1448          *
1449          * @since 2.6.0
1450          *
1451          * @param array $args Method parameters.
1452          * @return array
1453          */
1454         function wp_getPageTemplates( $args ) {
1455                 $this->escape( $args );
1456
1457                 $blog_id        = (int) $args[0];
1458                 $username       = $args[1];
1459                 $password       = $args[2];
1460
1461                 if ( !$user = $this->login($username, $password) ) {
1462                         return $this->error;
1463                 }
1464
1465                 if( !current_user_can( 'edit_pages' ) ) {
1466                         return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
1467                 }
1468
1469                 $templates = get_page_templates( );
1470                 $templates['Default'] = 'default';
1471
1472                 return $templates;
1473         }
1474
1475         /**
1476          * Retrieve blog options.
1477          *
1478          * @since 2.6.0
1479          *
1480          * @param array $args Method parameters.
1481          * @return array
1482          */
1483         function wp_getOptions( $args ) {
1484                 $this->escape( $args );
1485
1486                 $blog_id        = (int) $args[0];
1487                 $username       = $args[1];
1488                 $password       = $args[2];
1489                 $options        = (array) $args[3];
1490
1491                 if ( !$user = $this->login($username, $password) ) {
1492                         return $this->error;
1493                 }
1494
1495                 // If no specific options where asked for, return all of them
1496                 if (count( $options ) == 0 ) {
1497                         $options = array_keys($this->blog_options);
1498                 }
1499
1500                 return $this->_getOptions($options);
1501         }
1502
1503         /**
1504          * Retrieve blog options value from list.
1505          *
1506          * @since 2.6.0
1507          *
1508          * @param array $options Options to retrieve.
1509          * @return array
1510          */
1511         function _getOptions($options)
1512         {
1513                 $data = array( );
1514                 foreach( $options as $option ) {
1515                         if( array_key_exists( $option, $this->blog_options ) )
1516                         {
1517                                 $data[$option] = $this->blog_options[$option];
1518                                 //Is the value static or dynamic?
1519                                 if( isset( $data[$option]['option'] ) ) {
1520                                         $data[$option]['value'] = get_option( $data[$option]['option'] );
1521                                         unset($data[$option]['option']);
1522                                 }
1523                         }
1524                 }
1525
1526                 return $data;
1527         }
1528
1529         /**
1530          * Update blog options.
1531          *
1532          * @since 2.6.0
1533          *
1534          * @param array $args Method parameters.
1535          * @return unknown
1536          */
1537         function wp_setOptions( $args ) {
1538                 $this->escape( $args );
1539
1540                 $blog_id        = (int) $args[0];
1541                 $username       = $args[1];
1542                 $password       = $args[2];
1543                 $options        = (array) $args[3];
1544
1545                 if ( !$user = $this->login($username, $password) ) {
1546                         return $this->error;
1547                 }
1548
1549                 if( !current_user_can( 'manage_options' ) )
1550                         return new IXR_Error( 403, __( 'You are not allowed to update options.' ) );
1551
1552                 foreach( $options as $o_name => $o_value ) {
1553                         $option_names[] = $o_name;
1554                         if( empty( $o_value ) )
1555                                 continue;
1556
1557                         if( !array_key_exists( $o_name, $this->blog_options ) )
1558                                 continue;
1559
1560                         if( $this->blog_options[$o_name]['readonly'] == true )
1561                                 continue;
1562
1563                         update_option( $this->blog_options[$o_name]['option'], $o_value );
1564                 }
1565
1566                 //Now return the updated values
1567                 return $this->_getOptions($option_names);
1568         }
1569
1570         /* Blogger API functions.
1571          * specs on http://plant.blogger.com/api and http://groups.yahoo.com/group/bloggerDev/
1572          */
1573
1574         /**
1575          * Retrieve blogs that user owns.
1576          *
1577          * Will make more sense once we support multiple blogs.
1578          *
1579          * @since 1.5.0
1580          *
1581          * @param array $args Method parameters.
1582          * @return array
1583          */
1584         function blogger_getUsersBlogs($args) {
1585
1586                 $this->escape($args);
1587
1588                 $username = $args[1];
1589                 $password  = $args[2];
1590
1591                 if ( !$user = $this->login($username, $password) ) {
1592                         return $this->error;
1593                 }
1594
1595                 do_action('xmlrpc_call', 'blogger.getUsersBlogs');
1596
1597                 $is_admin = current_user_can('manage_options');
1598
1599                 $struct = array(
1600                         'isAdmin'  => $is_admin,
1601                         'url'      => get_option('home') . '/',
1602                         'blogid'   => '1',
1603                         'blogName' => get_option('blogname'),
1604                         'xmlrpc'   => site_url( 'xmlrpc.php' )
1605                 );
1606
1607                 return array($struct);
1608         }
1609
1610         /**
1611          * Retrieve user's data.
1612          *
1613          * Gives your client some info about you, so you don't have to.
1614          *
1615          * @since 1.5.0
1616          *
1617          * @param array $args Method parameters.
1618          * @return array
1619          */
1620         function blogger_getUserInfo($args) {
1621
1622                 $this->escape($args);
1623
1624                 $username = $args[1];
1625                 $password  = $args[2];
1626
1627                 if ( !$user = $this->login($username, $password) ) {
1628                         return $this->error;
1629                 }
1630
1631                 if( !current_user_can( 'edit_posts' ) )
1632                         return new IXR_Error( 401, __( 'Sorry, you do not have access to user data on this blog.' ) );
1633
1634                 do_action('xmlrpc_call', 'blogger.getUserInfo');
1635
1636                 $struct = array(
1637                         'nickname'  => $user->nickname,
1638                         'userid'    => $user->ID,
1639                         'url'       => $user->user_url,
1640                         'lastname'  => $user->last_name,
1641                         'firstname' => $user->first_name
1642                 );
1643
1644                 return $struct;
1645         }
1646
1647         /**
1648          * Retrieve post.
1649          *
1650          * @since 1.5.0
1651          *
1652          * @param array $args Method parameters.
1653          * @return array
1654          */
1655         function blogger_getPost($args) {
1656
1657                 $this->escape($args);
1658
1659                 $post_ID    = (int) $args[1];
1660                 $username = $args[2];
1661                 $password  = $args[3];
1662
1663                 if ( !$user = $this->login($username, $password) ) {
1664                         return $this->error;
1665                 }
1666
1667                 if( !current_user_can( 'edit_post', $post_ID ) )
1668                         return new IXR_Error( 401, __( 'Sorry, you cannot edit this post.' ) );
1669
1670                 do_action('xmlrpc_call', 'blogger.getPost');
1671
1672                 $post_data = wp_get_single_post($post_ID, ARRAY_A);
1673
1674                 $categories = implode(',', wp_get_post_categories($post_ID));
1675
1676                 $content  = '<title>'.stripslashes($post_data['post_title']).'</title>';
1677                 $content .= '<category>'.$categories.'</category>';
1678                 $content .= stripslashes($post_data['post_content']);
1679
1680                 $struct = array(
1681                         'userid'    => $post_data['post_author'],
1682                         'dateCreated' => new IXR_Date(mysql2date('Ymd\TH:i:s', $post_data['post_date'], false)),
1683                         'content'     => $content,
1684                         'postid'  => $post_data['ID']
1685                 );
1686
1687                 return $struct;
1688         }
1689
1690         /**
1691          * Retrieve list of recent posts.
1692          *
1693          * @since 1.5.0
1694          *
1695          * @param array $args Method parameters.
1696          * @return array
1697          */
1698         function blogger_getRecentPosts($args) {
1699
1700                 $this->escape($args);
1701
1702                 $blog_ID    = (int) $args[1]; /* though we don't use it yet */
1703                 $username = $args[2];
1704                 $password  = $args[3];
1705                 $num_posts  = $args[4];
1706
1707                 if ( !$user = $this->login($username, $password) ) {
1708                         return $this->error;
1709                 }
1710
1711                 do_action('xmlrpc_call', 'blogger.getRecentPosts');
1712
1713                 $posts_list = wp_get_recent_posts($num_posts);
1714
1715                 if (!$posts_list) {
1716                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
1717                         return $this->error;
1718                 }
1719
1720                 foreach ($posts_list as $entry) {
1721                         if( !current_user_can( 'edit_post', $entry['ID'] ) )
1722                                 continue;
1723
1724                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date'], false);
1725                         $categories = implode(',', wp_get_post_categories($entry['ID']));
1726
1727                         $content  = '<title>'.stripslashes($entry['post_title']).'</title>';
1728                         $content .= '<category>'.$categories.'</category>';
1729                         $content .= stripslashes($entry['post_content']);
1730
1731                         $struct[] = array(
1732                                 'userid' => $entry['post_author'],
1733                                 'dateCreated' => new IXR_Date($post_date),
1734                                 'content' => $content,
1735                                 'postid' => $entry['ID'],
1736                         );
1737
1738                 }
1739
1740                 $recent_posts = array();
1741                 for ($j=0; $j<count($struct); $j++) {
1742                         array_push($recent_posts, $struct[$j]);
1743                 }
1744
1745                 return $recent_posts;
1746         }
1747
1748         /**
1749          * Retrieve blog_filename content.
1750          *
1751          * @since 1.5.0
1752          *
1753          * @param array $args Method parameters.
1754          * @return string
1755          */
1756         function blogger_getTemplate($args) {
1757
1758                 $this->escape($args);
1759
1760                 $blog_ID    = (int) $args[1];
1761                 $username = $args[2];
1762                 $password  = $args[3];
1763                 $template   = $args[4]; /* could be 'main' or 'archiveIndex', but we don't use it */
1764
1765                 if ( !$user = $this->login($username, $password) ) {
1766                         return $this->error;
1767                 }
1768
1769                 do_action('xmlrpc_call', 'blogger.getTemplate');
1770
1771                 if ( !current_user_can('edit_themes') ) {
1772                         return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
1773                 }
1774
1775                 /* warning: here we make the assumption that the blog's URL is on the same server */
1776                 $filename = get_option('home') . '/';
1777                 $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
1778
1779                 $f = fopen($filename, 'r');
1780                 $content = fread($f, filesize($filename));
1781                 fclose($f);
1782
1783                 /* so it is actually editable with a windows/mac client */
1784                 // 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);
1785
1786                 return $content;
1787         }
1788
1789         /**
1790          * Updates the content of blog_filename.
1791          *
1792          * @since 1.5.0
1793          *
1794          * @param array $args Method parameters.
1795          * @return bool True when done.
1796          */
1797         function blogger_setTemplate($args) {
1798
1799                 $this->escape($args);
1800
1801                 $blog_ID    = (int) $args[1];
1802                 $username = $args[2];
1803                 $password  = $args[3];
1804                 $content    = $args[4];
1805                 $template   = $args[5]; /* could be 'main' or 'archiveIndex', but we don't use it */
1806
1807                 if ( !$user = $this->login($username, $password) ) {
1808                         return $this->error;
1809                 }
1810
1811                 do_action('xmlrpc_call', 'blogger.setTemplate');
1812
1813                 if ( !current_user_can('edit_themes') ) {
1814                         return new IXR_Error(401, __('Sorry, this user cannot edit the template.'));
1815                 }
1816
1817                 /* warning: here we make the assumption that the blog's URL is on the same server */
1818                 $filename = get_option('home') . '/';
1819                 $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
1820
1821                 if ($f = fopen($filename, 'w+')) {
1822                         fwrite($f, $content);
1823                         fclose($f);
1824                 } else {
1825                         return new IXR_Error(500, __('Either the file is not writable, or something wrong happened. The file has not been updated.'));
1826                 }
1827
1828                 return true;
1829         }
1830
1831         /**
1832          * Create new post.
1833          *
1834          * @since 1.5.0
1835          *
1836          * @param array $args Method parameters.
1837          * @return int
1838          */
1839         function blogger_newPost($args) {
1840
1841                 $this->escape($args);
1842
1843                 $blog_ID    = (int) $args[1]; /* though we don't use it yet */
1844                 $username = $args[2];
1845                 $password  = $args[3];
1846                 $content    = $args[4];
1847                 $publish    = $args[5];
1848
1849                 if ( !$user = $this->login($username, $password) ) {
1850                         return $this->error;
1851                 }
1852
1853                 do_action('xmlrpc_call', 'blogger.newPost');
1854
1855                 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
1856                 if ( !current_user_can($cap) )
1857                         return new IXR_Error(401, __('Sorry, you are not allowed to post on this blog.'));
1858
1859                 $post_status = ($publish) ? 'publish' : 'draft';
1860
1861                 $post_author = $user->ID;
1862
1863                 $post_title = xmlrpc_getposttitle($content);
1864                 $post_category = xmlrpc_getpostcategory($content);
1865                 $post_content = xmlrpc_removepostdata($content);
1866
1867                 $post_date = current_time('mysql');
1868                 $post_date_gmt = current_time('mysql', 1);
1869
1870                 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status');
1871
1872                 $post_ID = wp_insert_post($post_data);
1873                 if ( is_wp_error( $post_ID ) )
1874                         return new IXR_Error(500, $post_ID->get_error_message());
1875
1876                 if (!$post_ID)
1877                         return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
1878
1879                 $this->attach_uploads( $post_ID, $post_content );
1880
1881                 logIO('O', "Posted ! ID: $post_ID");
1882
1883                 return $post_ID;
1884         }
1885
1886         /**
1887          * Edit a post.
1888          *
1889          * @since 1.5.0
1890          *
1891          * @param array $args Method parameters.
1892          * @return bool true when done.
1893          */
1894         function blogger_editPost($args) {
1895
1896                 $this->escape($args);
1897
1898                 $post_ID     = (int) $args[1];
1899                 $username  = $args[2];
1900                 $password   = $args[3];
1901                 $content     = $args[4];
1902                 $publish     = $args[5];
1903
1904                 if ( !$user = $this->login($username, $password) ) {
1905                         return $this->error;
1906                 }
1907
1908                 do_action('xmlrpc_call', 'blogger.editPost');
1909
1910                 $actual_post = wp_get_single_post($post_ID,ARRAY_A);
1911
1912                 if (!$actual_post || $actual_post['post_type'] != 'post') {
1913                         return new IXR_Error(404, __('Sorry, no such post.'));
1914                 }
1915
1916                 $this->escape($actual_post);
1917
1918                 if ( !current_user_can('edit_post', $post_ID) )
1919                         return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.'));
1920
1921                 extract($actual_post, EXTR_SKIP);
1922
1923                 if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
1924                         return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
1925
1926                 $post_title = xmlrpc_getposttitle($content);
1927                 $post_category = xmlrpc_getpostcategory($content);
1928                 $post_content = xmlrpc_removepostdata($content);
1929
1930                 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
1931
1932                 $result = wp_update_post($postdata);
1933
1934                 if (!$result) {
1935                         return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be edited.'));
1936                 }
1937                 $this->attach_uploads( $ID, $post_content );
1938
1939                 return true;
1940         }
1941
1942         /**
1943          * Remove a post.
1944          *
1945          * @since 1.5.0
1946          *
1947          * @param array $args Method parameters.
1948          * @return bool True when post is deleted.
1949          */
1950         function blogger_deletePost($args) {
1951                 $this->escape($args);
1952
1953                 $post_ID     = (int) $args[1];
1954                 $username  = $args[2];
1955                 $password   = $args[3];
1956                 $publish     = $args[4];
1957
1958                 if ( !$user = $this->login($username, $password) ) {
1959                         return $this->error;
1960                 }
1961
1962                 do_action('xmlrpc_call', 'blogger.deletePost');
1963
1964                 $actual_post = wp_get_single_post($post_ID,ARRAY_A);
1965
1966                 if (!$actual_post || $actual_post['post_type'] != 'post') {
1967                         return new IXR_Error(404, __('Sorry, no such post.'));
1968                 }
1969
1970                 if ( !current_user_can('edit_post', $post_ID) )
1971                         return new IXR_Error(401, __('Sorry, you do not have the right to delete this post.'));
1972
1973                 $result = wp_delete_post($post_ID);
1974
1975                 if (!$result) {
1976                         return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be deleted.'));
1977                 }
1978
1979                 return true;
1980         }
1981
1982         /* MetaWeblog API functions
1983          * specs on wherever Dave Winer wants them to be
1984          */
1985
1986         /**
1987          * Create a new post.
1988          *
1989          * @since 1.5.0
1990          *
1991          * @param array $args Method parameters.
1992          * @return int
1993          */
1994         function mw_newPost($args) {
1995                 $this->escape($args);
1996
1997                 $blog_ID     = (int) $args[0]; // we will support this in the near future
1998                 $username  = $args[1];
1999                 $password   = $args[2];
2000                 $content_struct = $args[3];
2001                 $publish     = $args[4];
2002
2003                 if ( !$user = $this->login($username, $password) ) {
2004                         return $this->error;
2005                 }
2006
2007                 do_action('xmlrpc_call', 'metaWeblog.newPost');
2008
2009                 $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
2010                 $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' );
2011                 $post_type = 'post';
2012                 $page_template = '';
2013                 if( !empty( $content_struct['post_type'] ) ) {
2014                         if( $content_struct['post_type'] == 'page' ) {
2015                                 $cap = ( $publish ) ? 'publish_pages' : 'edit_pages';
2016                                 $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' );
2017                                 $post_type = 'page';
2018                                 if( !empty( $content_struct['wp_page_template'] ) )
2019                                         $page_template = $content_struct['wp_page_template'];
2020                         }
2021                         elseif( $content_struct['post_type'] == 'post' ) {
2022                                 // This is the default, no changes needed
2023                         }
2024                         else {
2025                                 // No other post_type values are allowed here
2026                                 return new IXR_Error( 401, __( 'Invalid post type.' ) );
2027                         }
2028                 }
2029
2030                 if( !current_user_can( $cap ) ) {
2031                         return new IXR_Error( 401, $error_message );
2032                 }
2033
2034                 // Let WordPress generate the post_name (slug) unless
2035                 // one has been provided.
2036                 $post_name = "";
2037                 if(isset($content_struct["wp_slug"])) {
2038                         $post_name = $content_struct["wp_slug"];
2039                 }
2040
2041                 // Only use a password if one was given.
2042                 if(isset($content_struct["wp_password"])) {
2043                         $post_password = $content_struct["wp_password"];
2044                 }
2045
2046                 // Only set a post parent if one was provided.
2047                 if(isset($content_struct["wp_page_parent_id"])) {
2048                         $post_parent = $content_struct["wp_page_parent_id"];
2049                 }
2050
2051                 // Only set the menu_order if it was provided.
2052                 if(isset($content_struct["wp_page_order"])) {
2053                         $menu_order = $content_struct["wp_page_order"];
2054                 }
2055
2056                 $post_author = $user->ID;
2057
2058                 // If an author id was provided then use it instead.
2059                 if(
2060                         isset($content_struct["wp_author_id"])
2061                         && ($user->ID != $content_struct["wp_author_id"])
2062                 ) {
2063                         switch($post_type) {
2064                                 case "post":
2065                                         if(!current_user_can("edit_others_posts")) {
2066                                                 return(new IXR_Error(401, __("You are not allowed to post as this user")));
2067                                         }
2068                                         break;
2069                                 case "page":
2070                                         if(!current_user_can("edit_others_pages")) {
2071                                                 return(new IXR_Error(401, __("You are not allowed to create pages as this user")));
2072                                         }
2073                                         break;
2074                                 default:
2075                                         return(new IXR_Error(401, __("Invalid post type.")));
2076                                         break;
2077                         }
2078                         $post_author = $content_struct["wp_author_id"];
2079                 }
2080
2081                 $post_title = $content_struct['title'];
2082                 $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
2083
2084                 $post_status = $publish ? 'publish' : 'draft';
2085
2086                 if( isset( $content_struct["{$post_type}_status"] ) ) {
2087                         switch( $content_struct["{$post_type}_status"] ) {
2088                                 case 'draft':
2089                                 case 'private':
2090                                 case 'publish':
2091                                         $post_status = $content_struct["{$post_type}_status"];
2092                                         break;
2093                                 case 'pending':
2094                                         // Pending is only valid for posts, not pages.
2095                                         if( $post_type === 'post' ) {
2096                                                 $post_status = $content_struct["{$post_type}_status"];
2097                                         }
2098                                         break;
2099                                 default:
2100                                         $post_status = $publish ? 'publish' : 'draft';
2101                                         break;
2102                         }
2103                 }
2104
2105                 $post_excerpt = $content_struct['mt_excerpt'];
2106                 $post_more = $content_struct['mt_text_more'];
2107
2108                 $tags_input = $content_struct['mt_keywords'];
2109
2110                 if(isset($content_struct["mt_allow_comments"])) {
2111                         if(!is_numeric($content_struct["mt_allow_comments"])) {
2112                                 switch($content_struct["mt_allow_comments"]) {
2113                                         case "closed":
2114                                                 $comment_status = "closed";
2115                                                 break;
2116                                         case "open":
2117                                                 $comment_status = "open";
2118                                                 break;
2119                                         default:
2120                                                 $comment_status = get_option("default_comment_status");
2121                                                 break;
2122                                 }
2123                         }
2124                         else {
2125                                 switch((int) $content_struct["mt_allow_comments"]) {
2126                                         case 0:
2127                                         case 2:
2128                                                 $comment_status = "closed";
2129                                                 break;
2130                                         case 1:
2131                                                 $comment_status = "open";
2132                                                 break;
2133                                         default:
2134                                                 $comment_status = get_option("default_comment_status");
2135                                                 break;
2136                                 }
2137                         }
2138                 }
2139                 else {
2140                         $comment_status = get_option("default_comment_status");
2141                 }
2142
2143                 if(isset($content_struct["mt_allow_pings"])) {
2144                         if(!is_numeric($content_struct["mt_allow_pings"])) {
2145                                 switch($content_struct['mt_allow_pings']) {
2146                                         case "closed":
2147                                                 $ping_status = "closed";
2148                                                 break;
2149                                         case "open":
2150                                                 $ping_status = "open";
2151                                                 break;
2152                                         default:
2153                                                 $ping_status = get_option("default_ping_status");
2154                                                 break;
2155                                 }
2156                         }
2157                         else {
2158                                 switch((int) $content_struct["mt_allow_pings"]) {
2159                                         case 0:
2160                                                 $ping_status = "closed";
2161                                                 break;
2162                                         case 1:
2163                                                 $ping_status = "open";
2164                                                 break;
2165                                         default:
2166                                                 $ping_status = get_option("default_ping_status");
2167                                                 break;
2168                                 }
2169                         }
2170                 }
2171                 else {
2172                         $ping_status = get_option("default_ping_status");
2173                 }
2174
2175                 if ($post_more) {
2176                         $post_content = $post_content . "<!--more-->" . $post_more;
2177                 }
2178
2179                 $to_ping = $content_struct['mt_tb_ping_urls'];
2180                 if ( is_array($to_ping) )
2181                         $to_ping = implode(' ', $to_ping);
2182
2183                 // Do some timestamp voodoo
2184                 if ( !empty( $content_struct['date_created_gmt'] ) )
2185                         $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force
2186                 elseif ( !empty( $content_struct['dateCreated']) )
2187                         $dateCreated = $content_struct['dateCreated']->getIso();
2188
2189                 if ( !empty( $dateCreated ) ) {
2190                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
2191                         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
2192                 } else {
2193                         $post_date = current_time('mysql');
2194                         $post_date_gmt = current_time('mysql', 1);
2195                 }
2196
2197                 $catnames = $content_struct['categories'];
2198                 logIO('O', 'Post cats: ' . var_export($catnames,true));
2199                 $post_category = array();
2200
2201                 if (is_array($catnames)) {
2202                         foreach ($catnames as $cat) {
2203                                 $post_category[] = get_cat_ID($cat);
2204                         }
2205                 }
2206
2207                 // We've got all the data -- post it:
2208                 $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');
2209
2210                 $post_ID = wp_insert_post($postdata, true);
2211                 if ( is_wp_error( $post_ID ) )
2212                         return new IXR_Error(500, $post_ID->get_error_message());
2213
2214                 if (!$post_ID) {
2215                         return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
2216                 }
2217
2218                 // Only posts can be sticky
2219                 if ( $post_type == 'post' && isset( $content_struct['sticky'] ) )
2220                         if ( $content_struct['sticky'] == true )
2221                                 stick_post( $post_ID );
2222                         elseif ( $content_struct['sticky'] == false )
2223                                 unstick_post( $post_ID );
2224
2225                 if ( isset($content_struct['custom_fields']) ) {
2226                         $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
2227                 }
2228
2229                 // Handle enclosures
2230                 $this->add_enclosure_if_new($post_ID, $content_struct['enclosure']);
2231
2232                 $this->attach_uploads( $post_ID, $post_content );
2233
2234                 logIO('O', "Posted ! ID: $post_ID");
2235
2236                 return strval($post_ID);
2237         }
2238
2239         function add_enclosure_if_new($post_ID, $enclosure) {
2240                 if( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
2241
2242                         $encstring = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'];
2243                         $found = false;
2244                         foreach ( (array) get_post_custom($post_ID) as $key => $val) {
2245                                 if ($key == 'enclosure') {
2246                                         foreach ( (array) $val as $enc ) {
2247                                                 if ($enc == $encstring) {
2248                                                         $found = true;
2249                                                         break 2;
2250                                                 }
2251                                         }
2252                                 }
2253                         }
2254                         if (!$found) {
2255                                 add_post_meta( $post_ID, 'enclosure', $encstring );
2256                         }
2257                 }
2258         }
2259
2260         /**
2261          * Attach upload to a post.
2262          *
2263          * @since 2.1.0
2264          *
2265          * @param int $post_ID Post ID.
2266          * @param string $post_content Post Content for attachment.
2267          */
2268         function attach_uploads( $post_ID, $post_content ) {
2269                 global $wpdb;
2270
2271                 // find any unattached files
2272                 $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '-1' AND post_type = 'attachment'" );
2273                 if( is_array( $attachments ) ) {
2274                         foreach( $attachments as $file ) {
2275                                 if( strpos( $post_content, $file->guid ) !== false ) {
2276                                         $wpdb->update($wpdb->posts, array('post_parent' => $post_ID), array('ID' => $file->ID) );
2277                                 }
2278                         }
2279                 }
2280         }
2281
2282         /**
2283          * Edit a post.
2284          *
2285          * @since 1.5.0
2286          *
2287          * @param array $args Method parameters.
2288          * @return bool True on success.
2289          */
2290         function mw_editPost($args) {
2291
2292                 $this->escape($args);
2293
2294                 $post_ID     = (int) $args[0];
2295                 $username  = $args[1];
2296                 $password   = $args[2];
2297                 $content_struct = $args[3];
2298                 $publish     = $args[4];
2299
2300                 if ( !$user = $this->login($username, $password) ) {
2301                         return $this->error;
2302                 }
2303
2304                 do_action('xmlrpc_call', 'metaWeblog.editPost');
2305
2306                 $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
2307                 $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' );
2308                 $post_type = 'post';
2309                 $page_template = '';
2310                 if( !empty( $content_struct['post_type'] ) ) {
2311                         if( $content_struct['post_type'] == 'page' ) {
2312                                 $cap = ( $publish ) ? 'publish_pages' : 'edit_pages';
2313                                 $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' );
2314                                 $post_type = 'page';
2315                                 if( !empty( $content_struct['wp_page_template'] ) )
2316                                         $page_template = $content_struct['wp_page_template'];
2317                         }
2318                         elseif( $content_struct['post_type'] == 'post' ) {
2319                                 // This is the default, no changes needed
2320                         }
2321                         else {
2322                                 // No other post_type values are allowed here
2323                                 return new IXR_Error( 401, __( 'Invalid post type.' ) );
2324                         }
2325                 }
2326
2327                 if( !current_user_can( $cap ) ) {
2328                         return new IXR_Error( 401, $error_message );
2329                 }
2330
2331                 $postdata = wp_get_single_post($post_ID, ARRAY_A);
2332
2333                 // If there is no post data for the give post id, stop
2334                 // now and return an error.  Other wise a new post will be
2335                 // created (which was the old behavior).
2336                 if(empty($postdata["ID"])) {
2337                         return(new IXR_Error(404, __("Invalid post ID.")));
2338                 }
2339
2340                 $this->escape($postdata);
2341                 extract($postdata, EXTR_SKIP);
2342
2343                 // Let WordPress manage slug if none was provided.
2344                 $post_name = "";
2345                 if(isset($content_struct["wp_slug"])) {
2346                         $post_name = $content_struct["wp_slug"];
2347                 }
2348
2349                 // Only use a password if one was given.
2350                 if(isset($content_struct["wp_password"])) {
2351                         $post_password = $content_struct["wp_password"];
2352                 }
2353
2354                 // Only set a post parent if one was given.
2355                 if(isset($content_struct["wp_page_parent_id"])) {
2356                         $post_parent = $content_struct["wp_page_parent_id"];
2357                 }
2358
2359                 // Only set the menu_order if it was given.
2360                 if(isset($content_struct["wp_page_order"])) {
2361                         $menu_order = $content_struct["wp_page_order"];
2362                 }
2363
2364                 $post_author = $postdata["post_author"];
2365
2366                 // Only set the post_author if one is set.
2367                 if(
2368                         isset($content_struct["wp_author_id"])
2369                         && ($user->ID != $content_struct["wp_author_id"])
2370                 ) {
2371                         switch($post_type) {
2372                                 case "post":
2373                                         if(!current_user_can("edit_others_posts")) {
2374                                                 return(new IXR_Error(401, __("You are not allowed to change the post author as this user.")));
2375                                         }
2376                                         break;
2377                                 case "page":
2378                                         if(!current_user_can("edit_others_pages")) {
2379                                                 return(new IXR_Error(401, __("You are not allowed to change the page author as this user.")));
2380                                         }
2381                                         break;
2382                                 default:
2383                                         return(new IXR_Error(401, __("Invalid post type.")));
2384                                         break;
2385                         }
2386                         $post_author = $content_struct["wp_author_id"];
2387                 }
2388
2389                 if(isset($content_struct["mt_allow_comments"])) {
2390                         if(!is_numeric($content_struct["mt_allow_comments"])) {
2391                                 switch($content_struct["mt_allow_comments"]) {
2392                                         case "closed":
2393                                                 $comment_status = "closed";
2394                                                 break;
2395                                         case "open":
2396                                                 $comment_status = "open";
2397                                                 break;
2398                                         default:
2399                                                 $comment_status = get_option("default_comment_status");
2400                                                 break;
2401                                 }
2402                         }
2403                         else {
2404                                 switch((int) $content_struct["mt_allow_comments"]) {
2405                                         case 0:
2406                                         case 2:
2407                                                 $comment_status = "closed";
2408                                                 break;
2409                                         case 1:
2410                                                 $comment_status = "open";
2411                                                 break;
2412                                         default:
2413                                                 $comment_status = get_option("default_comment_status");
2414                                                 break;
2415                                 }
2416                         }
2417                 }
2418
2419                 if(isset($content_struct["mt_allow_pings"])) {
2420                         if(!is_numeric($content_struct["mt_allow_pings"])) {
2421                                 switch($content_struct["mt_allow_pings"]) {
2422                                         case "closed":
2423                                                 $ping_status = "closed";
2424                                                 break;
2425                                         case "open":
2426                                                 $ping_status = "open";
2427                                                 break;
2428                                         default:
2429                                                 $ping_status = get_option("default_ping_status");
2430                                                 break;
2431                                 }
2432                         }
2433                         else {
2434                                 switch((int) $content_struct["mt_allow_pings"]) {
2435                                         case 0:
2436                                                 $ping_status = "closed";
2437                                                 break;
2438                                         case 1:
2439                                                 $ping_status = "open";
2440                                                 break;
2441                                         default:
2442                                                 $ping_status = get_option("default_ping_status");
2443                                                 break;
2444                                 }
2445                         }
2446                 }
2447
2448                 $post_title = $content_struct['title'];
2449                 $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
2450                 $catnames = $content_struct['categories'];
2451
2452                 $post_category = array();
2453
2454                 if (is_array($catnames)) {
2455                         foreach ($catnames as $cat) {
2456                                 $post_category[] = get_cat_ID($cat);
2457                         }
2458                 }
2459
2460                 $post_excerpt = $content_struct['mt_excerpt'];
2461                 $post_more = $content_struct['mt_text_more'];
2462
2463                 $post_status = $publish ? 'publish' : 'draft';
2464                 if( isset( $content_struct["{$post_type}_status"] ) ) {
2465                         switch( $content_struct["{$post_type}_status"] ) {
2466                                 case 'draft':
2467                                 case 'private':
2468                                 case 'publish':
2469                                         $post_status = $content_struct["{$post_type}_status"];
2470                                         break;
2471                                 case 'pending':
2472                                         // Pending is only valid for posts, not pages.
2473                                         if( $post_type === 'post' ) {
2474                                                 $post_status = $content_struct["{$post_type}_status"];
2475                                         }
2476                                         break;
2477                                 default:
2478                                         $post_status = $publish ? 'publish' : 'draft';
2479                                         break;
2480                         }
2481                 }
2482
2483                 $tags_input = $content_struct['mt_keywords'];
2484
2485                 if ( ('publish' == $post_status) ) {
2486                         if ( ( 'page' == $post_type ) && !current_user_can('publish_pages') )
2487                                 return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.'));
2488                         else if ( !current_user_can('publish_posts') )
2489                                 return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
2490                 }
2491
2492                 if ($post_more) {
2493                         $post_content = $post_content . "<!--more-->" . $post_more;
2494                 }
2495
2496                 $to_ping = $content_struct['mt_tb_ping_urls'];
2497                 if ( is_array($to_ping) )
2498                         $to_ping = implode(' ', $to_ping);
2499
2500                 // Do some timestamp voodoo
2501                 if ( !empty( $content_struct['date_created_gmt'] ) )
2502                         $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force
2503                 elseif ( !empty( $content_struct['dateCreated']) )
2504                         $dateCreated = $content_struct['dateCreated']->getIso();
2505
2506                 if ( !empty( $dateCreated ) ) {
2507                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
2508                         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
2509                 } else {
2510                         $post_date     = $postdata['post_date'];
2511                         $post_date_gmt = $postdata['post_date_gmt'];
2512                 }
2513
2514                 // We've got all the data -- post it:
2515                 $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');
2516
2517                 $result = wp_update_post($newpost, true);
2518                 if ( is_wp_error( $result ) )
2519                         return new IXR_Error(500, $result->get_error_message());
2520
2521                 if (!$result) {
2522                         return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.'));
2523                 }
2524
2525                 // Only posts can be sticky
2526                 if ( $post_type == 'post' && isset( $content_struct['sticky'] ) )
2527                         if ( $content_struct['sticky'] == true )
2528                                 stick_post( $post_ID );
2529                         elseif ( $content_struct['sticky'] == false )
2530                                 unstick_post( $post_ID );
2531
2532                 if ( isset($content_struct['custom_fields']) ) {
2533                         $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
2534                 }
2535
2536                 // Handle enclosures
2537                 $this->add_enclosure_if_new($post_ID, $content_struct['enclosure']);
2538
2539                 $this->attach_uploads( $ID, $post_content );
2540
2541                 logIO('O',"(MW) Edited ! ID: $post_ID");
2542
2543                 return true;
2544         }
2545
2546         /**
2547          * Retrieve post.
2548          *
2549          * @since 1.5.0
2550          *
2551          * @param array $args Method parameters.
2552          * @return array
2553          */
2554         function mw_getPost($args) {
2555
2556                 $this->escape($args);
2557
2558                 $post_ID     = (int) $args[0];
2559                 $username  = $args[1];
2560                 $password   = $args[2];
2561
2562                 if ( !$user = $this->login($username, $password) ) {
2563                         return $this->error;
2564                 }
2565
2566                 if( !current_user_can( 'edit_post', $post_ID ) )
2567                         return new IXR_Error( 401, __( 'Sorry, you cannot edit this post.' ) );
2568
2569                 do_action('xmlrpc_call', 'metaWeblog.getPost');
2570
2571                 $postdata = wp_get_single_post($post_ID, ARRAY_A);
2572
2573                 if ($postdata['post_date'] != '') {
2574                         $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date'], false);
2575                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $postdata['post_date_gmt'], false);
2576
2577                         $categories = array();
2578                         $catids = wp_get_post_categories($post_ID);
2579                         foreach($catids as $catid)
2580                                 $categories[] = get_cat_name($catid);
2581
2582                         $tagnames = array();
2583                         $tags = wp_get_post_tags( $post_ID );
2584                         if ( !empty( $tags ) ) {
2585                                 foreach ( $tags as $tag )
2586                                         $tagnames[] = $tag->name;
2587                                 $tagnames = implode( ', ', $tagnames );
2588                         } else {
2589                                 $tagnames = '';
2590                         }
2591
2592                         $post = get_extended($postdata['post_content']);
2593                         $link = post_permalink($postdata['ID']);
2594
2595                         // Get the author info.
2596                         $author = get_userdata($postdata['post_author']);
2597
2598                         $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
2599                         $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0;
2600
2601                         // Consider future posts as published
2602                         if( $postdata['post_status'] === 'future' ) {
2603                                 $postdata['post_status'] = 'publish';
2604                         }
2605
2606                         $sticky = false;
2607                         if ( is_sticky( $post_ID ) )
2608                                 $sticky = true;
2609
2610                         $enclosure = array();
2611                         foreach ( (array) get_post_custom($post_ID) as $key => $val) {
2612                                 if ($key == 'enclosure') {
2613                                         foreach ( (array) $val as $enc ) {
2614                                                 $encdata = split("\n", $enc);
2615                                                 $enclosure['url'] = trim(htmlspecialchars($encdata[0]));
2616                                                 $enclosure['length'] = trim($encdata[1]);
2617                                                 $enclosure['type'] = trim($encdata[2]);
2618                                                 break 2;
2619                                         }
2620                                 }
2621                         }
2622
2623                         $resp = array(
2624                                 'dateCreated' => new IXR_Date($post_date),
2625                                 'userid' => $postdata['post_author'],
2626                                 'postid' => $postdata['ID'],
2627                                 'description' => $post['main'],
2628                                 'title' => $postdata['post_title'],
2629                                 'link' => $link,
2630                                 'permaLink' => $link,
2631                                 // commented out because no other tool seems to use this
2632                                 //            'content' => $entry['post_content'],
2633                                 'categories' => $categories,
2634                                 'mt_excerpt' => $postdata['post_excerpt'],
2635                                 'mt_text_more' => $post['extended'],
2636                                 'mt_allow_comments' => $allow_comments,
2637                                 'mt_allow_pings' => $allow_pings,
2638                                 'mt_keywords' => $tagnames,
2639                                 'wp_slug' => $postdata['post_name'],
2640                                 'wp_password' => $postdata['post_password'],
2641                                 'wp_author_id' => $author->ID,
2642                                 'wp_author_display_name'        => $author->display_name,
2643                                 'date_created_gmt' => new IXR_Date($post_date_gmt),
2644                                 'post_status' => $postdata['post_status'],
2645                                 'custom_fields' => $this->get_custom_fields($post_ID),
2646                                 'sticky' => $sticky
2647                         );
2648
2649                         if (!empty($enclosure)) $resp['enclosure'] = $enclosure;
2650
2651                         return $resp;
2652                 } else {
2653                         return new IXR_Error(404, __('Sorry, no such post.'));
2654                 }
2655         }
2656
2657         /**
2658          * Retrieve list of recent posts.
2659          *
2660          * @since 1.5.0
2661          *
2662          * @param array $args Method parameters.
2663          * @return array
2664          */
2665         function mw_getRecentPosts($args) {
2666
2667                 $this->escape($args);
2668
2669                 $blog_ID     = (int) $args[0];
2670                 $username  = $args[1];
2671                 $password   = $args[2];
2672                 $num_posts   = (int) $args[3];
2673
2674                 if ( !$user = $this->login($username, $password) ) {
2675                         return $this->error;
2676                 }
2677
2678                 do_action('xmlrpc_call', 'metaWeblog.getRecentPosts');
2679
2680                 $posts_list = wp_get_recent_posts($num_posts);
2681
2682                 if (!$posts_list) {
2683                         return array( );
2684                 }
2685
2686                 foreach ($posts_list as $entry) {
2687                         if( !current_user_can( 'edit_post', $entry['ID'] ) )
2688                                 continue;
2689
2690                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date'], false);
2691                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt'], false);
2692
2693                         $categories = array();
2694                         $catids = wp_get_post_categories($entry['ID']);
2695                         foreach($catids as $catid) {
2696                                 $categories[] = get_cat_name($catid);
2697                         }
2698
2699                         $tagnames = array();
2700                         $tags = wp_get_post_tags( $entry['ID'] );
2701                         if ( !empty( $tags ) ) {
2702                                 foreach ( $tags as $tag ) {
2703                                         $tagnames[] = $tag->name;
2704                                 }
2705                                 $tagnames = implode( ', ', $tagnames );
2706                         } else {
2707                                 $tagnames = '';
2708                         }
2709
2710                         $post = get_extended($entry['post_content']);
2711                         $link = post_permalink($entry['ID']);
2712
2713                         // Get the post author info.
2714                         $author = get_userdata($entry['post_author']);
2715
2716                         $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
2717                         $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0;
2718
2719                         // Consider future posts as published
2720                         if( $entry['post_status'] === 'future' ) {
2721                                 $entry['post_status'] = 'publish';
2722                         }
2723
2724                         $struct[] = array(
2725                                 'dateCreated' => new IXR_Date($post_date),
2726                                 'userid' => $entry['post_author'],
2727                                 'postid' => $entry['ID'],
2728                                 'description' => $post['main'],
2729                                 'title' => $entry['post_title'],
2730                                 'link' => $link,
2731                                 'permaLink' => $link,
2732                                 // commented out because no other tool seems to use this
2733                                 // 'content' => $entry['post_content'],
2734                                 'categories' => $categories,
2735                                 'mt_excerpt' => $entry['post_excerpt'],
2736                                 'mt_text_more' => $post['extended'],
2737                                 'mt_allow_comments' => $allow_comments,
2738                                 'mt_allow_pings' => $allow_pings,
2739                                 'mt_keywords' => $tagnames,
2740                                 'wp_slug' => $entry['post_name'],
2741                                 'wp_password' => $entry['post_password'],
2742                                 'wp_author_id' => $author->ID,
2743                                 'wp_author_display_name' => $author->display_name,
2744                                 'date_created_gmt' => new IXR_Date($post_date_gmt),
2745                                 'post_status' => $entry['post_status'],
2746                                 'custom_fields' => $this->get_custom_fields($entry['ID'])
2747                         );
2748
2749                 }
2750
2751                 $recent_posts = array();
2752                 for ($j=0; $j<count($struct); $j++) {
2753                         array_push($recent_posts, $struct[$j]);
2754                 }
2755
2756                 return $recent_posts;
2757         }
2758
2759         /**
2760          * Retrieve the list of categories on a given blog.
2761          *
2762          * @since 1.5.0
2763          *
2764          * @param array $args Method parameters.
2765          * @return array
2766          */
2767         function mw_getCategories($args) {
2768
2769                 $this->escape($args);
2770
2771                 $blog_ID     = (int) $args[0];
2772                 $username  = $args[1];
2773                 $password   = $args[2];
2774
2775                 if ( !$user = $this->login($username, $password) ) {
2776                         return $this->error;
2777                 }
2778
2779                 if( !current_user_can( 'edit_posts' ) )
2780                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
2781
2782                 do_action('xmlrpc_call', 'metaWeblog.getCategories');
2783
2784                 $categories_struct = array();
2785
2786                 if ( $cats = get_categories('get=all') ) {
2787                         foreach ( $cats as $cat ) {
2788                                 $struct['categoryId'] = $cat->term_id;
2789                                 $struct['parentId'] = $cat->parent;
2790                                 $struct['description'] = $cat->name;
2791                                 $struct['categoryDescription'] = $cat->description;
2792                                 $struct['categoryName'] = $cat->name;
2793                                 $struct['htmlUrl'] = esc_html(get_category_link($cat->term_id));
2794                                 $struct['rssUrl'] = esc_html(get_category_feed_link($cat->term_id, 'rss2'));
2795
2796                                 $categories_struct[] = $struct;
2797                         }
2798                 }
2799
2800                 return $categories_struct;
2801         }
2802
2803         /**
2804          * Uploads a file, following your settings.
2805          *
2806          * Adapted from a patch by Johann Richard.
2807          *
2808          * @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
2809          *
2810          * @since 1.5.0
2811          *
2812          * @param array $args Method parameters.
2813          * @return array
2814          */
2815         function mw_newMediaObject($args) {
2816                 global $wpdb;
2817
2818                 $blog_ID     = (int) $args[0];
2819                 $username  = $wpdb->escape($args[1]);
2820                 $password   = $wpdb->escape($args[2]);
2821                 $data        = $args[3];
2822
2823                 $name = sanitize_file_name( $data['name'] );
2824                 $type = $data['type'];
2825                 $bits = $data['bits'];
2826
2827                 logIO('O', '(MW) Received '.strlen($bits).' bytes');
2828
2829                 if ( !$user = $this->login($username, $password) ) {
2830                         return $this->error;
2831                 }
2832
2833                 do_action('xmlrpc_call', 'metaWeblog.newMediaObject');
2834
2835                 if ( !current_user_can('upload_files') ) {
2836                         logIO('O', '(MW) User does not have upload_files capability');
2837                         $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
2838                         return $this->error;
2839                 }
2840
2841                 if ( $upload_err = apply_filters( "pre_upload_error", false ) )
2842                         return new IXR_Error(500, $upload_err);
2843
2844                 if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
2845                         // Get postmeta info on the object.
2846                         $old_file = $wpdb->get_row("
2847                                 SELECT ID
2848                                 FROM {$wpdb->posts}
2849                                 WHERE post_title = '{$name}'
2850                                         AND post_type = 'attachment'
2851                         ");
2852
2853                         // Delete previous file.
2854                         wp_delete_attachment($old_file->ID);
2855
2856                         // Make sure the new name is different by pre-pending the
2857                         // previous post id.
2858                         $filename = preg_replace("/^wpid\d+-/", "", $name);
2859                         $name = "wpid{$old_file->ID}-{$filename}";
2860                 }
2861
2862                 $upload = wp_upload_bits($name, $type, $bits);
2863                 if ( ! empty($upload['error']) ) {
2864                         $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']);
2865                         logIO('O', '(MW) ' . $errorString);
2866                         return new IXR_Error(500, $errorString);
2867                 }
2868                 // Construct the attachment array
2869                 // attach to post_id -1
2870                 $post_id = -1;
2871                 $attachment = array(
2872                         'post_title' => $name,
2873                         'post_content' => '',
2874                         'post_type' => 'attachment',
2875                         'post_parent' => $post_id,
2876                         'post_mime_type' => $type,
2877                         'guid' => $upload[ 'url' ]
2878                 );
2879
2880                 // Save the data
2881                 $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
2882                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
2883
2884                 return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
2885         }
2886
2887         /* MovableType API functions
2888          * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
2889          */
2890
2891         /**
2892          * Retrieve the post titles of recent posts.
2893          *
2894          * @since 1.5.0
2895          *
2896          * @param array $args Method parameters.
2897          * @return array
2898          */
2899         function mt_getRecentPostTitles($args) {
2900
2901                 $this->escape($args);
2902
2903                 $blog_ID     = (int) $args[0];
2904                 $username  = $args[1];
2905                 $password   = $args[2];
2906                 $num_posts   = (int) $args[3];
2907
2908                 if ( !$user = $this->login($username, $password) ) {
2909                         return $this->error;
2910                 }
2911
2912                 do_action('xmlrpc_call', 'mt.getRecentPostTitles');
2913
2914                 $posts_list = wp_get_recent_posts($num_posts);
2915
2916                 if (!$posts_list) {
2917                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
2918                         return $this->error;
2919                 }
2920
2921                 foreach ($posts_list as $entry) {
2922                         if( !current_user_can( 'edit_post', $entry['ID'] ) )
2923                                 continue;
2924
2925                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date'], false);
2926                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt'], false);
2927
2928                         $struct[] = array(
2929                                 'dateCreated' => new IXR_Date($post_date),
2930                                 'userid' => $entry['post_author'],
2931                                 'postid' => $entry['ID'],
2932                                 'title' => $entry['post_title'],
2933                                 'date_created_gmt' => new IXR_Date($post_date_gmt)
2934                         );
2935
2936                 }
2937
2938                 $recent_posts = array();
2939                 for ($j=0; $j<count($struct); $j++) {
2940                         array_push($recent_posts, $struct[$j]);
2941                 }
2942
2943                 return $recent_posts;
2944         }
2945
2946         /**
2947          * Retrieve list of all categories on blog.
2948          *
2949          * @since 1.5.0
2950          *
2951          * @param array $args Method parameters.
2952          * @return array
2953          */
2954         function mt_getCategoryList($args) {
2955
2956                 $this->escape($args);
2957
2958                 $blog_ID     = (int) $args[0];
2959                 $username  = $args[1];
2960                 $password   = $args[2];
2961
2962                 if ( !$user = $this->login($username, $password) ) {
2963                         return $this->error;
2964                 }
2965
2966                 if( !current_user_can( 'edit_posts' ) )
2967                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
2968
2969                 do_action('xmlrpc_call', 'mt.getCategoryList');
2970
2971                 $categories_struct = array();
2972
2973                 if ( $cats = get_categories('hide_empty=0&hierarchical=0') ) {
2974                         foreach ($cats as $cat) {
2975                                 $struct['categoryId'] = $cat->term_id;
2976                                 $struct['categoryName'] = $cat->name;
2977
2978                                 $categories_struct[] = $struct;
2979                         }
2980                 }
2981
2982                 return $categories_struct;
2983         }
2984
2985         /**
2986          * Retrieve post categories.
2987          *
2988          * @since 1.5.0
2989          *
2990          * @param array $args Method parameters.
2991          * @return array
2992          */
2993         function mt_getPostCategories($args) {
2994
2995                 $this->escape($args);
2996
2997                 $post_ID     = (int) $args[0];
2998                 $username  = $args[1];
2999                 $password   = $args[2];
3000
3001                 if ( !$user = $this->login($username, $password) ) {
3002                         return $this->error;
3003                 }
3004
3005                 if( !current_user_can( 'edit_post', $post_ID ) )
3006                         return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
3007
3008                 do_action('xmlrpc_call', 'mt.getPostCategories');
3009
3010                 $categories = array();
3011                 $catids = wp_get_post_categories(intval($post_ID));
3012                 // first listed category will be the primary category
3013                 $isPrimary = true;
3014                 foreach($catids as $catid) {
3015                         $categories[] = array(
3016                                 'categoryName' => get_cat_name($catid),
3017                                 'categoryId' => (string) $catid,
3018                                 'isPrimary' => $isPrimary
3019                         );
3020                         $isPrimary = false;
3021                 }
3022
3023                 return $categories;
3024         }
3025
3026         /**
3027          * Sets categories for a post.
3028          *
3029          * @since 1.5.0
3030          *
3031          * @param array $args Method parameters.
3032          * @return bool True on success.
3033          */
3034         function mt_setPostCategories($args) {
3035
3036                 $this->escape($args);
3037
3038                 $post_ID     = (int) $args[0];
3039                 $username  = $args[1];
3040                 $password   = $args[2];
3041                 $categories  = $args[3];
3042
3043                 if ( !$user = $this->login($username, $password) ) {
3044                         return $this->error;
3045                 }
3046
3047                 do_action('xmlrpc_call', 'mt.setPostCategories');
3048
3049                 if ( !current_user_can('edit_post', $post_ID) )
3050                         return new IXR_Error(401, __('Sorry, you cannot edit this post.'));
3051
3052                 foreach($categories as $cat) {
3053                         $catids[] = $cat['categoryId'];
3054                 }
3055
3056                 wp_set_post_categories($post_ID, $catids);
3057
3058                 return true;
3059         }
3060
3061         /**
3062          * Retrieve an array of methods supported by this server.
3063          *
3064          * @since 1.5.0
3065          *
3066          * @param array $args Method parameters.
3067          * @return array
3068          */
3069         function mt_supportedMethods($args) {
3070
3071                 do_action('xmlrpc_call', 'mt.supportedMethods');
3072
3073                 $supported_methods = array();
3074                 foreach($this->methods as $key=>$value) {
3075                         $supported_methods[] = $key;
3076                 }
3077
3078                 return $supported_methods;
3079         }
3080
3081         /**
3082          * Retrieve an empty array because we don't support per-post text filters.
3083          *
3084          * @since 1.5.0
3085          *
3086          * @param array $args Method parameters.
3087          */
3088         function mt_supportedTextFilters($args) {
3089                 do_action('xmlrpc_call', 'mt.supportedTextFilters');
3090                 return apply_filters('xmlrpc_text_filters', array());
3091         }
3092
3093         /**
3094          * Retrieve trackbacks sent to a given post.
3095          *
3096          * @since 1.5.0
3097          *
3098          * @param array $args Method parameters.
3099          * @return mixed
3100          */
3101         function mt_getTrackbackPings($args) {
3102
3103                 global $wpdb;
3104
3105                 $post_ID = intval($args);
3106
3107                 do_action('xmlrpc_call', 'mt.getTrackbackPings');
3108
3109                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
3110
3111                 if (!$actual_post) {
3112                         return new IXR_Error(404, __('Sorry, no such post.'));
3113                 }
3114
3115                 $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) );
3116
3117                 if (!$comments) {
3118                         return array();
3119                 }
3120
3121                 $trackback_pings = array();
3122                 foreach($comments as $comment) {
3123                         if ( 'trackback' == $comment->comment_type ) {
3124                                 $content = $comment->comment_content;
3125                                 $title = substr($content, 8, (strpos($content, '</strong>') - 8));
3126                                 $trackback_pings[] = array(
3127                                         'pingTitle' => $title,
3128                                         'pingURL'   => $comment->comment_author_url,
3129                                         'pingIP'    => $comment->comment_author_IP
3130                                 );
3131                 }
3132                 }
3133
3134                 return $trackback_pings;
3135         }
3136
3137         /**
3138          * Sets a post's publish status to 'publish'.
3139          *
3140          * @since 1.5.0
3141          *
3142          * @param array $args Method parameters.
3143          * @return int
3144          */
3145         function mt_publishPost($args) {
3146
3147                 $this->escape($args);
3148
3149                 $post_ID     = (int) $args[0];
3150                 $username  = $args[1];
3151                 $password   = $args[2];
3152
3153                 if ( !$user = $this->login($username, $password) ) {
3154                         return $this->error;
3155                 }
3156
3157                 do_action('xmlrpc_call', 'mt.publishPost');
3158
3159                 if ( !current_user_can('edit_post', $post_ID) )
3160                         return new IXR_Error(401, __('Sorry, you cannot edit this post.'));
3161
3162                 $postdata = wp_get_single_post($post_ID,ARRAY_A);
3163
3164                 $postdata['post_status'] = 'publish';
3165
3166                 // retain old cats
3167                 $cats = wp_get_post_categories($post_ID);
3168                 $postdata['post_category'] = $cats;
3169                 $this->escape($postdata);
3170
3171                 $result = wp_update_post($postdata);
3172
3173                 return $result;
3174         }
3175
3176         /* PingBack functions
3177          * specs on www.hixie.ch/specs/pingback/pingback
3178          */
3179
3180         /**
3181          * Retrieves a pingback and registers it.
3182          *
3183          * @since 1.5.0
3184          *
3185          * @param array $args Method parameters.
3186          * @return array
3187          */
3188         function pingback_ping($args) {
3189                 global $wpdb;
3190
3191                 do_action('xmlrpc_call', 'pingback.ping');
3192
3193                 $this->escape($args);
3194
3195                 $pagelinkedfrom = $args[0];
3196                 $pagelinkedto   = $args[1];
3197
3198                 $title = '';
3199
3200                 $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
3201                 $pagelinkedto = str_replace('&amp;', '&', $pagelinkedto);
3202                 $pagelinkedto = str_replace('&', '&amp;', $pagelinkedto);
3203
3204                 // Check if the page linked to is in our site
3205                 $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
3206                 if( !$pos1 )
3207                         return new IXR_Error(0, __('Is there no link to us?'));
3208
3209                 // let's find which post is linked to
3210                 // FIXME: does url_to_postid() cover all these cases already?
3211                 //        if so, then let's use it and drop the old code.
3212                 $urltest = parse_url($pagelinkedto);
3213                 if ($post_ID = url_to_postid($pagelinkedto)) {
3214                         $way = 'url_to_postid()';
3215                 } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
3216                         // the path defines the post_ID (archives/p/XXXX)
3217                         $blah = explode('/', $match[0]);
3218                         $post_ID = (int) $blah[1];
3219                         $way = 'from the path';
3220                 } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
3221                         // the querystring defines the post_ID (?p=XXXX)
3222                         $blah = explode('=', $match[0]);
3223                         $post_ID = (int) $blah[1];
3224                         $way = 'from the querystring';
3225                 } elseif (isset($urltest['fragment'])) {
3226                         // an #anchor is there, it's either...
3227                         if (intval($urltest['fragment'])) {
3228                                 // ...an integer #XXXX (simpliest case)
3229                                 $post_ID = (int) $urltest['fragment'];
3230                                 $way = 'from the fragment (numeric)';
3231                         } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) {
3232                                 // ...a post id in the form 'post-###'
3233                                 $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
3234                                 $way = 'from the fragment (post-###)';
3235                         } elseif (is_string($urltest['fragment'])) {
3236                                 // ...or a string #title, a little more complicated
3237                                 $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
3238                                 $sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title);
3239                                 if (! ($post_ID = $wpdb->get_var($sql)) ) {
3240                                         // returning unknown error '0' is better than die()ing
3241                                         return new IXR_Error(0, '');
3242                                 }
3243                                 $way = 'from the fragment (title)';
3244                         }
3245                 } else {
3246                         // TODO: Attempt to extract a post ID from the given URL
3247                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn&#8217;t exist, or it is not a pingback-enabled resource.'));
3248                 }
3249                 $post_ID = (int) $post_ID;
3250
3251
3252                 logIO("O","(PB) URL='$pagelinkedto' ID='$post_ID' Found='$way'");
3253
3254                 $post = get_post($post_ID);
3255
3256                 if ( !$post ) // Post_ID not found
3257                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn&#8217;t exist, or it is not a pingback-enabled resource.'));
3258
3259                 if ( $post_ID == url_to_postid($pagelinkedfrom) )
3260                         return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.'));
3261
3262                 // Check if pings are on
3263                 if ( !pings_open($post) )
3264                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn&#8217;t exist, or it is not a pingback-enabled resource.'));
3265
3266                 // Let's check that the remote site didn't already pingback this entry
3267                 $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom) );
3268
3269                 if ( $wpdb->num_rows ) // We already have a Pingback from this URL
3270                         return new IXR_Error(48, __('The pingback has already been registered.'));
3271
3272                 // very stupid, but gives time to the 'from' server to publish !
3273                 sleep(1);
3274
3275                 // Let's check the remote site
3276                 $linea = wp_remote_fopen( $pagelinkedfrom );
3277                 if ( !$linea )
3278                         return new IXR_Error(16, __('The source URL does not exist.'));
3279
3280                 $linea = apply_filters('pre_remote_source', $linea, $pagelinkedto);
3281
3282                 // Work around bug in strip_tags():
3283                 $linea = str_replace('<!DOC', '<DOC', $linea);
3284                 $linea = preg_replace( '/[\s\r\n\t]+/', ' ', $linea ); // normalize spaces
3285                 $linea = preg_replace( "/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea );
3286
3287                 preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
3288                 $title = $matchtitle[1];
3289                 if ( empty( $title ) )
3290                         return new IXR_Error(32, __('We cannot find a title on that page.'));
3291
3292                 $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
3293
3294                 $p = explode( "\n\n", $linea );
3295
3296                 $preg_target = preg_quote($pagelinkedto);
3297
3298                 foreach ( $p as $para ) {
3299                         if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link?
3300                                 preg_match("|<a[^>]+?".$preg_target."[^>]*>([^>]+?)</a>|", $para, $context);
3301
3302                                 // If the URL isn't in a link context, keep looking
3303                                 if ( empty($context) )
3304                                         continue;
3305
3306                                 // We're going to use this fake tag to mark the context in a bit
3307                                 // the marker is needed in case the link text appears more than once in the paragraph
3308                                 $excerpt = preg_replace('|\</?wpcontext\>|', '', $para);
3309
3310                                 // prevent really long link text
3311                                 if ( strlen($context[1]) > 100 )
3312                                         $context[1] = substr($context[1], 0, 100) . '...';
3313
3314                                 $marker = '<wpcontext>'.$context[1].'</wpcontext>';    // set up our marker
3315                                 $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
3316                                 $excerpt = strip_tags($excerpt, '<wpcontext>');        // strip all tags but our context marker
3317                                 $excerpt = trim($excerpt);
3318                                 $preg_marker = preg_quote($marker);
3319                                 $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
3320                                 $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
3321                                 break;
3322                         }
3323                 }
3324
3325                 if ( empty($context) ) // Link to target not found
3326                         return new IXR_Error(17, __('The source URL does not contain a link to the target URL, and so cannot be used as a source.'));
3327
3328                 $pagelinkedfrom = str_replace('&', '&amp;', $pagelinkedfrom);
3329
3330                 $context = '[...] ' . esc_html( $excerpt ) . ' [...]';
3331                 $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom );
3332
3333                 $comment_post_ID = (int) $post_ID;
3334                 $comment_author = $title;
3335                 $this->escape($comment_author);
3336                 $comment_author_url = $pagelinkedfrom;
3337                 $comment_content = $context;
3338                 $this->escape($comment_content);
3339                 $comment_type = 'pingback';
3340
3341                 $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type');
3342
3343                 $comment_ID = wp_new_comment($commentdata);
3344                 do_action('pingback_post', $comment_ID);
3345
3346                 return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto);
3347         }
3348
3349         /**
3350          * Retrieve array of URLs that pingbacked the given URL.
3351          *
3352          * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
3353          *
3354          * @since 1.5.0
3355          *
3356          * @param array $args Method parameters.
3357          * @return array
3358          */
3359         function pingback_extensions_getPingbacks($args) {
3360
3361                 global $wpdb;
3362
3363                 do_action('xmlrpc_call', 'pingback.extensions.getPingbacks');
3364
3365                 $this->escape($args);
3366
3367                 $url = $args;
3368
3369                 $post_ID = url_to_postid($url);
3370                 if (!$post_ID) {
3371                         // We aren't sure that the resource is available and/or pingback enabled
3372                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn&#8217;t exist, or it is not a pingback-enabled resource.'));
3373                 }
3374
3375                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
3376
3377                 if (!$actual_post) {
3378                         // No such post = resource not found
3379                         return new IXR_Error(32, __('The specified target URL does not exist.'));
3380                 }
3381
3382                 $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) );
3383
3384                 if (!$comments) {
3385                         return array();
3386                 }
3387
3388                 $pingbacks = array();
3389                 foreach($comments as $comment) {
3390                         if ( 'pingback' == $comment->comment_type )
3391                                 $pingbacks[] = $comment->comment_author_url;
3392                 }
3393
3394                 return $pingbacks;
3395         }
3396 }
3397
3398 $wp_xmlrpc_server = new wp_xmlrpc_server();
3399
3400 ?>