Wordpress 2.5.1
[autoinstalls/wordpress.git] / xmlrpc.php
1 <?php
2
3 define('XMLRPC_REQUEST', true);
4
5 // Some browser-embedded clients send cookies. We don't want them.
6 $_COOKIE = array();
7
8 // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
9 // but we can do it ourself.
10 if ( !isset( $HTTP_RAW_POST_DATA ) ) {
11         $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
12 }
13
14 # fix for mozBlog and other cases where '<?xml' isn't on the very first line
15 if ( isset($HTTP_RAW_POST_DATA) )
16         $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
17
18 include('./wp-config.php');
19
20 if ( isset( $_GET['rsd'] ) ) { // http://archipelago.phrasewise.com/rsd
21 header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true);
22 ?>
23 <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
24 <rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
25   <service>
26     <engineName>WordPress</engineName>
27     <engineLink>http://wordpress.org/</engineLink>
28     <homePageLink><?php bloginfo_rss('url') ?></homePageLink>
29     <apis>
30       <api name="WordPress" blogID="1" preferred="true" apiLink="<?php bloginfo_rss('wpurl') ?>/xmlrpc.php" />
31       <api name="Movable Type" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('wpurl') ?>/xmlrpc.php" />
32       <api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('wpurl') ?>/xmlrpc.php" />
33       <api name="Blogger" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('wpurl') ?>/xmlrpc.php" />
34       <api name="Atom" blogID="" preferred="false" apiLink="<?php echo apply_filters('atom_service_url', (get_bloginfo('url')."/wp-app.php/service"))?>" />
35     </apis>
36   </service>
37 </rsd>
38 <?php
39 exit;
40 }
41
42 include_once(ABSPATH . 'wp-admin/includes/admin.php');
43 include_once(ABSPATH . WPINC . '/class-IXR.php');
44
45 // Turn off all warnings and errors.
46 // error_reporting(0);
47
48 $post_default_title = ""; // posts submitted via the xmlrpc interface get that title
49
50 $xmlrpc_logging = 0;
51
52 function logIO($io,$msg) {
53         global $xmlrpc_logging;
54         if ($xmlrpc_logging) {
55                 $fp = fopen("../xmlrpc.log","a+");
56                 $date = gmdate("Y-m-d H:i:s ");
57                 $iot = ($io == "I") ? " Input: " : " Output: ";
58                 fwrite($fp, "\n\n".$date.$iot.$msg);
59                 fclose($fp);
60         }
61         return true;
62         }
63
64 function starify($string) {
65         $i = strlen($string);
66         return str_repeat('*', $i);
67 }
68
69 if ( isset($HTTP_RAW_POST_DATA) )
70   logIO("I", $HTTP_RAW_POST_DATA);
71
72 class wp_xmlrpc_server extends IXR_Server {
73
74         function wp_xmlrpc_server() {
75                 $this->methods = array(
76                         // WordPress API
77                         'wp.getPage'                    => 'this:wp_getPage',
78                         'wp.getPages'                   => 'this:wp_getPages',
79                         'wp.newPage'                    => 'this:wp_newPage',
80                         'wp.deletePage'                 => 'this:wp_deletePage',
81                         'wp.editPage'                   => 'this:wp_editPage',
82                         'wp.getPageList'                => 'this:wp_getPageList',
83                         'wp.getAuthors'                 => 'this:wp_getAuthors',
84                         'wp.getCategories'              => 'this:mw_getCategories',             // Alias
85                         'wp.newCategory'                => 'this:wp_newCategory',
86                         'wp.deleteCategory'             => 'this:wp_deleteCategory',
87                         'wp.suggestCategories'  => 'this:wp_suggestCategories',
88                         'wp.uploadFile'                 => 'this:mw_newMediaObject',    // Alias
89                         'wp.getCommentCount'    => 'this:wp_getCommentCount',
90                         'wp.getPostStatusList'  => 'this:wp_getPostStatusList',
91                         'wp.getPageStatusList'  => 'this:wp_getPageStatusList',
92
93                         // Blogger API
94                         'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
95                         'blogger.getUserInfo' => 'this:blogger_getUserInfo',
96                         'blogger.getPost' => 'this:blogger_getPost',
97                         'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
98                         'blogger.getTemplate' => 'this:blogger_getTemplate',
99                         'blogger.setTemplate' => 'this:blogger_setTemplate',
100                         'blogger.newPost' => 'this:blogger_newPost',
101                         'blogger.editPost' => 'this:blogger_editPost',
102                         'blogger.deletePost' => 'this:blogger_deletePost',
103
104                         // MetaWeblog API (with MT extensions to structs)
105                         'metaWeblog.newPost' => 'this:mw_newPost',
106                         'metaWeblog.editPost' => 'this:mw_editPost',
107                         'metaWeblog.getPost' => 'this:mw_getPost',
108                         'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
109                         'metaWeblog.getCategories' => 'this:mw_getCategories',
110                         'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',
111
112                         // MetaWeblog API aliases for Blogger API
113                         // see http://www.xmlrpc.com/stories/storyReader$2460
114                         'metaWeblog.deletePost' => 'this:blogger_deletePost',
115                         'metaWeblog.getTemplate' => 'this:blogger_getTemplate',
116                         'metaWeblog.setTemplate' => 'this:blogger_setTemplate',
117                         'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',
118
119                         // MovableType API
120                         'mt.getCategoryList' => 'this:mt_getCategoryList',
121                         'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
122                         'mt.getPostCategories' => 'this:mt_getPostCategories',
123                         'mt.setPostCategories' => 'this:mt_setPostCategories',
124                         'mt.supportedMethods' => 'this:mt_supportedMethods',
125                         'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
126                         'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
127                         'mt.publishPost' => 'this:mt_publishPost',
128
129                         // PingBack
130                         'pingback.ping' => 'this:pingback_ping',
131                         'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
132
133                         'demo.sayHello' => 'this:sayHello',
134                         'demo.addTwoNumbers' => 'this:addTwoNumbers'
135                 );
136                 $this->methods = apply_filters('xmlrpc_methods', $this->methods);
137                 $this->IXR_Server($this->methods);
138         }
139
140         function sayHello($args) {
141                 return 'Hello!';
142         }
143
144         function addTwoNumbers($args) {
145                 $number1 = $args[0];
146                 $number2 = $args[1];
147                 return $number1 + $number2;
148         }
149
150         function login_pass_ok($user_login, $user_pass) {
151                 if (!user_pass_ok($user_login, $user_pass)) {
152                         $this->error = new IXR_Error(403, __('Bad login/pass combination.'));
153                         return false;
154                 }
155                 return true;
156         }
157
158         function escape(&$array) {
159                 global $wpdb;
160
161                 if(!is_array($array)) {
162                         return($wpdb->escape($array));
163                 }
164                 else {
165                         foreach ( (array) $array as $k => $v ) {
166                                 if (is_array($v)) {
167                                         $this->escape($array[$k]);
168                                 } else if (is_object($v)) {
169                                         //skip
170                                 } else {
171                                         $array[$k] = $wpdb->escape($v);
172                                 }
173                         }
174                 }
175         }
176
177         function get_custom_fields($post_id) {
178                 $post_id = (int) $post_id;
179
180                 $custom_fields = array();
181
182                 foreach ( (array) has_meta($post_id) as $meta ) {
183                         // Don't expose protected fields.
184                         if ( strpos($meta['meta_key'], '_wp_') === 0 ) {
185                                 continue;
186                         }
187
188                         $custom_fields[] = array(
189                                 "id"    => $meta['meta_id'],
190                                 "key"   => $meta['meta_key'],
191                                 "value" => $meta['meta_value']
192                         );
193                 }
194
195                 return $custom_fields;
196         }
197
198         function set_custom_fields($post_id, $fields) {
199                 $post_id = (int) $post_id;
200
201                 foreach ( (array) $fields as $meta ) {
202                         if ( isset($meta['id']) ) {
203                                 $meta['id'] = (int) $meta['id'];
204
205                                 if ( isset($meta['key']) ) {
206                                         update_meta($meta['id'], $meta['key'], $meta['value']);
207                                 }
208                                 else {
209                                         delete_meta($meta['id']);
210                                 }
211                         }
212                         else {
213                                 $_POST['metakeyinput'] = $meta['key'];
214                                 $_POST['metavalue'] = $meta['value'];
215                                 add_meta($post_id);
216                         }
217                 }
218         }
219
220         /**
221          * WordPress XML-RPC API
222          * wp_getPage
223          */
224         function wp_getPage($args) {
225                 $this->escape($args);
226
227                 $blog_id        = (int) $args[0];
228                 $page_id        = (int) $args[1];
229                 $username       = $args[2];
230                 $password       = $args[3];
231
232                 if(!$this->login_pass_ok($username, $password)) {
233                         return($this->error);
234                 }
235
236                 set_current_user( 0, $username );
237                 if( !current_user_can( 'edit_page', $page_id ) )
238                         return new IXR_Error( 401, __( 'Sorry, you can not edit this page.' ) );
239
240                 do_action('xmlrpc_call', 'wp.getPage');
241
242                 // Lookup page info.
243                 $page = get_page($page_id);
244
245                 // If we found the page then format the data.
246                 if($page->ID && ($page->post_type == "page")) {
247                         // Get all of the page content and link.
248                         $full_page = get_extended($page->post_content);
249                         $link = post_permalink($page->ID);
250
251                         // Get info the page parent if there is one.
252                         $parent_title = "";
253                         if(!empty($page->post_parent)) {
254                                 $parent = get_page($page->post_parent);
255                                 $parent_title = $parent->post_title;
256                         }
257
258                         // Determine comment and ping settings.
259                         $allow_comments = ("open" == $page->comment_status) ? 1 : 0;
260                         $allow_pings = ("open" == $page->ping_status) ? 1 : 0;
261
262                         // Format page date.
263                         $page_date = mysql2date("Ymd\TH:i:s", $page->post_date);
264                         $page_date_gmt = mysql2date("Ymd\TH:i:s", $page->post_date_gmt);
265
266                         // Pull the categories info together.
267                         $categories = array();
268                         foreach(wp_get_post_categories($page->ID) as $cat_id) {
269                                 $categories[] = get_cat_name($cat_id);
270                         }
271
272                         // Get the author info.
273                         $author = get_userdata($page->post_author);
274
275                         $page_struct = array(
276                                 "dateCreated"                   => new IXR_Date($page_date),
277                                 "userid"                                => $page->post_author,
278                                 "page_id"                               => $page->ID,
279                                 "page_status"                   => $page->post_status,
280                                 "description"                   => $full_page["main"],
281                                 "title"                                 => $page->post_title,
282                                 "link"                                  => $link,
283                                 "permaLink"                             => $link,
284                                 "categories"                    => $categories,
285                                 "excerpt"                               => $page->post_excerpt,
286                                 "text_more"                             => $full_page["extended"],
287                                 "mt_allow_comments"             => $allow_comments,
288                                 "mt_allow_pings"                => $allow_pings,
289                                 "wp_slug"                               => $page->post_name,
290                                 "wp_password"                   => $page->post_password,
291                                 "wp_author"                             => $author->display_name,
292                                 "wp_page_parent_id"             => $page->post_parent,
293                                 "wp_page_parent_title"  => $parent_title,
294                                 "wp_page_order"                 => $page->menu_order,
295                                 "wp_author_id"                  => $author->ID,
296                                 "wp_author_display_name"        => $author->display_name,
297                                 "date_created_gmt"              => new IXR_Date($page_date_gmt),
298                                 "custom_fields"                 => $this->get_custom_fields($page_id)
299                         );
300
301                         return($page_struct);
302                 }
303                 // If the page doesn't exist indicate that.
304                 else {
305                         return(new IXR_Error(404, __("Sorry, no such page.")));
306                 }
307         }
308
309         /**
310          * WordPress XML-RPC API
311          * wp_getPages
312          */
313         function wp_getPages($args) {
314                 $this->escape($args);
315
316                 $blog_id        = (int) $args[0];
317                 $username       = $args[1];
318                 $password       = $args[2];
319
320                 if(!$this->login_pass_ok($username, $password)) {
321                         return($this->error);
322                 }
323
324                 set_current_user( 0, $username );
325                 if( !current_user_can( 'edit_pages' ) )
326                         return new IXR_Error( 401, __( 'Sorry, you can not edit pages.' ) );
327
328                 do_action('xmlrpc_call', 'wp.getPages');
329
330                 // Lookup info on pages.
331                 $pages = get_pages();
332                 $num_pages = count($pages);
333
334                 // If we have pages, put together their info.
335                 if($num_pages >= 1) {
336                         $pages_struct = array();
337
338                         for($i = 0; $i < $num_pages; $i++) {
339                                 $page = wp_xmlrpc_server::wp_getPage(array(
340                                         $blog_id, $pages[$i]->ID, $username, $password
341                                 ));
342                                 $pages_struct[] = $page;
343                         }
344
345                         return($pages_struct);
346                 }
347                 // If no pages were found return an error.
348                 else {
349                         return(array());
350                 }
351         }
352
353         /**
354          * WordPress XML-RPC API
355          * wp_newPage
356          */
357         function wp_newPage($args) {
358                 // Items not escaped here will be escaped in newPost.
359                 $username       = $this->escape($args[1]);
360                 $password       = $this->escape($args[2]);
361                 $page           = $args[3];
362                 $publish        = $args[4];
363
364                 if(!$this->login_pass_ok($username, $password)) {
365                         return($this->error);
366                 }
367
368                 do_action('xmlrpc_call', 'wp.newPage');
369
370                 // Set the user context and check if they are allowed
371                 // to add new pages.
372                 $user = set_current_user(0, $username);
373                 if(!current_user_can("publish_pages")) {
374                         return(new IXR_Error(401, __("Sorry, you can not add new pages.")));
375                 }
376
377                 // Mark this as content for a page.
378                 $args[3]["post_type"] = "page";
379
380                 // Let mw_newPost do all of the heavy lifting.
381                 return($this->mw_newPost($args));
382         }
383
384         /**
385          * WordPress XML-RPC API
386          * wp_deletePage
387          */
388         function wp_deletePage($args) {
389                 $this->escape($args);
390
391                 $blog_id        = (int) $args[0];
392                 $username       = $args[1];
393                 $password       = $args[2];
394                 $page_id        = (int) $args[3];
395
396                 if(!$this->login_pass_ok($username, $password)) {
397                         return($this->error);
398                 }
399
400                 do_action('xmlrpc_call', 'wp.deletePage');
401
402                 // Get the current page based on the page_id and
403                 // make sure it is a page and not a post.
404                 $actual_page = wp_get_single_post($page_id, ARRAY_A);
405                 if(
406                         !$actual_page
407                         || ($actual_page["post_type"] != "page")
408                 ) {
409                         return(new IXR_Error(404, __("Sorry, no such page.")));
410                 }
411
412                 // Set the user context and make sure they can delete pages.
413                 set_current_user(0, $username);
414                 if(!current_user_can("delete_page", $page_id)) {
415                         return(new IXR_Error(401, __("Sorry, you do not have the right to delete this page.")));
416                 }
417
418                 // Attempt to delete the page.
419                 $result = wp_delete_post($page_id);
420                 if(!$result) {
421                         return(new IXR_Error(500, __("Failed to delete the page.")));
422                 }
423
424                 return(true);
425         }
426
427         /**
428          * WordPress XML-RPC API
429          * wp_editPage
430          */
431         function wp_editPage($args) {
432                 // Items not escaped here will be escaped in editPost.
433                 $blog_id        = (int) $args[0];
434                 $page_id        = (int) $this->escape($args[1]);
435                 $username       = $this->escape($args[2]);
436                 $password       = $this->escape($args[3]);
437                 $content        = $args[4];
438                 $publish        = $args[5];
439
440                 if(!$this->login_pass_ok($username, $password)) {
441                         return($this->error);
442                 }
443
444                 do_action('xmlrpc_call', 'wp.editPage');
445
446                 // Get the page data and make sure it is a page.
447                 $actual_page = wp_get_single_post($page_id, ARRAY_A);
448                 if(
449                         !$actual_page
450                         || ($actual_page["post_type"] != "page")
451                 ) {
452                         return(new IXR_Error(404, __("Sorry, no such page.")));
453                 }
454
455                 // Set the user context and make sure they are allowed to edit pages.
456                 set_current_user(0, $username);
457                 if(!current_user_can("edit_page", $page_id)) {
458                         return(new IXR_Error(401, __("Sorry, you do not have the right to edit this page.")));
459                 }
460
461                 // Mark this as content for a page.
462                 $content["post_type"] = "page";
463
464                 // Arrange args in the way mw_editPost understands.
465                 $args = array(
466                         $page_id,
467                         $username,
468                         $password,
469                         $content,
470                         $publish
471                 );
472
473                 // Let mw_editPost do all of the heavy lifting.
474                 return($this->mw_editPost($args));
475         }
476
477         /**
478          * WordPress XML-RPC API
479          * wp_getPageList
480          */
481         function wp_getPageList($args) {
482                 global $wpdb;
483
484                 $this->escape($args);
485
486                 $blog_id                                = (int) $args[0];
487                 $username                               = $args[1];
488                 $password                               = $args[2];
489
490                 if(!$this->login_pass_ok($username, $password)) {
491                         return($this->error);
492                 }
493
494                 set_current_user( 0, $username );
495                 if( !current_user_can( 'edit_pages' ) )
496                         return new IXR_Error( 401, __( 'Sorry, you can not edit pages.' ) );
497
498                 do_action('xmlrpc_call', 'wp.getPageList');
499
500                 // Get list of pages ids and titles
501                 $page_list = $wpdb->get_results("
502                         SELECT ID page_id,
503                                 post_title page_title,
504                                 post_parent page_parent_id,
505                                 post_date_gmt,
506                                 post_date
507                         FROM {$wpdb->posts}
508                         WHERE post_type = 'page'
509                         ORDER BY ID
510                 ");
511
512                 // The date needs to be formated properly.
513                 $num_pages = count($page_list);
514                 for($i = 0; $i < $num_pages; $i++) {
515                         $post_date = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date);
516                         $post_date_gmt = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date_gmt);
517
518                         $page_list[$i]->dateCreated = new IXR_Date($post_date);
519                         $page_list[$i]->date_created_gmt = new IXR_Date($post_date_gmt);
520
521                         unset($page_list[$i]->post_date_gmt);
522                         unset($page_list[$i]->post_date);
523                 }
524
525                 return($page_list);
526         }
527
528         /**
529          * WordPress XML-RPC API
530          * wp_getAuthors
531          */
532         function wp_getAuthors($args) {
533
534                 $this->escape($args);
535
536                 $blog_id        = (int) $args[0];
537                 $username       = $args[1];
538                 $password       = $args[2];
539
540                 if(!$this->login_pass_ok($username, $password)) {
541                         return($this->error);
542                 }
543
544                 set_current_user(0, $username);
545                 if(!current_user_can("edit_posts")) {
546                         return(new IXR_Error(401, __("Sorry, you can not edit posts on this blog.")));
547         }
548
549                 do_action('xmlrpc_call', 'wp.getAuthors');
550
551                 $authors = array();
552                 foreach( (array) get_users_of_blog() as $row ) {
553                         $authors[] = array(
554                                 "user_id"       => $row->user_id,
555                                 "user_login"    => $row->user_login,
556                                 "display_name"  => $row->display_name
557                         );
558                 }
559
560                 return($authors);
561         }
562
563         /**
564          * WordPress XML-RPC API
565          * wp_newCategory
566          */
567         function wp_newCategory($args) {
568                 $this->escape($args);
569
570                 $blog_id                                = (int) $args[0];
571                 $username                               = $args[1];
572                 $password                               = $args[2];
573                 $category                               = $args[3];
574
575                 if(!$this->login_pass_ok($username, $password)) {
576                         return($this->error);
577                 }
578
579                 do_action('xmlrpc_call', 'wp.newCategory');
580
581                 // Set the user context and make sure they are
582                 // allowed to add a category.
583                 set_current_user(0, $username);
584                 if(!current_user_can("manage_categories")) {
585                         return(new IXR_Error(401, __("Sorry, you do not have the right to add a category.")));
586                 }
587
588                 // If no slug was provided make it empty so that
589                 // WordPress will generate one.
590                 if(empty($category["slug"])) {
591                         $category["slug"] = "";
592                 }
593
594                 // If no parent_id was provided make it empty
595                 // so that it will be a top level page (no parent).
596                 if ( !isset($category["parent_id"]) )
597                         $category["parent_id"] = "";
598
599                 // If no description was provided make it empty.
600                 if(empty($category["description"])) {
601                         $category["description"] = "";
602                 }
603
604                 $new_category = array(
605                         "cat_name"                              => $category["name"],
606                         "category_nicename"             => $category["slug"],
607                         "category_parent"               => $category["parent_id"],
608                         "category_description"  => $category["description"]
609                 );
610
611                 $cat_id = wp_insert_category($new_category);
612                 if(!$cat_id) {
613                         return(new IXR_Error(500, __("Sorry, the new category failed.")));
614                 }
615
616                 return($cat_id);
617         }
618
619         /**
620          * WordPress XML-RPC API
621          * wp_deleteCategory
622          */
623         function wp_deleteCategory($args) {
624                 $this->escape($args);
625
626                 $blog_id                = (int) $args[0];
627                 $username               = $args[1];
628                 $password               = $args[2];
629                 $category_id    = (int) $args[3];
630
631                 if( !$this->login_pass_ok( $username, $password ) ) {
632                         return $this->error;
633                 }
634
635                 do_action('xmlrpc_call', 'wp.deleteCategory');
636
637                 set_current_user(0, $username);
638                 if( !current_user_can("manage_categories") ) {
639                         return new IXR_Error( 401, __( "Sorry, you do not have the right to delete a category." ) );
640                 }
641
642                 return wp_delete_category( $category_id );
643         }
644
645
646         /**
647          * WordPress XML-RPC API
648          * wp_suggestCategories
649          */
650         function wp_suggestCategories($args) {
651                 $this->escape($args);
652
653                 $blog_id                                = (int) $args[0];
654                 $username                               = $args[1];
655                 $password                               = $args[2];
656                 $category                               = $args[3];
657                 $max_results                    = (int) $args[4];
658
659                 if(!$this->login_pass_ok($username, $password)) {
660                         return($this->error);
661                 }
662
663                 set_current_user(0, $username);
664                 if( !current_user_can( 'edit_posts' ) )
665                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts to this blog in order to view categories.' ) );
666
667                 do_action('xmlrpc_call', 'wp.suggestCategories');
668
669                 $category_suggestions = array();
670                 $args = array('get' => 'all', 'number' => $max_results, 'name__like' => $category);
671                 foreach ( (array) get_categories($args) as $cat ) {
672                         $category_suggestions[] = array(
673                                 "category_id"   => $cat->cat_ID,
674                                 "category_name" => $cat->cat_name
675                         );
676                 }
677
678                 return($category_suggestions);
679         }
680
681         function wp_getCommentCount( $args ) {
682                 $this->escape($args);
683
684                 $blog_id        = (int) $args[0];
685                 $username       = $args[1];
686                 $password       = $args[2];
687                 $post_id        = (int) $args[3];
688
689                 if( !$this->login_pass_ok( $username, $password ) ) {
690                         return new IXR_Error( 403, __( 'Bad login/pass combination.' ) );
691                 }
692
693                 set_current_user( 0, $username );
694                 if( !current_user_can( 'edit_posts' ) ) {
695                         return new IXR_Error( 403, __( 'You are not allowed access to details about comments.' ) );
696                 }
697
698                 do_action('xmlrpc_call', 'wp.getCommentCount');
699
700                 return get_comment_count( $post_id );
701         }
702
703
704         function wp_getPostStatusList( $args ) {
705                 $this->escape( $args );
706
707                 $blog_id        = (int) $args[0];
708                 $username       = $args[1];
709                 $password       = $args[2];
710
711                 if( !$this->login_pass_ok( $username, $password ) ) {
712                         return new IXR_Error( 403, __( 'Bad login/pass combination.' ) );
713                 }
714
715                 set_current_user( 0, $username );
716                 if( !current_user_can( 'edit_posts' ) ) {
717                         return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
718                 }
719
720                 do_action('xmlrpc_call', 'wp.getPostStatusList');
721
722                 return get_post_statuses( );
723         }
724
725
726         function wp_getPageStatusList( $args ) {
727                 $this->escape( $args );
728
729                 $blog_id        = (int) $args[0];
730                 $username       = $args[1];
731                 $password       = $args[2];
732
733                 if( !$this->login_pass_ok( $username, $password ) ) {
734                         return new IXR_Error( 403, __( 'Bad login/pass combination.' ) );
735                 }
736
737                 set_current_user( 0, $username );
738                 if( !current_user_can( 'edit_posts' ) ) {
739                         return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) );
740                 }
741
742                 do_action('xmlrpc_call', 'wp.getPageStatusList');
743
744                 return get_page_statuses( );
745         }
746
747
748         /* Blogger API functions
749          * specs on http://plant.blogger.com/api and http://groups.yahoo.com/group/bloggerDev/
750          */
751
752
753         /* blogger.getUsersBlogs will make more sense once we support multiple blogs */
754         function blogger_getUsersBlogs($args) {
755
756                 $this->escape($args);
757
758                 $user_login = $args[1];
759                 $user_pass  = $args[2];
760
761                 if (!$this->login_pass_ok($user_login, $user_pass)) {
762                         return $this->error;
763                 }
764
765                 do_action('xmlrpc_call', 'blogger.getUsersBlogs');
766
767                 set_current_user(0, $user_login);
768                 $is_admin = current_user_can('level_8');
769
770                 $struct = array(
771                         'isAdmin'  => $is_admin,
772                         'url'      => get_option('home') . '/',
773                         'blogid'   => '1',
774                         'blogName' => get_option('blogname')
775                 );
776
777                 return array($struct);
778         }
779
780
781         /* blogger.getUsersInfo gives your client some info about you, so you don't have to */
782         function blogger_getUserInfo($args) {
783
784                 $this->escape($args);
785
786                 $user_login = $args[1];
787                 $user_pass  = $args[2];
788
789                 if (!$this->login_pass_ok($user_login, $user_pass)) {
790                         return $this->error;
791                 }
792
793                 set_current_user( 0, $user_login );
794                 if( !current_user_can( 'edit_posts' ) )
795                         return new IXR_Error( 401, __( 'Sorry, you do not have access to user data on this blog.' ) );
796
797                 do_action('xmlrpc_call', 'blogger.getUserInfo');
798
799                 $user_data = get_userdatabylogin($user_login);
800
801                 $struct = array(
802                         'nickname'  => $user_data->nickname,
803                         'userid'    => $user_data->ID,
804                         'url'       => $user_data->user_url,
805                         'lastname'  => $user_data->last_name,
806                         'firstname' => $user_data->first_name
807                 );
808
809                 return $struct;
810         }
811
812
813         /* blogger.getPost ...gets a post */
814         function blogger_getPost($args) {
815
816                 $this->escape($args);
817
818                 $post_ID    = (int) $args[1];
819                 $user_login = $args[2];
820                 $user_pass  = $args[3];
821
822                 if (!$this->login_pass_ok($user_login, $user_pass)) {
823                         return $this->error;
824                 }
825
826                 set_current_user( 0, $user_login );
827                 if( !current_user_can( 'edit_post', $post_ID ) )
828                         return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
829
830                 do_action('xmlrpc_call', 'blogger.getPost');
831
832                 $post_data = wp_get_single_post($post_ID, ARRAY_A);
833
834                 $categories = implode(',', wp_get_post_categories($post_ID));
835
836                 $content  = '<title>'.stripslashes($post_data['post_title']).'</title>';
837                 $content .= '<category>'.$categories.'</category>';
838                 $content .= stripslashes($post_data['post_content']);
839
840                 $struct = array(
841                         'userid'    => $post_data['post_author'],
842                         'dateCreated' => new IXR_Date(mysql2date('Ymd\TH:i:s', $post_data['post_date'])),
843                         'content'     => $content,
844                         'postid'  => $post_data['ID']
845                 );
846
847                 return $struct;
848         }
849
850
851         /* blogger.getRecentPosts ...gets recent posts */
852         function blogger_getRecentPosts($args) {
853
854                 $this->escape($args);
855
856                 $blog_ID    = (int) $args[1]; /* though we don't use it yet */
857                 $user_login = $args[2];
858                 $user_pass  = $args[3];
859                 $num_posts  = $args[4];
860
861                 if (!$this->login_pass_ok($user_login, $user_pass)) {
862                         return $this->error;
863                 }
864
865                 do_action('xmlrpc_call', 'blogger.getRecentPosts');
866
867                 $posts_list = wp_get_recent_posts($num_posts);
868
869                 set_current_user( 0, $user_login );
870
871                 if (!$posts_list) {
872                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
873                         return $this->error;
874                 }
875
876                 foreach ($posts_list as $entry) {
877                         if( !current_user_can( 'edit_post', $entry['ID'] ) )
878                                 continue;
879
880                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
881                         $categories = implode(',', wp_get_post_categories($entry['ID']));
882
883                         $content  = '<title>'.stripslashes($entry['post_title']).'</title>';
884                         $content .= '<category>'.$categories.'</category>';
885                         $content .= stripslashes($entry['post_content']);
886
887                         $struct[] = array(
888                                 'userid' => $entry['post_author'],
889                                 'dateCreated' => new IXR_Date($post_date),
890                                 'content' => $content,
891                                 'postid' => $entry['ID'],
892                         );
893
894                 }
895
896                 $recent_posts = array();
897                 for ($j=0; $j<count($struct); $j++) {
898                         array_push($recent_posts, $struct[$j]);
899                 }
900
901                 return $recent_posts;
902         }
903
904
905         /* blogger.getTemplate returns your blog_filename */
906         function blogger_getTemplate($args) {
907
908                 $this->escape($args);
909
910           $blog_ID    = (int) $args[1];
911           $user_login = $args[2];
912           $user_pass  = $args[3];
913           $template   = $args[4]; /* could be 'main' or 'archiveIndex', but we don't use it */
914
915           if (!$this->login_pass_ok($user_login, $user_pass)) {
916             return $this->error;
917           }
918
919           do_action('xmlrpc_call', 'blogger.getTemplate');
920
921           set_current_user(0, $user_login);
922           if ( !current_user_can('edit_themes') ) {
923             return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
924           }
925
926           /* warning: here we make the assumption that the blog's URL is on the same server */
927           $filename = get_option('home') . '/';
928           $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
929
930           $f = fopen($filename, 'r');
931           $content = fread($f, filesize($filename));
932           fclose($f);
933
934           /* so it is actually editable with a windows/mac client */
935           // 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);
936
937           return $content;
938         }
939
940
941         /* blogger.setTemplate updates the content of blog_filename */
942         function blogger_setTemplate($args) {
943
944                 $this->escape($args);
945
946                 $blog_ID    = (int) $args[1];
947                 $user_login = $args[2];
948                 $user_pass  = $args[3];
949                 $content    = $args[4];
950                 $template   = $args[5]; /* could be 'main' or 'archiveIndex', but we don't use it */
951
952                 if (!$this->login_pass_ok($user_login, $user_pass)) {
953                         return $this->error;
954                 }
955
956                 do_action('xmlrpc_call', 'blogger.setTemplate');
957
958                 set_current_user(0, $user_login);
959                 if ( !current_user_can('edit_themes') ) {
960                         return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
961                 }
962
963                 /* warning: here we make the assumption that the blog's URL is on the same server */
964                 $filename = get_option('home') . '/';
965                 $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
966
967                 if ($f = fopen($filename, 'w+')) {
968                         fwrite($f, $content);
969                         fclose($f);
970                 } else {
971                         return new IXR_Error(500, __('Either the file is not writable, or something wrong happened. The file has not been updated.'));
972                 }
973
974                 return true;
975         }
976
977
978         /* blogger.newPost ...creates a new post */
979         function blogger_newPost($args) {
980
981                 $this->escape($args);
982
983                 $blog_ID    = (int) $args[1]; /* though we don't use it yet */
984                 $user_login = $args[2];
985                 $user_pass  = $args[3];
986                 $content    = $args[4];
987                 $publish    = $args[5];
988
989                 if (!$this->login_pass_ok($user_login, $user_pass)) {
990                         return $this->error;
991                 }
992
993                 do_action('xmlrpc_call', 'blogger.newPost');
994
995                 $cap = ($publish) ? 'publish_posts' : 'edit_posts';
996                 $user = set_current_user(0, $user_login);
997                 if ( !current_user_can($cap) )
998                         return new IXR_Error(401, __('Sorry, you are not allowed to post on this blog.'));
999
1000                 $post_status = ($publish) ? 'publish' : 'draft';
1001
1002                 $post_author = $user->ID;
1003
1004                 $post_title = xmlrpc_getposttitle($content);
1005                 $post_category = xmlrpc_getpostcategory($content);
1006                 $post_content = xmlrpc_removepostdata($content);
1007
1008                 $post_date = current_time('mysql');
1009                 $post_date_gmt = current_time('mysql', 1);
1010
1011                 $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status');
1012
1013                 $post_ID = wp_insert_post($post_data);
1014                 if ( is_wp_error( $post_ID ) )
1015                         return new IXR_Error(500, $post_ID->get_error_message());
1016
1017                 if (!$post_ID)
1018                         return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
1019
1020                 $this->attach_uploads( $post_ID, $post_content );
1021
1022                 logIO('O', "Posted ! ID: $post_ID");
1023
1024                 return $post_ID;
1025         }
1026
1027         /* blogger.editPost ...edits a post */
1028         function blogger_editPost($args) {
1029
1030                 $this->escape($args);
1031
1032                 $post_ID     = (int) $args[1];
1033                 $user_login  = $args[2];
1034                 $user_pass   = $args[3];
1035                 $content     = $args[4];
1036                 $publish     = $args[5];
1037
1038                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1039                         return $this->error;
1040                 }
1041
1042                 do_action('xmlrpc_call', 'blogger.editPost');
1043
1044                 $actual_post = wp_get_single_post($post_ID,ARRAY_A);
1045
1046                 if (!$actual_post) {
1047                         return new IXR_Error(404, __('Sorry, no such post.'));
1048                 }
1049
1050                 $this->escape($actual_post);
1051
1052                 set_current_user(0, $user_login);
1053                 if ( !current_user_can('edit_post', $post_ID) )
1054                         return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.'));
1055
1056                 extract($actual_post, EXTR_SKIP);
1057
1058                 if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
1059                         return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
1060
1061                 $post_title = xmlrpc_getposttitle($content);
1062                 $post_category = xmlrpc_getpostcategory($content);
1063                 $post_content = xmlrpc_removepostdata($content);
1064
1065                 $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
1066
1067                 $result = wp_update_post($postdata);
1068
1069                 if (!$result) {
1070                         return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be edited.'));
1071                 }
1072                 $this->attach_uploads( $ID, $post_content );
1073
1074                 return true;
1075         }
1076
1077
1078         /* blogger.deletePost ...deletes a post */
1079         function blogger_deletePost($args) {
1080                 $this->escape($args);
1081
1082                 $post_ID     = (int) $args[1];
1083                 $user_login  = $args[2];
1084                 $user_pass   = $args[3];
1085                 $publish     = $args[4];
1086
1087                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1088                         return $this->error;
1089                 }
1090
1091                 do_action('xmlrpc_call', 'blogger.deletePost');
1092
1093                 $actual_post = wp_get_single_post($post_ID,ARRAY_A);
1094
1095                 if (!$actual_post) {
1096                         return new IXR_Error(404, __('Sorry, no such post.'));
1097                 }
1098
1099                 set_current_user(0, $user_login);
1100                 if ( !current_user_can('edit_post', $post_ID) )
1101                         return new IXR_Error(401, __('Sorry, you do not have the right to delete this post.'));
1102
1103                 $result = wp_delete_post($post_ID);
1104
1105                 if (!$result) {
1106                         return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be deleted.'));
1107                 }
1108
1109                 return true;
1110         }
1111
1112
1113
1114         /* MetaWeblog API functions
1115          * specs on wherever Dave Winer wants them to be
1116          */
1117
1118         /* metaweblog.newPost creates a post */
1119         function mw_newPost($args) {
1120                 $this->escape($args);
1121
1122                 $blog_ID     = (int) $args[0]; // we will support this in the near future
1123                 $user_login  = $args[1];
1124                 $user_pass   = $args[2];
1125                 $content_struct = $args[3];
1126                 $publish     = $args[4];
1127
1128                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1129                         return $this->error;
1130                 }
1131                 $user = set_current_user(0, $user_login);
1132
1133                 do_action('xmlrpc_call', 'metaWeblog.newPost');
1134
1135                 $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
1136                 $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' );
1137                 $post_type = 'post';
1138                 if( !empty( $content_struct['post_type'] ) ) {
1139                         if( $content_struct['post_type'] == 'page' ) {
1140                                 $cap = ( $publish ) ? 'publish_pages' : 'edit_pages';
1141                                 $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' );
1142                                 $post_type = 'page';
1143                         }
1144                         elseif( $content_struct['post_type'] == 'post' ) {
1145                                 // This is the default, no changes needed
1146                         }
1147                         else {
1148                                 // No other post_type values are allowed here
1149                                 return new IXR_Error( 401, __( 'Invalid post type.' ) );
1150                         }
1151                 }
1152
1153                 if( !current_user_can( $cap ) ) {
1154                         return new IXR_Error( 401, $error_message );
1155                 }
1156
1157                 // Let WordPress generate the post_name (slug) unless
1158                 // one has been provided.
1159                 $post_name = "";
1160                 if(isset($content_struct["wp_slug"])) {
1161                         $post_name = $content_struct["wp_slug"];
1162                 }
1163
1164                 // Only use a password if one was given.
1165                 if(isset($content_struct["wp_password"])) {
1166                         $post_password = $content_struct["wp_password"];
1167                 }
1168
1169                 // Only set a post parent if one was provided.
1170                 if(isset($content_struct["wp_page_parent_id"])) {
1171                         $post_parent = $content_struct["wp_page_parent_id"];
1172                 }
1173
1174                 // Only set the menu_order if it was provided.
1175                 if(isset($content_struct["wp_page_order"])) {
1176                         $menu_order = $content_struct["wp_page_order"];
1177                 }
1178
1179                 $post_author = $user->ID;
1180
1181                 // If an author id was provided then use it instead.
1182                 if(
1183                         isset($content_struct["wp_author_id"])
1184                         && ($user->ID != $content_struct["wp_author_id"])
1185                 ) {
1186                         switch($post_type) {
1187                                 case "post":
1188                                         if(!current_user_can("edit_others_posts")) {
1189                                                 return(new IXR_Error(401, __("You are not allowed to post as this user")));
1190                                         }
1191                                         break;
1192                                 case "page":
1193                                         if(!current_user_can("edit_others_pages")) {
1194                                                 return(new IXR_Error(401, __("You are not allowed to create pages as this user")));
1195                                         }
1196                                         break;
1197                                 default:
1198                                         return(new IXR_Error(401, __("Invalid post type.")));
1199                                         break;
1200                         }
1201                         $post_author = $content_struct["wp_author_id"];
1202                 }
1203
1204                 $post_title = $content_struct['title'];
1205                 $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
1206
1207                 $post_status = $publish ? 'publish' : 'draft';
1208
1209                 if( isset( $content_struct["{$post_type}_status"] ) ) {
1210                         switch( $content_struct["{$post_type}_status"] ) {
1211                                 case 'draft':
1212                                 case 'private':
1213                                 case 'publish':
1214                                         $post_status = $content_struct["{$post_type}_status"];
1215                                         break;
1216                                 case 'pending':
1217                                         // Pending is only valid for posts, not pages.
1218                                         if( $post_type === 'post' ) {
1219                                                 $post_status = $content_struct["{$post_type}_status"];
1220                                         }
1221                                         break;
1222                                 default:
1223                                         $post_status = $publish ? 'publish' : 'draft';
1224                                         break;
1225                         }
1226                 }
1227
1228                 $post_excerpt = $content_struct['mt_excerpt'];
1229                 $post_more = $content_struct['mt_text_more'];
1230
1231                 $tags_input = $content_struct['mt_keywords'];
1232
1233                 if(isset($content_struct["mt_allow_comments"])) {
1234                         if(!is_numeric($content_struct["mt_allow_comments"])) {
1235                                 switch($content_struct["mt_allow_comments"]) {
1236                                         case "closed":
1237                                                 $comment_status = "closed";
1238                                                 break;
1239                                         case "open":
1240                                                 $comment_status = "open";
1241                                                 break;
1242                                         default:
1243                                                 $comment_status = get_option("default_comment_status");
1244                                                 break;
1245                                 }
1246                         }
1247                         else {
1248                                 switch((int) $content_struct["mt_allow_comments"]) {
1249                                         case 0:
1250                                         case 2:
1251                                                 $comment_status = "closed";
1252                                                 break;
1253                                         case 1:
1254                                                 $comment_status = "open";
1255                                                 break;
1256                                         default:
1257                                                 $comment_status = get_option("default_comment_status");
1258                                                 break;
1259                                 }
1260                         }
1261                 }
1262                 else {
1263                         $comment_status = get_option("default_comment_status");
1264                 }
1265
1266                 if(isset($content_struct["mt_allow_pings"])) {
1267                         if(!is_numeric($content_struct["mt_allow_pings"])) {
1268                                 switch($content_struct['mt_allow_pings']) {
1269                                         case "closed":
1270                                                 $ping_status = "closed";
1271                                                 break;
1272                                         case "open":
1273                                                 $ping_status = "open";
1274                                                 break;
1275                                         default:
1276                                                 $ping_status = get_option("default_ping_status");
1277                                                 break;
1278                                 }
1279                         }
1280                         else {
1281                                 switch((int) $content_struct["mt_allow_pings"]) {
1282                                         case 0:
1283                                                 $ping_status = "closed";
1284                                                 break;
1285                                         case 1:
1286                                                 $ping_status = "open";
1287                                                 break;
1288                                         default:
1289                                                 $ping_status = get_option("default_ping_status");
1290                                                 break;
1291                                 }
1292                         }
1293                 }
1294                 else {
1295                         $ping_status = get_option("default_ping_status");
1296                 }
1297
1298                 if ($post_more) {
1299                         $post_content = $post_content . "\n<!--more-->\n" . $post_more;
1300                 }
1301
1302                 $to_ping = $content_struct['mt_tb_ping_urls'];
1303                 if ( is_array($to_ping) )
1304                         $to_ping = implode(' ', $to_ping);
1305
1306                 // Do some timestamp voodoo
1307                 if ( !empty( $content_struct['date_created_gmt'] ) )
1308                         $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
1309                 elseif ( !empty( $content_struct['dateCreated']) )
1310                         $dateCreated = $content_struct['dateCreated']->getIso();
1311
1312                 if ( !empty( $dateCreated ) ) {
1313                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1314                         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
1315                 } else {
1316                         $post_date = current_time('mysql');
1317                         $post_date_gmt = current_time('mysql', 1);
1318                 }
1319
1320                 $catnames = $content_struct['categories'];
1321                 logIO('O', 'Post cats: ' . var_export($catnames,true));
1322                 $post_category = array();
1323
1324                 if (is_array($catnames)) {
1325                         foreach ($catnames as $cat) {
1326                                 $post_category[] = get_cat_ID($cat);
1327                         }
1328                 }
1329
1330                 // We've got all the data -- post it:
1331                 $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');
1332
1333                 $post_ID = wp_insert_post($postdata);
1334                 if ( is_wp_error( $post_ID ) )
1335                         return new IXR_Error(500, $post_ID->get_error_message());
1336
1337                 if (!$post_ID) {
1338                         return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
1339                 }
1340
1341                 if ( isset($content_struct['custom_fields']) ) {
1342                         $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
1343                 }
1344
1345                 $this->attach_uploads( $post_ID, $post_content );
1346
1347                 logIO('O', "Posted ! ID: $post_ID");
1348
1349                 return strval($post_ID);
1350         }
1351
1352         function attach_uploads( $post_ID, $post_content ) {
1353                 global $wpdb;
1354
1355                 // find any unattached files
1356                 $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '-1' AND post_type = 'attachment'" );
1357                 if( is_array( $attachments ) ) {
1358                         foreach( $attachments as $file ) {
1359                                 if( strpos( $post_content, $file->guid ) !== false ) {
1360                                         $wpdb->query( "UPDATE {$wpdb->posts} SET post_parent = '$post_ID' WHERE ID = '{$file->ID}'" );
1361                                 }
1362                         }
1363                 }
1364         }
1365
1366         /* metaweblog.editPost ...edits a post */
1367         function mw_editPost($args) {
1368
1369                 $this->escape($args);
1370
1371                 $post_ID     = (int) $args[0];
1372                 $user_login  = $args[1];
1373                 $user_pass   = $args[2];
1374                 $content_struct = $args[3];
1375                 $publish     = $args[4];
1376
1377                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1378                         return $this->error;
1379                 }
1380                 $user = set_current_user(0, $user_login);
1381
1382                 do_action('xmlrpc_call', 'metaWeblog.editPost');
1383
1384                 $cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
1385                 $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' );
1386                 $post_type = 'post';
1387                 if( !empty( $content_struct['post_type'] ) ) {
1388                         if( $content_struct['post_type'] == 'page' ) {
1389                                 $cap = ( $publish ) ? 'publish_pages' : 'edit_pages';
1390                                 $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' );
1391                                 $post_type = 'page';
1392                         }
1393                         elseif( $content_struct['post_type'] == 'post' ) {
1394                                 // This is the default, no changes needed
1395                         }
1396                         else {
1397                                 // No other post_type values are allowed here
1398                                 return new IXR_Error( 401, __( 'Invalid post type.' ) );
1399                         }
1400                 }
1401
1402                 if( !current_user_can( $cap ) ) {
1403                         return new IXR_Error( 401, $error_message );
1404                 }
1405
1406                 $postdata = wp_get_single_post($post_ID, ARRAY_A);
1407
1408                 // If there is no post data for the give post id, stop
1409                 // now and return an error.  Other wise a new post will be
1410                 // created (which was the old behavior).
1411                 if(empty($postdata["ID"])) {
1412                         return(new IXR_Error(404, __("Invalid post id.")));
1413                 }
1414
1415                 $this->escape($postdata);
1416                 extract($postdata, EXTR_SKIP);
1417
1418                 // Let WordPress manage slug if none was provided.
1419                 $post_name = "";
1420                 if(isset($content_struct["wp_slug"])) {
1421                         $post_name = $content_struct["wp_slug"];
1422                 }
1423
1424                 // Only use a password if one was given.
1425                 if(isset($content_struct["wp_password"])) {
1426                         $post_password = $content_struct["wp_password"];
1427                 }
1428
1429                 // Only set a post parent if one was given.
1430                 if(isset($content_struct["wp_page_parent_id"])) {
1431                         $post_parent = $content_struct["wp_page_parent_id"];
1432                 }
1433
1434                 // Only set the menu_order if it was given.
1435                 if(isset($content_struct["wp_page_order"])) {
1436                         $menu_order = $content_struct["wp_page_order"];
1437                 }
1438
1439                 $post_author = $postdata["post_author"];
1440
1441                 // Only set the post_author if one is set.
1442                 if(
1443                         isset($content_struct["wp_author_id"])
1444                         && ($user->ID != $content_struct["wp_author_id"])
1445                 ) {
1446                         switch($post_type) {
1447                                 case "post":
1448                                         if(!current_user_can("edit_others_posts")) {
1449                                                 return(new IXR_Error(401, __("You are not allowed to change the post author as this user.")));
1450                                         }
1451                                         break;
1452                                 case "page":
1453                                         if(!current_user_can("edit_others_pages")) {
1454                                                 return(new IXR_Error(401, __("You are not allowed to change the page author as this user.")));
1455                                         }
1456                                         break;
1457                                 default:
1458                                         return(new IXR_Error(401, __("Invalid post type.")));
1459                                         break;
1460                         }
1461                         $post_author = $content_struct["wp_author_id"];
1462                 }
1463
1464                 if(isset($content_struct["mt_allow_comments"])) {
1465                         if(!is_numeric($content_struct["mt_allow_comments"])) {
1466                                 switch($content_struct["mt_allow_comments"]) {
1467                                         case "closed":
1468                                                 $comment_status = "closed";
1469                                                 break;
1470                                         case "open":
1471                                                 $comment_status = "open";
1472                                                 break;
1473                                         default:
1474                                                 $comment_status = get_option("default_comment_status");
1475                                                 break;
1476                                 }
1477                         }
1478                         else {
1479                                 switch((int) $content_struct["mt_allow_comments"]) {
1480                                         case 0:
1481                                         case 2:
1482                                                 $comment_status = "closed";
1483                                                 break;
1484                                         case 1:
1485                                                 $comment_status = "open";
1486                                                 break;
1487                                         default:
1488                                                 $comment_status = get_option("default_comment_status");
1489                                                 break;
1490                                 }
1491                         }
1492                 }
1493
1494                 if(isset($content_struct["mt_allow_pings"])) {
1495                         if(!is_numeric($content_struct["mt_allow_pings"])) {
1496                                 switch($content_struct["mt_allow_pings"]) {
1497                                         case "closed":
1498                                                 $ping_status = "closed";
1499                                                 break;
1500                                         case "open":
1501                                                 $ping_status = "open";
1502                                                 break;
1503                                         default:
1504                                                 $ping_status = get_option("default_ping_status");
1505                                                 break;
1506                                 }
1507                         }
1508                         else {
1509                                 switch((int) $content_struct["mt_allow_pings"]) {
1510                                         case 0:
1511                                                 $ping_status = "closed";
1512                                                 break;
1513                                         case 1:
1514                                                 $ping_status = "open";
1515                                                 break;
1516                                         default:
1517                                                 $ping_status = get_option("default_ping_status");
1518                                                 break;
1519                                 }
1520                         }
1521                 }
1522
1523                 $post_title = $content_struct['title'];
1524                 $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
1525                 $catnames = $content_struct['categories'];
1526
1527                 $post_category = array();
1528
1529                 if (is_array($catnames)) {
1530                         foreach ($catnames as $cat) {
1531                                 $post_category[] = get_cat_ID($cat);
1532                         }
1533                 }
1534
1535                 $post_excerpt = $content_struct['mt_excerpt'];
1536                 $post_more = $content_struct['mt_text_more'];
1537
1538                 $post_status = $publish ? 'publish' : 'draft';
1539                 if( isset( $content_struct["{$post_type}_status"] ) ) {
1540                         switch( $content_struct["{$post_type}_status"] ) {
1541                                 case 'draft':
1542                                 case 'private':
1543                                 case 'publish':
1544                                         $post_status = $content_struct["{$post_type}_status"];
1545                                         break;
1546                                 case 'pending':
1547                                         // Pending is only valid for posts, not pages.
1548                                         if( $post_type === 'post' ) {
1549                                                 $post_status = $content_struct["{$post_type}_status"];
1550                                         }
1551                                         break;
1552                                 default:
1553                                         $post_status = $publish ? 'publish' : 'draft';
1554                                         break;
1555                         }
1556                 }
1557
1558                 $tags_input = $content_struct['mt_keywords'];
1559
1560                 if ( ('publish' == $post_status) ) {
1561                         if ( ( 'page' == $post_type ) && !current_user_can('publish_pages') )
1562                                 return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.'));
1563                         else if ( !current_user_can('publish_posts') )
1564                                 return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
1565                 }
1566
1567                 if ($post_more) {
1568                         $post_content = $post_content . "\n<!--more-->\n" . $post_more;
1569                 }
1570
1571                 $to_ping = $content_struct['mt_tb_ping_urls'];
1572                 if ( is_array($to_ping) )
1573                         $to_ping = implode(' ', $to_ping);
1574
1575                 // Do some timestamp voodoo
1576                 if ( !empty( $content_struct['date_created_gmt'] ) )
1577                         $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
1578                 elseif ( !empty( $content_struct['dateCreated']) )
1579                         $dateCreated = $content_struct['dateCreated']->getIso();
1580
1581                 if ( !empty( $dateCreated ) ) {
1582                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1583                         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
1584                 } else {
1585                         $post_date     = $postdata['post_date'];
1586                         $post_date_gmt = $postdata['post_date_gmt'];
1587                 }
1588
1589                 // We've got all the data -- post it:
1590                 $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');
1591
1592                 $result = wp_update_post($newpost);
1593                 if (!$result) {
1594                         return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.'));
1595                 }
1596
1597                 if ( isset($content_struct['custom_fields']) ) {
1598                         $this->set_custom_fields($post_ID, $content_struct['custom_fields']);
1599                 }
1600
1601                 $this->attach_uploads( $ID, $post_content );
1602
1603                 logIO('O',"(MW) Edited ! ID: $post_ID");
1604
1605                 return true;
1606         }
1607
1608
1609         /* metaweblog.getPost ...returns a post */
1610         function mw_getPost($args) {
1611
1612                 $this->escape($args);
1613
1614                 $post_ID     = (int) $args[0];
1615                 $user_login  = $args[1];
1616                 $user_pass   = $args[2];
1617
1618                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1619                         return $this->error;
1620                 }
1621
1622                 set_current_user( 0, $user_login );
1623                 if( !current_user_can( 'edit_post', $post_ID ) )
1624                         return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
1625
1626                 do_action('xmlrpc_call', 'metaWeblog.getPost');
1627
1628                 $postdata = wp_get_single_post($post_ID, ARRAY_A);
1629
1630                 if ($postdata['post_date'] != '') {
1631                         $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date']);
1632                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $postdata['post_date_gmt']);
1633
1634                         $categories = array();
1635                         $catids = wp_get_post_categories($post_ID);
1636                         foreach($catids as $catid)
1637                                 $categories[] = get_cat_name($catid);
1638
1639                         $tagnames = array();
1640                         $tags = wp_get_post_tags( $post_ID );
1641                         if ( !empty( $tags ) ) {
1642                                 foreach ( $tags as $tag )
1643                                         $tagnames[] = $tag->name;
1644                                 $tagnames = implode( ', ', $tagnames );
1645                         } else {
1646                                 $tagnames = '';
1647                         }
1648
1649                         $post = get_extended($postdata['post_content']);
1650                         $link = post_permalink($postdata['ID']);
1651
1652                         // Get the author info.
1653                         $author = get_userdata($postdata['post_author']);
1654
1655                         $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
1656                         $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0;
1657
1658                         // Consider future posts as published
1659                         if( $postdata['post_status'] === 'future' ) {
1660                                 $postdata['post_status'] = 'publish';
1661                         }
1662
1663                         $resp = array(
1664                                 'dateCreated' => new IXR_Date($post_date),
1665                                 'userid' => $postdata['post_author'],
1666                                 'postid' => $postdata['ID'],
1667                                 'description' => $post['main'],
1668                                 'title' => $postdata['post_title'],
1669                                 'link' => $link,
1670                                 'permaLink' => $link,
1671                                 // commented out because no other tool seems to use this
1672                                 //            'content' => $entry['post_content'],
1673                                 'categories' => $categories,
1674                                 'mt_excerpt' => $postdata['post_excerpt'],
1675                                 'mt_text_more' => $post['extended'],
1676                                 'mt_allow_comments' => $allow_comments,
1677                                 'mt_allow_pings' => $allow_pings,
1678                                 'mt_keywords' => $tagnames,
1679                                 'wp_slug' => $postdata['post_name'],
1680                                 'wp_password' => $postdata['post_password'],
1681                                 'wp_author_id' => $author->ID,
1682                                 'wp_author_display_name'        => $author->display_name,
1683                                 'date_created_gmt' => new IXR_Date($post_date_gmt),
1684                                 'post_status' => $postdata['post_status'],
1685                                 'custom_fields' => $this->get_custom_fields($post_ID)
1686                         );
1687
1688                         return $resp;
1689                 } else {
1690                         return new IXR_Error(404, __('Sorry, no such post.'));
1691                 }
1692         }
1693
1694
1695         /* metaweblog.getRecentPosts ...returns recent posts */
1696         function mw_getRecentPosts($args) {
1697
1698                 $this->escape($args);
1699
1700                 $blog_ID     = (int) $args[0];
1701                 $user_login  = $args[1];
1702                 $user_pass   = $args[2];
1703                 $num_posts   = (int) $args[3];
1704
1705                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1706                         return $this->error;
1707                 }
1708
1709                 do_action('xmlrpc_call', 'metaWeblog.getRecentPosts');
1710
1711                 $posts_list = wp_get_recent_posts($num_posts);
1712
1713                 if (!$posts_list) {
1714                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
1715                         return $this->error;
1716                 }
1717
1718                 set_current_user( 0, $user_login );
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']);
1725                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
1726
1727                         $categories = array();
1728                         $catids = wp_get_post_categories($entry['ID']);
1729                         foreach($catids as $catid) {
1730                                 $categories[] = get_cat_name($catid);
1731                         }
1732
1733                         $tagnames = array();
1734                         $tags = wp_get_post_tags( $entry['ID'] );
1735                         if ( !empty( $tags ) ) {
1736                                 foreach ( $tags as $tag ) {
1737                                         $tagnames[] = $tag->name;
1738                                 }
1739                                 $tagnames = implode( ', ', $tagnames );
1740                         } else {
1741                                 $tagnames = '';
1742                         }
1743
1744                         $post = get_extended($entry['post_content']);
1745                         $link = post_permalink($entry['ID']);
1746
1747                         // Get the post author info.
1748                         $author = get_userdata($entry['post_author']);
1749
1750                         $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
1751                         $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0;
1752
1753                         // Consider future posts as published
1754                         if( $entry['post_status'] === 'future' ) {
1755                                 $entry['post_status'] = 'publish';
1756                         }
1757
1758                         $struct[] = array(
1759                                 'dateCreated' => new IXR_Date($post_date),
1760                                 'userid' => $entry['post_author'],
1761                                 'postid' => $entry['ID'],
1762                                 'description' => $post['main'],
1763                                 'title' => $entry['post_title'],
1764                                 'link' => $link,
1765                                 'permaLink' => $link,
1766 // commented out because no other tool seems to use this
1767 //            'content' => $entry['post_content'],
1768                                 'categories' => $categories,
1769                                 'mt_excerpt' => $entry['post_excerpt'],
1770                                 'mt_text_more' => $post['extended'],
1771                                 'mt_allow_comments' => $allow_comments,
1772                                 'mt_allow_pings' => $allow_pings,
1773                                 'mt_keywords' => $tagnames,
1774                                 'wp_slug' => $entry['post_name'],
1775                                 'wp_password' => $entry['post_password'],
1776                                 'wp_author_id' => $author->ID,
1777                                 'wp_author_display_name' => $author->display_name,
1778                                 'date_created_gmt' => new IXR_Date($post_date_gmt),
1779                                 'post_status' => $entry['post_status'],
1780                                 'custom_fields' => $this->get_custom_fields($entry['ID'])
1781                         );
1782
1783                 }
1784
1785                 $recent_posts = array();
1786                 for ($j=0; $j<count($struct); $j++) {
1787                         array_push($recent_posts, $struct[$j]);
1788                 }
1789
1790                 return $recent_posts;
1791         }
1792
1793
1794         /* metaweblog.getCategories ...returns the list of categories on a given blog */
1795         function mw_getCategories($args) {
1796
1797                 $this->escape($args);
1798
1799                 $blog_ID     = (int) $args[0];
1800                 $user_login  = $args[1];
1801                 $user_pass   = $args[2];
1802
1803                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1804                         return $this->error;
1805                 }
1806
1807                 set_current_user( 0, $user_login );
1808                 if( !current_user_can( 'edit_posts' ) )
1809                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
1810
1811                 do_action('xmlrpc_call', 'metaWeblog.getCategories');
1812
1813                 $categories_struct = array();
1814
1815                 if ( $cats = get_categories('get=all') ) {
1816                         foreach ( $cats as $cat ) {
1817                                 $struct['categoryId'] = $cat->term_id;
1818                                 $struct['parentId'] = $cat->parent;
1819                                 $struct['description'] = $cat->name;
1820                                 $struct['categoryName'] = $cat->name;
1821                                 $struct['htmlUrl'] = wp_specialchars(get_category_link($cat->term_id));
1822                                 $struct['rssUrl'] = wp_specialchars(get_category_rss_link(false, $cat->term_id, $cat->name));
1823
1824                                 $categories_struct[] = $struct;
1825                         }
1826                 }
1827
1828                 return $categories_struct;
1829         }
1830
1831
1832         /* metaweblog.newMediaObject uploads a file, following your settings */
1833         function mw_newMediaObject($args) {
1834                 // adapted from a patch by Johann Richard
1835                 // http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
1836
1837                 global $wpdb;
1838
1839                 $blog_ID     = (int) $args[0];
1840                 $user_login  = $wpdb->escape($args[1]);
1841                 $user_pass   = $wpdb->escape($args[2]);
1842                 $data        = $args[3];
1843
1844                 $name = sanitize_file_name( $data['name'] );
1845                 $type = $data['type'];
1846                 $bits = $data['bits'];
1847
1848                 logIO('O', '(MW) Received '.strlen($bits).' bytes');
1849
1850                 if ( !$this->login_pass_ok($user_login, $user_pass) )
1851                         return $this->error;
1852
1853                 do_action('xmlrpc_call', 'metaWeblog.newMediaObject');
1854
1855                 set_current_user(0, $user_login);
1856                 if ( !current_user_can('upload_files') ) {
1857                         logIO('O', '(MW) User does not have upload_files capability');
1858                         $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
1859                         return $this->error;
1860                 }
1861
1862                 if ( $upload_err = apply_filters( "pre_upload_error", false ) )
1863                         return new IXR_Error(500, $upload_err);
1864
1865                 if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
1866                         // Get postmeta info on the object.
1867                         $old_file = $wpdb->get_row("
1868                                 SELECT ID
1869                                 FROM {$wpdb->posts}
1870                                 WHERE post_title = '{$name}'
1871                                         AND post_type = 'attachment'
1872                         ");
1873
1874                         // Delete previous file.
1875                         wp_delete_attachment($old_file->ID);
1876
1877                         // Make sure the new name is different by pre-pending the
1878                         // previous post id.
1879                         $filename = preg_replace("/^wpid\d+-/", "", $name);
1880                         $name = "wpid{$old_file->ID}-{$filename}";
1881                 }
1882
1883                 $upload = wp_upload_bits($name, $type, $bits);
1884                 if ( ! empty($upload['error']) ) {
1885                         $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']);
1886                         logIO('O', '(MW) ' . $errorString);
1887                         return new IXR_Error(500, $errorString);
1888                 }
1889                 // Construct the attachment array
1890                 // attach to post_id -1
1891                 $post_id = -1;
1892                 $attachment = array(
1893                         'post_title' => $name,
1894                         'post_content' => '',
1895                         'post_type' => 'attachment',
1896                         'post_parent' => $post_id,
1897                         'post_mime_type' => $type,
1898                         'guid' => $upload[ 'url' ]
1899                 );
1900
1901                 // Save the data
1902                 $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
1903                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
1904
1905                 return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
1906         }
1907
1908
1909         /* MovableType API functions
1910          * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
1911          */
1912
1913         /* mt.getRecentPostTitles ...returns recent posts' titles */
1914         function mt_getRecentPostTitles($args) {
1915
1916                 $this->escape($args);
1917
1918                 $blog_ID     = (int) $args[0];
1919                 $user_login  = $args[1];
1920                 $user_pass   = $args[2];
1921                 $num_posts   = (int) $args[3];
1922
1923                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1924                         return $this->error;
1925                 }
1926
1927                 do_action('xmlrpc_call', 'mt.getRecentPostTitles');
1928
1929                 $posts_list = wp_get_recent_posts($num_posts);
1930
1931                 if (!$posts_list) {
1932                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
1933                         return $this->error;
1934                 }
1935
1936                 set_current_user( 0, $user_login );
1937
1938                 foreach ($posts_list as $entry) {
1939                         if( !current_user_can( 'edit_post', $entry['ID'] ) )
1940                                 continue;
1941
1942                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
1943                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
1944
1945                         $struct[] = array(
1946                                 'dateCreated' => new IXR_Date($post_date),
1947                                 'userid' => $entry['post_author'],
1948                                 'postid' => $entry['ID'],
1949                                 'title' => $entry['post_title'],
1950                                 'date_created_gmt' => new IXR_Date($post_date_gmt)
1951                         );
1952
1953                 }
1954
1955                 $recent_posts = array();
1956                 for ($j=0; $j<count($struct); $j++) {
1957                         array_push($recent_posts, $struct[$j]);
1958                 }
1959
1960                 return $recent_posts;
1961         }
1962
1963
1964         /* mt.getCategoryList ...returns the list of categories on a given blog */
1965         function mt_getCategoryList($args) {
1966
1967                 $this->escape($args);
1968
1969                 $blog_ID     = (int) $args[0];
1970                 $user_login  = $args[1];
1971                 $user_pass   = $args[2];
1972
1973                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1974                         return $this->error;
1975                 }
1976
1977                 set_current_user( 0, $user_login );
1978                 if( !current_user_can( 'edit_posts' ) )
1979                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
1980
1981                 do_action('xmlrpc_call', 'mt.getCategoryList');
1982
1983                 $categories_struct = array();
1984
1985                 if ( $cats = get_categories('hide_empty=0&hierarchical=0') ) {
1986                         foreach ($cats as $cat) {
1987                                 $struct['categoryId'] = $cat->term_id;
1988                                 $struct['categoryName'] = $cat->name;
1989
1990                                 $categories_struct[] = $struct;
1991                         }
1992                 }
1993
1994                 return $categories_struct;
1995         }
1996
1997
1998         /* mt.getPostCategories ...returns a post's categories */
1999         function mt_getPostCategories($args) {
2000
2001                 $this->escape($args);
2002
2003                 $post_ID     = (int) $args[0];
2004                 $user_login  = $args[1];
2005                 $user_pass   = $args[2];
2006
2007                 if (!$this->login_pass_ok($user_login, $user_pass)) {
2008                         return $this->error;
2009                 }
2010
2011                 set_current_user( 0, $user_login );
2012                 if( !current_user_can( 'edit_post', $post_ID ) )
2013                         return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
2014
2015                 do_action('xmlrpc_call', 'mt.getPostCategories');
2016
2017                 $categories = array();
2018                 $catids = wp_get_post_categories(intval($post_ID));
2019                 // first listed category will be the primary category
2020                 $isPrimary = true;
2021                 foreach($catids as $catid) {
2022                         $categories[] = array(
2023                                 'categoryName' => get_cat_name($catid),
2024                                 'categoryId' => (string) $catid,
2025                                 'isPrimary' => $isPrimary
2026                         );
2027                         $isPrimary = false;
2028                 }
2029
2030                 return $categories;
2031         }
2032
2033
2034         /* mt.setPostCategories ...sets a post's categories */
2035         function mt_setPostCategories($args) {
2036
2037                 $this->escape($args);
2038
2039                 $post_ID     = (int) $args[0];
2040                 $user_login  = $args[1];
2041                 $user_pass   = $args[2];
2042                 $categories  = $args[3];
2043
2044                 if (!$this->login_pass_ok($user_login, $user_pass)) {
2045                         return $this->error;
2046                 }
2047
2048                 do_action('xmlrpc_call', 'mt.setPostCategories');
2049
2050                 set_current_user(0, $user_login);
2051                 if ( !current_user_can('edit_post', $post_ID) )
2052                         return new IXR_Error(401, __('Sorry, you can not edit this post.'));
2053
2054                 foreach($categories as $cat) {
2055                         $catids[] = $cat['categoryId'];
2056                 }
2057
2058                 wp_set_post_categories($post_ID, $catids);
2059
2060                 return true;
2061         }
2062
2063
2064         /* mt.supportedMethods ...returns an array of methods supported by this server */
2065         function mt_supportedMethods($args) {
2066
2067                 do_action('xmlrpc_call', 'mt.supportedMethods');
2068
2069                 $supported_methods = array();
2070                 foreach($this->methods as $key=>$value) {
2071                         $supported_methods[] = $key;
2072                 }
2073
2074                 return $supported_methods;
2075         }
2076
2077
2078         /* mt.supportedTextFilters ...returns an empty array because we don't
2079                  support per-post text filters yet */
2080         function mt_supportedTextFilters($args) {
2081                 do_action('xmlrpc_call', 'mt.supportedTextFilters');
2082                 return apply_filters('xmlrpc_text_filters', array());
2083         }
2084
2085
2086         /* mt.getTrackbackPings ...returns trackbacks sent to a given post */
2087         function mt_getTrackbackPings($args) {
2088
2089                 global $wpdb;
2090
2091                 $post_ID = intval($args);
2092
2093                 do_action('xmlrpc_call', 'mt.getTrackbackPings');
2094
2095                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
2096
2097                 if (!$actual_post) {
2098                         return new IXR_Error(404, __('Sorry, no such post.'));
2099                 }
2100
2101                 $comments = $wpdb->get_results("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = $post_ID");
2102
2103                 if (!$comments) {
2104                         return array();
2105                 }
2106
2107                 $trackback_pings = array();
2108                 foreach($comments as $comment) {
2109                         if ( 'trackback' == $comment->comment_type ) {
2110                                 $content = $comment->comment_content;
2111                                 $title = substr($content, 8, (strpos($content, '</strong>') - 8));
2112                                 $trackback_pings[] = array(
2113                                         'pingTitle' => $title,
2114                                         'pingURL'   => $comment->comment_author_url,
2115                                         'pingIP'    => $comment->comment_author_IP
2116                                 );
2117                 }
2118                 }
2119
2120                 return $trackback_pings;
2121         }
2122
2123
2124         /* mt.publishPost ...sets a post's publish status to 'publish' */
2125         function mt_publishPost($args) {
2126
2127                 $this->escape($args);
2128
2129                 $post_ID     = (int) $args[0];
2130                 $user_login  = $args[1];
2131                 $user_pass   = $args[2];
2132
2133                 if (!$this->login_pass_ok($user_login, $user_pass)) {
2134                         return $this->error;
2135                 }
2136
2137                 do_action('xmlrpc_call', 'mt.publishPost');
2138
2139                 set_current_user(0, $user_login);
2140                 if ( !current_user_can('edit_post', $post_ID) )
2141                         return new IXR_Error(401, __('Sorry, you can not edit this post.'));
2142
2143                 $postdata = wp_get_single_post($post_ID,ARRAY_A);
2144
2145                 $postdata['post_status'] = 'publish';
2146
2147                 // retain old cats
2148                 $cats = wp_get_post_categories($post_ID);
2149                 $postdata['post_category'] = $cats;
2150                 $this->escape($postdata);
2151
2152                 $result = wp_update_post($postdata);
2153
2154                 return $result;
2155         }
2156
2157
2158
2159         /* PingBack functions
2160          * specs on www.hixie.ch/specs/pingback/pingback
2161          */
2162
2163         /* pingback.ping gets a pingback and registers it */
2164         function pingback_ping($args) {
2165                 global $wpdb;
2166
2167                 do_action('xmlrpc_call', 'pingback.ping');
2168
2169                 $this->escape($args);
2170
2171                 $pagelinkedfrom = $args[0];
2172                 $pagelinkedto   = $args[1];
2173
2174                 $title = '';
2175
2176                 $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
2177                 $pagelinkedto = str_replace('&amp;', '&', $pagelinkedto);
2178                 $pagelinkedto = str_replace('&', '&amp;', $pagelinkedto);
2179
2180                 // Check if the page linked to is in our site
2181                 $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
2182                 if( !$pos1 )
2183                         return new IXR_Error(0, __('Is there no link to us?'));
2184
2185                 // let's find which post is linked to
2186                 // FIXME: does url_to_postid() cover all these cases already?
2187                 //        if so, then let's use it and drop the old code.
2188                 $urltest = parse_url($pagelinkedto);
2189                 if ($post_ID = url_to_postid($pagelinkedto)) {
2190                         $way = 'url_to_postid()';
2191                 } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
2192                         // the path defines the post_ID (archives/p/XXXX)
2193                         $blah = explode('/', $match[0]);
2194                         $post_ID = (int) $blah[1];
2195                         $way = 'from the path';
2196                 } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
2197                         // the querystring defines the post_ID (?p=XXXX)
2198                         $blah = explode('=', $match[0]);
2199                         $post_ID = (int) $blah[1];
2200                         $way = 'from the querystring';
2201                 } elseif (isset($urltest['fragment'])) {
2202                         // an #anchor is there, it's either...
2203                         if (intval($urltest['fragment'])) {
2204                                 // ...an integer #XXXX (simpliest case)
2205                                 $post_ID = (int) $urltest['fragment'];
2206                                 $way = 'from the fragment (numeric)';
2207                         } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) {
2208                                 // ...a post id in the form 'post-###'
2209                                 $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
2210                                 $way = 'from the fragment (post-###)';
2211                         } elseif (is_string($urltest['fragment'])) {
2212                                 // ...or a string #title, a little more complicated
2213                                 $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
2214                                 $sql = "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE '$title'";
2215                                 if (! ($post_ID = $wpdb->get_var($sql)) ) {
2216                                         // returning unknown error '0' is better than die()ing
2217                                         return new IXR_Error(0, '');
2218                                 }
2219                                 $way = 'from the fragment (title)';
2220                         }
2221                 } else {
2222                         // TODO: Attempt to extract a post ID from the given URL
2223                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
2224                 }
2225                 $post_ID = (int) $post_ID;
2226
2227
2228                 logIO("O","(PB) URL='$pagelinkedto' ID='$post_ID' Found='$way'");
2229
2230                 $post = get_post($post_ID);
2231
2232                 if ( !$post ) // Post_ID not found
2233                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
2234
2235                 if ( $post_ID == url_to_postid($pagelinkedfrom) )
2236                         return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.'));
2237
2238                 // Check if pings are on
2239                 if ( 'closed' == $post->ping_status )
2240                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
2241
2242                 // Let's check that the remote site didn't already pingback this entry
2243                 $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post_ID' AND comment_author_url = '$pagelinkedfrom'");
2244
2245                 if ( $wpdb->num_rows ) // We already have a Pingback from this URL
2246                         return new IXR_Error(48, __('The pingback has already been registered.'));
2247
2248                 // very stupid, but gives time to the 'from' server to publish !
2249                 sleep(1);
2250
2251                 // Let's check the remote site
2252                 $linea = wp_remote_fopen( $pagelinkedfrom );
2253                 if ( !$linea )
2254                         return new IXR_Error(16, __('The source URL does not exist.'));
2255
2256                 $linea = apply_filters('pre_remote_source', $linea, $pagelinkedto);
2257
2258                 // Work around bug in strip_tags():
2259                 $linea = str_replace('<!DOC', '<DOC', $linea);
2260                 $linea = preg_replace( '/[\s\r\n\t]+/', ' ', $linea ); // normalize spaces
2261                 $linea = preg_replace( "/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea );
2262
2263                 preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
2264                 $title = $matchtitle[1];
2265                 if ( empty( $title ) )
2266                         return new IXR_Error(32, __('We cannot find a title on that page.'));
2267
2268                 $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
2269
2270                 $p = explode( "\n\n", $linea );
2271
2272                 $preg_target = preg_quote($pagelinkedto);
2273
2274                 foreach ( $p as $para ) {
2275                         if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link?
2276                                 preg_match("|<a[^>]+?".$preg_target."[^>]*>([^>]+?)</a>|", $para, $context);
2277
2278                                 // If the URL isn't in a link context, keep looking
2279                                 if ( empty($context) )
2280                                         continue;
2281
2282                                 // We're going to use this fake tag to mark the context in a bit
2283                                 // the marker is needed in case the link text appears more than once in the paragraph
2284                                 $excerpt = preg_replace('|\</?wpcontext\>|', '', $para);
2285
2286                                 // prevent really long link text
2287                                 if ( strlen($context[1]) > 100 )
2288                                         $context[1] = substr($context[1], 0, 100) . '...';
2289
2290                                 $marker = '<wpcontext>'.$context[1].'</wpcontext>';    // set up our marker
2291                                 $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
2292                                 $excerpt = strip_tags($excerpt, '<wpcontext>');        // strip all tags but our context marker
2293                                 $excerpt = trim($excerpt);
2294                                 $preg_marker = preg_quote($marker);
2295                                 $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
2296                                 $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
2297                                 break;
2298                         }
2299                 }
2300
2301                 if ( empty($context) ) // Link to target not found
2302                         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.'));
2303
2304                 $pagelinkedfrom = str_replace('&', '&amp;', $pagelinkedfrom);
2305
2306                 $context = '[...] ' . wp_specialchars( $excerpt ) . ' [...]';
2307                 $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom );
2308
2309                 $comment_post_ID = (int) $post_ID;
2310                 $comment_author = $title;
2311                 $this->escape($comment_author);
2312                 $comment_author_url = $pagelinkedfrom;
2313                 $comment_content = $context;
2314                 $this->escape($comment_content);
2315                 $comment_type = 'pingback';
2316
2317                 $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type');
2318
2319                 $comment_ID = wp_new_comment($commentdata);
2320                 do_action('pingback_post', $comment_ID);
2321
2322                 return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto);
2323         }
2324
2325
2326         /* pingback.extensions.getPingbacks returns an array of URLs
2327         that pingbacked the given URL
2328         specs on http://www.aquarionics.com/misc/archives/blogite/0198.html */
2329         function pingback_extensions_getPingbacks($args) {
2330
2331                 global $wpdb;
2332
2333                 do_action('xmlrpc_call', 'pingback.extensions.getPingsbacks');
2334
2335                 $this->escape($args);
2336
2337                 $url = $args;
2338
2339                 $post_ID = url_to_postid($url);
2340                 if (!$post_ID) {
2341                         // We aren't sure that the resource is available and/or pingback enabled
2342                         return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.'));
2343                 }
2344
2345                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
2346
2347                 if (!$actual_post) {
2348                         // No such post = resource not found
2349                         return new IXR_Error(32, __('The specified target URL does not exist.'));
2350                 }
2351
2352                 $comments = $wpdb->get_results("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = $post_ID");
2353
2354                 if (!$comments) {
2355                         return array();
2356                 }
2357
2358                 $pingbacks = array();
2359                 foreach($comments as $comment) {
2360                         if ( 'pingback' == $comment->comment_type )
2361                                 $pingbacks[] = $comment->comment_author_url;
2362                 }
2363
2364                 return $pingbacks;
2365         }
2366 }
2367
2368
2369 $wp_xmlrpc_server = new wp_xmlrpc_server();
2370
2371 ?>