]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - xmlrpc.php
Wordpress 2.3.2
[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
979       $cap = ($publish) ? 'publish_posts' : 'edit_posts';
980           $user = set_current_user(0, $user_login);
981           if ( !current_user_can($cap) )
982             return new IXR_Error(401, __('Sorry, you are not allowed to post on this blog.'));
983
984                 // The post_type defaults to post, but could also be page.
985                 $post_type = "post";
986                 if(
987                         !empty($content_struct["post_type"])
988                         && ($content_struct["post_type"] == "page")
989                 ) {
990                         $post_type = "page";
991                 }
992
993                 // Let WordPress generate the post_name (slug) unless
994                 // one has been provided.
995                 $post_name = "";
996                 if(isset($content_struct["wp_slug"])) {
997                         $post_name = $content_struct["wp_slug"];
998                 }
999
1000                 // Only use a password if one was given.
1001                 if(isset($content_struct["wp_password"])) {
1002                         $post_password = $content_struct["wp_password"];
1003                 }
1004
1005                 // Only set a post parent if one was provided.
1006                 if(isset($content_struct["wp_page_parent_id"])) {
1007                         $post_parent = $content_struct["wp_page_parent_id"];
1008                 }
1009
1010                 // Only set the menu_order if it was provided.
1011                 if(isset($content_struct["wp_page_order"])) {
1012                         $menu_order = $content_struct["wp_page_order"];
1013                 }
1014
1015           $post_author = $user->ID;
1016
1017                 // If an author id was provided then use it instead.
1018                 if(
1019                         isset($content_struct["wp_author_id"])
1020                         && ($user->ID != $content_struct["wp_author_id"])
1021                 ) {
1022                         switch($post_type) {
1023                                 case "post":
1024                                         if(!current_user_can("edit_others_posts")) {
1025                                                 return(new IXR_Error(401, __("You are not allowed to post as this user")));
1026                                         }
1027                                         break;
1028                                 case "page":
1029                                         if(!current_user_can("edit_others_pages")) {
1030                                                 return(new IXR_Error(401, __("You are not allowed to create pages as this user")));
1031                                         }
1032                                         break;
1033                                 default:
1034                                         return(new IXR_Error(401, __("Invalid post type.")));
1035                                         break;
1036                         }
1037                         $post_author = $content_struct["wp_author_id"];
1038                 }
1039
1040           $post_title = $content_struct['title'];
1041           $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
1042           $post_status = $publish ? 'publish' : 'draft';
1043
1044           $post_excerpt = $content_struct['mt_excerpt'];
1045           $post_more = $content_struct['mt_text_more'];
1046
1047                 $tags_input = $content_struct['mt_keywords'];
1048
1049                 if(isset($content_struct["mt_allow_comments"])) {
1050                         if(!is_numeric($content_struct["mt_allow_comments"])) {
1051                                 switch($content_struct["mt_allow_comments"]) {
1052                                         case "closed":
1053                                                 $comment_status = "closed";
1054                                                 break;
1055                                         case "open":
1056                                                 $comment_status = "open";
1057                                                 break;
1058                                         default:
1059                                                 $comment_status = get_option("default_comment_status");
1060                                                 break;
1061                                 }
1062                         }
1063                         else {
1064                                 switch((int) $content_struct["mt_allow_comments"]) {
1065                                         case 0:
1066                                                 $comment_status = "closed";
1067                                                 break;
1068                                         case 1:
1069                                                 $comment_status = "open";
1070                                                 break;
1071                                         default:
1072                                                 $comment_status = get_option("default_comment_status");
1073                                                 break;
1074                                 }
1075                         }
1076                 }
1077                 else {
1078                         $comment_status = get_option("default_comment_status");
1079                 }
1080
1081                 if(isset($content_struct["mt_allow_pings"])) {
1082                         if(!is_numeric($content_struct["mt_allow_pings"])) {
1083                                 switch($content_struct['mt_allow_pings']) {
1084                                         case "closed":
1085                                                 $ping_status = "closed";
1086                                                 break;
1087                                         case "open":
1088                                                 $ping_status = "open";
1089                                                 break;
1090                                         default:
1091                                                 $ping_status = get_option("default_ping_status");
1092                                                 break;
1093                                 }
1094                         }
1095                         else {
1096                                 switch((int) $content_struct["mt_allow_pings"]) {
1097                                         case 0:
1098                                                 $ping_status = "closed";
1099                                                 break;
1100                                         case 1:
1101                                                 $ping_status = "open";
1102                                                 break;
1103                                         default:
1104                                                 $ping_status = get_option("default_ping_status");
1105                                                 break;
1106                                 }
1107                         }
1108                 }
1109                 else {
1110                         $ping_status = get_option("default_ping_status");
1111                 }
1112
1113           if ($post_more) {
1114             $post_content = $post_content . "\n<!--more-->\n" . $post_more;
1115           }
1116
1117           $to_ping = $content_struct['mt_tb_ping_urls'];
1118           if ( is_array($to_ping) )
1119                 $to_ping = implode(' ', $to_ping);
1120
1121                 // Do some timestamp voodoo
1122                 $dateCreatedd = $content_struct['dateCreated'];
1123                 if (!empty($dateCreatedd)) {
1124                         $dateCreated = $dateCreatedd->getIso();
1125                         $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1126                         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
1127                 } else {
1128                         $post_date = current_time('mysql');
1129                         $post_date_gmt = current_time('mysql', 1);
1130                 }
1131
1132           $catnames = $content_struct['categories'];
1133           logIO('O', 'Post cats: ' . printr($catnames,true));
1134           $post_category = array();
1135
1136           if (is_array($catnames)) {
1137             foreach ($catnames as $cat) {
1138               $post_category[] = get_cat_ID($cat);
1139             }
1140           }
1141
1142           // We've got all the data -- post it:
1143           $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');
1144
1145           $post_ID = wp_insert_post($postdata);
1146           if ( is_wp_error( $post_ID ) )
1147                 return new IXR_Error(500, $post_ID->get_error_message());
1148
1149           if (!$post_ID) {
1150             return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
1151           }
1152
1153           $this->attach_uploads( $post_ID, $post_content );
1154
1155           logIO('O', "Posted ! ID: $post_ID");
1156
1157           return strval($post_ID);
1158         }
1159
1160         function attach_uploads( $post_ID, $post_content ) {
1161                 global $wpdb;
1162
1163                 // find any unattached files
1164                 $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '-1' AND post_type = 'attachment'" );
1165                 if( is_array( $attachments ) ) {
1166                         foreach( $attachments as $file ) {
1167                                 if( strpos( $post_content, $file->guid ) !== false ) {
1168                                         $wpdb->query( "UPDATE {$wpdb->posts} SET post_parent = '$post_ID' WHERE ID = '{$file->ID}'" );
1169                                 }
1170                         }
1171                 }
1172         }
1173
1174         /* metaweblog.editPost ...edits a post */
1175         function mw_editPost($args) {
1176
1177           global $wpdb, $post_default_category;
1178
1179                 $this->escape($args);
1180
1181           $post_ID     = (int) $args[0];
1182           $user_login  = $args[1];
1183           $user_pass   = $args[2];
1184           $content_struct = $args[3];
1185           $publish     = $args[4];
1186
1187           if (!$this->login_pass_ok($user_login, $user_pass)) {
1188             return $this->error;
1189           }
1190
1191                 $user = set_current_user(0, $user_login);
1192
1193                 // The post_type defaults to post, but could also be page.
1194                 $post_type = "post";
1195                 if(
1196                         !empty($content_struct["post_type"])
1197                         && ($content_struct["post_type"] == "page")
1198                 ) {
1199                         $post_type = "page";
1200                 }
1201
1202           // Edit page caps are checked in editPage.  Just check post here.
1203           if ( ( 'post' == $post_type ) && !current_user_can('edit_post', $post_ID) )
1204             return new IXR_Error(401, __('Sorry, you can not edit this post.'));
1205
1206           $postdata = wp_get_single_post($post_ID, ARRAY_A);
1207
1208                 // If there is no post data for the give post id, stop
1209                 // now and return an error.  Other wise a new post will be
1210                 // created (which was the old behavior).
1211                 if(empty($postdata["ID"])) {
1212                         return(new IXR_Error(404, __("Invalid post id.")));
1213                 }
1214
1215                 $this->escape($postdata);
1216                 extract($postdata, EXTR_SKIP);
1217
1218                 // Let WordPress manage slug if none was provided.
1219                 $post_name = "";
1220                 if(isset($content_struct["wp_slug"])) {
1221                         $post_name = $content_struct["wp_slug"];
1222                 }
1223
1224                 // Only use a password if one was given.
1225                 if(isset($content_struct["wp_password"])) {
1226                         $post_password = $content_struct["wp_password"];
1227                 }
1228
1229                 // Only set a post parent if one was given.
1230                 if(isset($content_struct["wp_page_parent_id"])) {
1231                         $post_parent = $content_struct["wp_page_parent_id"];
1232                 }
1233
1234                 // Only set the menu_order if it was given.
1235                 if(isset($content_struct["wp_page_order"])) {
1236                         $menu_order = $content_struct["wp_page_order"];
1237                 }
1238
1239                 $post_author = $postdata["post_author"];
1240
1241                 // Only set the post_author if one is set.
1242                 if(
1243                         isset($content_struct["wp_author_id"])
1244                         && ($user->ID != $content_struct["wp_author_id"])
1245                 ) {
1246                         switch($post_type) {
1247                                 case "post":
1248                                         if(!current_user_can("edit_others_posts")) {
1249                                                 return(new IXR_Error(401, __("You are not allowed to change the post author as this user.")));
1250                                         }
1251                                         break;
1252                                 case "page":
1253                                         if(!current_user_can("edit_others_pages")) {
1254                                                 return(new IXR_Error(401, __("You are not allowed to change the page author as this user.")));
1255                                         }
1256                                         break;
1257                                 default:
1258                                         return(new IXR_Error(401, __("Invalid post type.")));
1259                                         break;
1260                         }
1261                         $post_author = $content_struct["wp_author_id"];
1262                 }
1263
1264                 if(isset($content_struct["mt_allow_comments"])) {
1265                         if(!is_numeric($content_struct["mt_allow_comments"])) {
1266                                 switch($content_struct["mt_allow_comments"]) {
1267                                         case "closed":
1268                                                 $comment_status = "closed";
1269                                                 break;
1270                                         case "open":
1271                                                 $comment_status = "open";
1272                                                 break;
1273                                         default:
1274                                                 $comment_status = get_option("default_comment_status");
1275                                                 break;
1276                                 }
1277                         }
1278                         else {
1279                                 switch((int) $content_struct["mt_allow_comments"]) {
1280                                         case 0:
1281                                                 $comment_status = "closed";
1282                                                 break;
1283                                         case 1:
1284                                                 $comment_status = "open";
1285                                                 break;
1286                                         default:
1287                                                 $comment_status = get_option("default_comment_status");
1288                                                 break;
1289                                 }
1290                         }
1291                 }
1292
1293                 if(isset($content_struct["mt_allow_pings"])) {
1294                         if(!is_numeric($content_struct["mt_allow_pings"])) {
1295                                 switch($content_struct["mt_allow_pings"]) {
1296                                         case "closed":
1297                                                 $ping_status = "closed";
1298                                                 break;
1299                                         case "open":
1300                                                 $ping_status = "open";
1301                                                 break;
1302                                         default:
1303                                                 $ping_status = get_option("default_ping_status");
1304                                                 break;
1305                                 }
1306                         }
1307                         else {
1308                                 switch((int) $content_struct["mt_allow_pings"]) {
1309                                         case 0:
1310                                                 $ping_status = "closed";
1311                                                 break;
1312                                         case 1:
1313                                                 $ping_status = "open";
1314                                                 break;
1315                                         default:
1316                                                 $ping_status = get_option("default_ping_status");
1317                                                 break;
1318                                 }
1319                         }
1320                 }
1321
1322           $post_title = $content_struct['title'];
1323           $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
1324           $catnames = $content_struct['categories'];
1325
1326           $post_category = array();
1327
1328           if (is_array($catnames)) {
1329             foreach ($catnames as $cat) {
1330               $post_category[] = get_cat_ID($cat);
1331             }
1332           }
1333
1334           $post_excerpt = $content_struct['mt_excerpt'];
1335           $post_more = $content_struct['mt_text_more'];
1336           $post_status = $publish ? 'publish' : 'draft';
1337
1338           $tags_input = $content_struct['mt_keywords'];
1339
1340           if ( ('publish' == $post_status) ) {
1341                 if ( ( 'page' == $post_type ) && !current_user_can('publish_pages') )
1342                         return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.'));
1343                 else if ( !current_user_can('publish_posts') )
1344                         return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
1345           }
1346
1347           if ($post_more) {
1348             $post_content = $post_content . "\n<!--more-->\n" . $post_more;
1349           }
1350
1351           $to_ping = $content_struct['mt_tb_ping_urls'];
1352           if ( is_array($to_ping) )
1353                 $to_ping = implode(' ', $to_ping);
1354
1355           // Do some timestamp voodoo
1356           $dateCreatedd = $content_struct['dateCreated'];
1357           if (!empty($dateCreatedd)) {
1358             $dateCreated = $dateCreatedd->getIso();
1359             $post_date     = get_date_from_gmt(iso8601_to_datetime($dateCreated));
1360             $post_date_gmt = iso8601_to_datetime($dateCreated . "Z", GMT);
1361           } else {
1362             $post_date     = $postdata['post_date'];
1363             $post_date_gmt = $postdata['post_date_gmt'];
1364           }
1365
1366           // We've got all the data -- post it:
1367           $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');
1368
1369           $result = wp_update_post($newpost);
1370           if (!$result) {
1371             return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.'));
1372           }
1373           $this->attach_uploads( $ID, $post_content );
1374
1375           logIO('O',"(MW) Edited ! ID: $post_ID");
1376
1377           return true;
1378         }
1379
1380
1381         /* metaweblog.getPost ...returns a post */
1382         function mw_getPost($args) {
1383
1384                 global $wpdb;
1385
1386                 $this->escape($args);
1387
1388                 $post_ID     = (int) $args[0];
1389                 $user_login  = $args[1];
1390                 $user_pass   = $args[2];
1391
1392                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1393                         return $this->error;
1394                 }
1395
1396                 set_current_user( 0, $user_login );
1397                 if( !current_user_can( 'edit_post', $post_ID ) )
1398                         return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
1399
1400                 do_action('xmlrpc_call', 'metaWeblog.getPost');
1401
1402                 $postdata = wp_get_single_post($post_ID, ARRAY_A);
1403
1404                 if ($postdata['post_date'] != '') {
1405                         $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date']);
1406                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $postdata['post_date_gmt']);
1407
1408                         $categories = array();
1409                         $catids = wp_get_post_categories($post_ID);
1410                         foreach($catids as $catid) {
1411                                 $categories[] = get_cat_name($catid);
1412                         }
1413
1414                         $tagnames = array();
1415                         $tags = wp_get_post_tags( $post_ID );
1416                         if ( !empty( $tags ) ) {
1417                                 foreach ( $tags as $tag ) {
1418                                         $tagnames[] = $tag->name;
1419                                 }
1420                                 $tagnames = implode( ', ', $tagnames );
1421                         } else {
1422                                 $tagnames = '';
1423                         }
1424
1425                         $post = get_extended($postdata['post_content']);
1426                         $link = post_permalink($postdata['ID']);
1427
1428                         // Get the author info.
1429                         $author = get_userdata($postdata['post_author']);
1430
1431                         $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
1432                         $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0;
1433
1434                         $resp = array(
1435                         'dateCreated' => new IXR_Date($post_date),
1436                                 'userid' => $postdata['post_author'],
1437                                 'postid' => $postdata['ID'],
1438                                 'description' => $post['main'],
1439                                 'title' => $postdata['post_title'],
1440                                 'link' => $link,
1441                                 'permaLink' => $link,
1442                                 // commented out because no other tool seems to use this
1443                                 //            'content' => $entry['post_content'],
1444                                 'categories' => $categories,
1445                                 'mt_excerpt' => $postdata['post_excerpt'],
1446                                 'mt_text_more' => $post['extended'],
1447                                 'mt_allow_comments' => $allow_comments,
1448                                 'mt_allow_pings' => $allow_pings,
1449                                 'mt_keywords' => $tagnames,
1450                                 'wp_slug' => $postdata['post_name'],
1451                                 'wp_password' => $postdata['post_password'],
1452                                 'wp_author_id' => $author->ID,
1453                                 'wp_author_display_name'        => $author->display_name,
1454                                 'date_created_gmt' => new IXR_Date($post_date_gmt)
1455                         );
1456
1457                         return $resp;
1458                 } else {
1459                         return new IXR_Error(404, __('Sorry, no such post.'));
1460                 }
1461         }
1462
1463
1464         /* metaweblog.getRecentPosts ...returns recent posts */
1465         function mw_getRecentPosts($args) {
1466
1467                 $this->escape($args);
1468
1469                 $blog_ID     = (int) $args[0];
1470                 $user_login  = $args[1];
1471                 $user_pass   = $args[2];
1472                 $num_posts   = (int) $args[3];
1473
1474                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1475                         return $this->error;
1476                 }
1477
1478                 $posts_list = wp_get_recent_posts($num_posts);
1479
1480                 if (!$posts_list) {
1481                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
1482                         return $this->error;
1483                 }
1484
1485                 set_current_user( 0, $user_login );
1486
1487                 foreach ($posts_list as $entry) {
1488                         if( !current_user_can( 'edit_post', $entry['ID'] ) )
1489                                 continue;
1490
1491                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
1492                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
1493
1494                         $categories = array();
1495                         $catids = wp_get_post_categories($entry['ID']);
1496                         foreach($catids as $catid) {
1497                                 $categories[] = get_cat_name($catid);
1498                         }
1499
1500                         $tagnames = array();
1501                         $tags = wp_get_post_tags( $entry['ID'] );
1502                         if ( !empty( $tags ) ) {
1503                                 foreach ( $tags as $tag ) {
1504                                         $tagnames[] = $tag->name;
1505                                 }
1506                                 $tagnames = implode( ', ', $tagnames );
1507                         } else {
1508                                 $tagnames = '';
1509                         }
1510
1511                         $post = get_extended($entry['post_content']);
1512                         $link = post_permalink($entry['ID']);
1513
1514                         // Get the post author info.
1515                         $author = get_userdata($entry['post_author']);
1516
1517                         $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
1518                         $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0;
1519
1520                         $struct[] = array(
1521                                 'dateCreated' => new IXR_Date($post_date),
1522                                 'userid' => $entry['post_author'],
1523                                 'postid' => $entry['ID'],
1524                                 'description' => $post['main'],
1525                                 'title' => $entry['post_title'],
1526                                 'link' => $link,
1527                                 'permaLink' => $link,
1528 // commented out because no other tool seems to use this
1529 //            'content' => $entry['post_content'],
1530                                 'categories' => $categories,
1531                                 'mt_excerpt' => $entry['post_excerpt'],
1532                                 'mt_text_more' => $post['extended'],
1533                                 'mt_allow_comments' => $allow_comments,
1534                                 'mt_allow_pings' => $allow_pings,
1535                                 'mt_keywords' => $tagnames,
1536                                 'wp_slug' => $entry['post_name'],
1537                                 'wp_password' => $entry['post_password'],
1538                                 'wp_author_id' => $author->ID,
1539                                 'wp_author_display_name' => $author->display_name,
1540                                 'date_created_gmt' => new IXR_Date($post_date_gmt)
1541                         );
1542
1543                 }
1544
1545                 $recent_posts = array();
1546                 for ($j=0; $j<count($struct); $j++) {
1547                         array_push($recent_posts, $struct[$j]);
1548                 }
1549
1550                 return $recent_posts;
1551         }
1552
1553
1554         /* metaweblog.getCategories ...returns the list of categories on a given blog */
1555         function mw_getCategories($args) {
1556
1557                 global $wpdb;
1558
1559                 $this->escape($args);
1560
1561                 $blog_ID     = (int) $args[0];
1562                 $user_login  = $args[1];
1563                 $user_pass   = $args[2];
1564
1565                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1566                         return $this->error;
1567                 }
1568
1569                 set_current_user( 0, $user_login );
1570                 if( !current_user_can( 'edit_posts' ) )
1571                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
1572
1573                 do_action('xmlrpc_call', 'metaWeblog.getCategories');
1574
1575                 $categories_struct = array();
1576
1577                 if ( $cats = get_categories('get=all') ) {
1578                         foreach ( $cats as $cat ) {
1579                                 $struct['categoryId'] = $cat->term_id;
1580                                 $struct['parentId'] = $cat->parent;
1581                                 $struct['description'] = $cat->name;
1582                                 $struct['categoryName'] = $cat->name;
1583                                 $struct['htmlUrl'] = wp_specialchars(get_category_link($cat->term_id));
1584                                 $struct['rssUrl'] = wp_specialchars(get_category_rss_link(false, $cat->term_id, $cat->name));
1585
1586                                 $categories_struct[] = $struct;
1587                         }
1588                 }
1589
1590                 return $categories_struct;
1591         }
1592
1593
1594         /* metaweblog.newMediaObject uploads a file, following your settings */
1595         function mw_newMediaObject($args) {
1596                 // adapted from a patch by Johann Richard
1597                 // http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
1598
1599                 global $wpdb;
1600
1601                 $blog_ID     = (int) $args[0];
1602                 $user_login  = $wpdb->escape($args[1]);
1603                 $user_pass   = $wpdb->escape($args[2]);
1604                 $data        = $args[3];
1605
1606                 $name = sanitize_file_name( $data['name'] );
1607                 $type = $data['type'];
1608                 $bits = $data['bits'];
1609
1610                 logIO('O', '(MW) Received '.strlen($bits).' bytes');
1611
1612                 if ( !$this->login_pass_ok($user_login, $user_pass) )
1613                         return $this->error;
1614
1615                 set_current_user(0, $user_login);
1616                 if ( !current_user_can('upload_files') ) {
1617                         logIO('O', '(MW) User does not have upload_files capability');
1618                         $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
1619                         return $this->error;
1620                 }
1621
1622                 if ( $upload_err = apply_filters( "pre_upload_error", false ) )
1623                         return new IXR_Error(500, $upload_err);
1624
1625                 if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
1626                         // Get postmeta info on the object.
1627                         $old_file = $wpdb->get_row("
1628                                 SELECT ID
1629                                 FROM {$wpdb->posts}
1630                                 WHERE post_title = '{$name}'
1631                                         AND post_type = 'attachment'
1632                         ");
1633
1634                         // Delete previous file.
1635                         wp_delete_attachment($old_file->ID);
1636
1637                         // Make sure the new name is different by pre-pending the
1638                         // previous post id.
1639                         $filename = preg_replace("/^wpid\d+-/", "", $name);
1640                         $name = "wpid{$old_file->ID}-{$filename}";
1641                 }
1642
1643                 $upload = wp_upload_bits($name, $type, $bits, $overwrite);
1644                 if ( ! empty($upload['error']) ) {
1645                         $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']);
1646                         logIO('O', '(MW) ' . $errorString);
1647                         return new IXR_Error(500, $errorString);
1648                 }
1649                 // Construct the attachment array
1650                 // attach to post_id -1
1651                 $post_id = -1;
1652                 $attachment = array(
1653                         'post_title' => $name,
1654                         'post_content' => '',
1655                         'post_type' => 'attachment',
1656                         'post_parent' => $post_id,
1657                         'post_mime_type' => $type,
1658                         'guid' => $upload[ 'url' ]
1659                 );
1660
1661                 // Save the data
1662                 $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
1663                 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
1664
1665                 return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
1666         }
1667
1668
1669         /* MovableType API functions
1670          * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
1671          */
1672
1673         /* mt.getRecentPostTitles ...returns recent posts' titles */
1674         function mt_getRecentPostTitles($args) {
1675
1676                 $this->escape($args);
1677
1678                 $blog_ID     = (int) $args[0];
1679                 $user_login  = $args[1];
1680                 $user_pass   = $args[2];
1681                 $num_posts   = (int) $args[3];
1682
1683                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1684                         return $this->error;
1685                 }
1686
1687                 $posts_list = wp_get_recent_posts($num_posts);
1688
1689                 if (!$posts_list) {
1690                         $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
1691                         return $this->error;
1692                 }
1693
1694                 set_current_user( 0, $user_login );
1695
1696                 foreach ($posts_list as $entry) {
1697                         if( !current_user_can( 'edit_post', $entry['ID'] ) ) 
1698                                 continue;
1699
1700                         $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
1701                         $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
1702
1703                         $struct[] = array(
1704                                 'dateCreated' => new IXR_Date($post_date),
1705                                 'userid' => $entry['post_author'],
1706                                 'postid' => $entry['ID'],
1707                                 'title' => $entry['post_title'],
1708                                 'date_created_gmt' => new IXR_Date($post_date_gmt)
1709                         );
1710
1711                 }
1712
1713                 $recent_posts = array();
1714                 for ($j=0; $j<count($struct); $j++) {
1715                         array_push($recent_posts, $struct[$j]);
1716                 }
1717
1718                 return $recent_posts;
1719         }
1720
1721
1722         /* mt.getCategoryList ...returns the list of categories on a given blog */
1723         function mt_getCategoryList($args) {
1724
1725                 global $wpdb;
1726
1727                 $this->escape($args);
1728
1729                 $blog_ID     = (int) $args[0];
1730                 $user_login  = $args[1];
1731                 $user_pass   = $args[2];
1732
1733                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1734                         return $this->error;
1735                 }
1736
1737                 set_current_user( 0, $user_login );
1738                 if( !current_user_can( 'edit_posts' ) )
1739                         return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) );
1740
1741                 do_action('xmlrpc_call', 'mt.getCategoryList');
1742
1743                 $categories_struct = array();
1744
1745                 if ( $cats = get_categories('hide_empty=0&hierarchical=0') ) {
1746                         foreach ($cats as $cat) {
1747                                 $struct['categoryId'] = $cat->term_id;
1748                                 $struct['categoryName'] = $cat->name;
1749
1750                                 $categories_struct[] = $struct;
1751                         }
1752                 }
1753
1754                 return $categories_struct;
1755         }
1756
1757
1758         /* mt.getPostCategories ...returns a post's categories */
1759         function mt_getPostCategories($args) {
1760
1761                 $this->escape($args);
1762
1763                 $post_ID     = (int) $args[0];
1764                 $user_login  = $args[1];
1765                 $user_pass   = $args[2];
1766
1767                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1768                         return $this->error;
1769                 }
1770
1771                 set_current_user( 0, $user_login );
1772                 if( !current_user_can( 'edit_post', $post_ID ) )
1773                         return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) );
1774
1775                 do_action('xmlrpc_call', 'mt.getPostCategories');
1776
1777                 $categories = array();
1778                 $catids = wp_get_post_categories(intval($post_ID));
1779                 // first listed category will be the primary category
1780                 $isPrimary = true;
1781                 foreach($catids as $catid) {
1782                         $categories[] = array(
1783                                 'categoryName' => get_cat_name($catid),
1784                                 'categoryId' => (string) $catid,
1785                                 'isPrimary' => $isPrimary
1786                         );
1787                         $isPrimary = false;
1788                 }
1789
1790                 return $categories;
1791         }
1792
1793
1794         /* mt.setPostCategories ...sets a post's categories */
1795         function mt_setPostCategories($args) {
1796
1797                 $this->escape($args);
1798
1799                 $post_ID     = (int) $args[0];
1800                 $user_login  = $args[1];
1801                 $user_pass   = $args[2];
1802                 $categories  = $args[3];
1803
1804                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1805                         return $this->error;
1806                 }
1807
1808                 set_current_user(0, $user_login);
1809                 if ( !current_user_can('edit_post', $post_ID) )
1810                         return new IXR_Error(401, __('Sorry, you can not edit this post.'));
1811
1812                 foreach($categories as $cat) {
1813                         $catids[] = $cat['categoryId'];
1814                 }
1815
1816                 wp_set_post_categories($post_ID, $catids);
1817
1818                 return true;
1819         }
1820
1821
1822         /* mt.supportedMethods ...returns an array of methods supported by this server */
1823         function mt_supportedMethods($args) {
1824
1825                 $supported_methods = array();
1826                 foreach($this->methods as $key=>$value) {
1827                         $supported_methods[] = $key;
1828                 }
1829
1830                 return $supported_methods;
1831         }
1832
1833
1834         /* mt.supportedTextFilters ...returns an empty array because we don't
1835                  support per-post text filters yet */
1836         function mt_supportedTextFilters($args) {
1837                 return apply_filters('xmlrpc_text_filters', array());
1838         }
1839
1840
1841         /* mt.getTrackbackPings ...returns trackbacks sent to a given post */
1842         function mt_getTrackbackPings($args) {
1843
1844                 global $wpdb;
1845
1846                 $post_ID = intval($args);
1847
1848                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
1849
1850                 if (!$actual_post) {
1851                         return new IXR_Error(404, __('Sorry, no such post.'));
1852                 }
1853
1854                 $comments = $wpdb->get_results("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = $post_ID");
1855
1856                 if (!$comments) {
1857                         return array();
1858                 }
1859
1860                 $trackback_pings = array();
1861                 foreach($comments as $comment) {
1862                         if ( 'trackback' == $comment->comment_type ) {
1863                                 $content = $comment->comment_content;
1864                                 $title = substr($content, 8, (strpos($content, '</strong>') - 8));
1865                                 $trackback_pings[] = array(
1866                                         'pingTitle' => $title,
1867                                         'pingURL'   => $comment->comment_author_url,
1868                                         'pingIP'    => $comment->comment_author_IP
1869                                 );
1870                 }
1871                 }
1872
1873                 return $trackback_pings;
1874         }
1875
1876
1877         /* mt.publishPost ...sets a post's publish status to 'publish' */
1878         function mt_publishPost($args) {
1879
1880                 $this->escape($args);
1881
1882                 $post_ID     = (int) $args[0];
1883                 $user_login  = $args[1];
1884                 $user_pass   = $args[2];
1885
1886                 if (!$this->login_pass_ok($user_login, $user_pass)) {
1887                         return $this->error;
1888                 }
1889
1890                 set_current_user(0, $user_login);
1891                 if ( !current_user_can('edit_post', $post_ID) )
1892                         return new IXR_Error(401, __('Sorry, you can not edit this post.'));
1893
1894                 $postdata = wp_get_single_post($post_ID,ARRAY_A);
1895
1896                 $postdata['post_status'] = 'publish';
1897
1898                 // retain old cats
1899                 $cats = wp_get_post_categories($post_ID);
1900                 $postdata['post_category'] = $cats;
1901                 $this->escape($postdata);
1902
1903                 $result = wp_update_post($postdata);
1904
1905                 return $result;
1906         }
1907
1908
1909
1910         /* PingBack functions
1911          * specs on www.hixie.ch/specs/pingback/pingback
1912          */
1913
1914         /* pingback.ping gets a pingback and registers it */
1915         function pingback_ping($args) {
1916                 global $wpdb, $wp_version;
1917
1918                 $this->escape($args);
1919
1920                 $pagelinkedfrom = $args[0];
1921                 $pagelinkedto   = $args[1];
1922
1923                 $title = '';
1924
1925                 $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
1926                 $pagelinkedto = str_replace('&amp;', '&', $pagelinkedto);
1927                 $pagelinkedto = str_replace('&', '&amp;', $pagelinkedto);
1928
1929                 $error_code = -1;
1930
1931                 // Check if the page linked to is in our site
1932                 $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
1933                 if( !$pos1 )
1934                                 return new IXR_Error(0, __('Is there no link to us?'));
1935
1936                 // let's find which post is linked to
1937                 // FIXME: does url_to_postid() cover all these cases already?
1938                 //        if so, then let's use it and drop the old code.
1939                 $urltest = parse_url($pagelinkedto);
1940                 if ($post_ID = url_to_postid($pagelinkedto)) {
1941                         $way = 'url_to_postid()';
1942                 } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
1943                         // the path defines the post_ID (archives/p/XXXX)
1944                         $blah = explode('/', $match[0]);
1945                         $post_ID = (int) $blah[1];
1946                         $way = 'from the path';
1947                 } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
1948                         // the querystring defines the post_ID (?p=XXXX)
1949                         $blah = explode('=', $match[0]);
1950                         $post_ID = (int) $blah[1];
1951                         $way = 'from the querystring';
1952                 } elseif (isset($urltest['fragment'])) {
1953                         // an #anchor is there, it's either...
1954                         if (intval($urltest['fragment'])) {
1955                                 // ...an integer #XXXX (simpliest case)
1956                                 $post_ID = (int) $urltest['fragment'];
1957                                 $way = 'from the fragment (numeric)';
1958                         } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) {
1959                                 // ...a post id in the form 'post-###'
1960                                 $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
1961                                 $way = 'from the fragment (post-###)';
1962                         } elseif (is_string($urltest['fragment'])) {
1963                                 // ...or a string #title, a little more complicated
1964                                 $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
1965                                 $sql = "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE '$title'";
1966                                 if (! ($post_ID = $wpdb->get_var($sql)) ) {
1967                                         // returning unknown error '0' is better than die()ing
1968                                         return new IXR_Error(0, '');
1969                                 }
1970                                 $way = 'from the fragment (title)';
1971                         }
1972                 } else {
1973                         // TODO: Attempt to extract a post ID from the given URL
1974                         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.'));
1975                 }
1976                 $post_ID = (int) $post_ID;
1977
1978
1979                 logIO("O","(PB) URL='$pagelinkedto' ID='$post_ID' Found='$way'");
1980
1981                 $post = get_post($post_ID);
1982
1983                 if ( !$post ) // Post_ID not found
1984                         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.'));
1985
1986                 if ( $post_ID == url_to_postid($pagelinkedfrom) )
1987                         return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.'));
1988
1989                 // Check if pings are on
1990                 if ( 'closed' == $post->ping_status )
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                 // Let's check that the remote site didn't already pingback this entry
1994                 $result = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post_ID' AND comment_author_url = '$pagelinkedfrom'");
1995
1996                 if ( $wpdb->num_rows ) // We already have a Pingback from this URL
1997                         return new IXR_Error(48, __('The pingback has already been registered.'));
1998
1999                 // very stupid, but gives time to the 'from' server to publish !
2000                 sleep(1);
2001
2002                 // Let's check the remote site
2003                 $linea = wp_remote_fopen( $pagelinkedfrom );
2004                 if ( !$linea )
2005                         return new IXR_Error(16, __('The source URL does not exist.'));
2006
2007                 // Work around bug in strip_tags():
2008                 $linea = str_replace('<!DOC', '<DOC', $linea);
2009                 $linea = preg_replace( '/[\s\r\n\t]+/', ' ', $linea ); // normalize spaces
2010                 $linea = preg_replace( "/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea );
2011
2012                 preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
2013                 $title = $matchtitle[1];
2014                 if ( empty( $title ) )
2015                         return new IXR_Error(32, __('We cannot find a title on that page.'));
2016
2017                 $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
2018
2019                 $p = explode( "\n\n", $linea );
2020
2021                 $preg_target = preg_quote($pagelinkedto);
2022
2023                 foreach ( $p as $para ) {
2024                         if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link?
2025                                 preg_match("|<a[^>]+?".$preg_target."[^>]*>([^>]+?)</a>|", $para, $context);
2026
2027                                 // If the URL isn't in a link context, keep looking
2028                                 if ( empty($context) )
2029                                         continue;
2030
2031                                 // We're going to use this fake tag to mark the context in a bit
2032                                 // the marker is needed in case the link text appears more than once in the paragraph
2033                                 $excerpt = preg_replace('|\</?wpcontext\>|', '', $para);
2034
2035                                 // prevent really long link text
2036                                 if ( strlen($context[1]) > 100 )
2037                                         $context[1] = substr($context[1], 0, 100) . '...';
2038
2039                                 $marker = '<wpcontext>'.$context[1].'</wpcontext>';    // set up our marker
2040                                 $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker
2041                                 $excerpt = strip_tags($excerpt, '<wpcontext>');        // strip all tags but our context marker
2042                                 $excerpt = trim($excerpt);
2043                                 $preg_marker = preg_quote($marker);
2044                                 $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt);
2045                                 $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper
2046                                 break;
2047                         }
2048                 }
2049
2050                 if ( empty($context) ) // Link to target not found
2051                         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.'));
2052
2053                 $pagelinkedfrom = str_replace('&', '&amp;', $pagelinkedfrom);
2054
2055                 $context = '[...] ' . wp_specialchars( $excerpt ) . ' [...]';
2056                 $original_pagelinkedfrom = $pagelinkedfrom;
2057                 $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom );
2058                 $original_title = $title;
2059
2060                 $comment_post_ID = (int) $post_ID;
2061                 $comment_author = $title;
2062                 $this->escape($comment_author);
2063                 $comment_author_url = $pagelinkedfrom;
2064                 $comment_content = $context;
2065                 $this->escape($comment_content);
2066                 $comment_type = 'pingback';
2067
2068                 $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type');
2069
2070                 $comment_ID = wp_new_comment($commentdata);
2071                 do_action('pingback_post', $comment_ID);
2072
2073                 return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto);
2074         }
2075
2076
2077         /* pingback.extensions.getPingbacks returns an array of URLs
2078         that pingbacked the given URL
2079         specs on http://www.aquarionics.com/misc/archives/blogite/0198.html */
2080         function pingback_extensions_getPingbacks($args) {
2081
2082                 global $wpdb;
2083
2084                 $this->escape($args);
2085
2086                 $url = $args;
2087
2088                 $post_ID = url_to_postid($url);
2089                 if (!$post_ID) {
2090                         // We aren't sure that the resource is available and/or pingback enabled
2091                         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.'));
2092                 }
2093
2094                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
2095
2096                 if (!$actual_post) {
2097                         // No such post = resource not found
2098                         return new IXR_Error(32, __('The specified target URL does not exist.'));
2099                 }
2100
2101                 $comments = $wpdb->get_results("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = $post_ID");
2102
2103                 if (!$comments) {
2104                         return array();
2105                 }
2106
2107                 $pingbacks = array();
2108                 foreach($comments as $comment) {
2109                         if ( 'pingback' == $comment->comment_type )
2110                                 $pingbacks[] = $comment->comment_author_url;
2111                 }
2112
2113                 return $pingbacks;
2114         }
2115 }
2116
2117
2118 $wp_xmlrpc_server = new wp_xmlrpc_server();
2119
2120 ?>