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