]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - xmlrpc.php
Wordpress 2.0.11
[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 # fix for mozBlog and other cases where '<?xml' isn't on the very first line
9 if ( isset($HTTP_RAW_POST_DATA) )
10         $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
11
12 include('./wp-config.php');
13
14 if ( isset( $_GET['rsd'] ) ) { // http://archipelago.phrasewise.com/rsd 
15 header('Content-type: text/xml; charset=' . get_settings('blog_charset'), true);
16
17 ?>
18 <?php echo '<?xml version="1.0" encoding="'.get_settings('blog_charset').'"?'.'>'; ?>
19 <rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
20   <service>
21     <engineName>WordPress</engineName>
22     <engineLink>http://wordpress.org/</engineLink>
23     <homePageLink><?php bloginfo_rss('url') ?></homePageLink>
24     <apis>
25       <api name="Movable Type" blogID="1" preferred="true" apiLink="<?php bloginfo_rss('url') ?>/xmlrpc.php" />
26       <api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('url') ?>/xmlrpc.php" />
27       <api name="Blogger" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('url') ?>/xmlrpc.php" />
28     </apis>
29   </service>
30 </rsd>
31 <?php
32 exit;
33 }
34
35 include_once(ABSPATH . WPINC . '/class-IXR.php');
36
37 // Turn off all warnings and errors.
38 // error_reporting(0);
39
40 $post_default_title = ""; // posts submitted via the xmlrpc interface get that title
41
42 $xmlrpc_logging = 0;
43
44 function logIO($io,$msg) {
45         global $xmlrpc_logging;
46         if ($xmlrpc_logging) {
47                 $fp = fopen("../xmlrpc.log","a+");
48                 $date = gmdate("Y-m-d H:i:s ");
49                 $iot = ($io == "I") ? " Input: " : " Output: ";
50                 fwrite($fp, "\n\n".$date.$iot.$msg);
51                 fclose($fp);
52         }
53         return true;
54         }
55
56 function starify($string) {
57         $i = strlen($string);
58         return str_repeat('*', $i);
59 }
60
61 if ( isset($HTTP_RAW_POST_DATA) )
62   logIO("I", $HTTP_RAW_POST_DATA);
63
64
65 class wp_xmlrpc_server extends IXR_Server {
66
67         function wp_xmlrpc_server() {
68                 $this->methods = array(
69                   // Blogger API
70                   'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
71                   'blogger.getUserInfo' => 'this:blogger_getUserInfo',
72                   'blogger.getPost' => 'this:blogger_getPost',
73                   'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
74                   'blogger.getTemplate' => 'this:blogger_getTemplate',
75                   'blogger.setTemplate' => 'this:blogger_setTemplate',
76                   'blogger.newPost' => 'this:blogger_newPost',
77                   'blogger.editPost' => 'this:blogger_editPost',
78                   'blogger.deletePost' => 'this:blogger_deletePost',
79
80                   // MetaWeblog API (with MT extensions to structs)
81                   'metaWeblog.newPost' => 'this:mw_newPost',
82                   'metaWeblog.editPost' => 'this:mw_editPost',
83                   'metaWeblog.getPost' => 'this:mw_getPost',
84                   'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
85                   'metaWeblog.getCategories' => 'this:mw_getCategories',
86                   'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',
87
88                   // MetaWeblog API aliases for Blogger API
89                   // see http://www.xmlrpc.com/stories/storyReader$2460
90                   'metaWeblog.deletePost' => 'this:blogger_deletePost',
91                   'metaWeblog.getTemplate' => 'this:blogger_getTemplate',
92                   'metaWeblog.setTemplate' => 'this:blogger_setTemplate',
93                   'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',
94
95                   // MovableType API
96                   'mt.getCategoryList' => 'this:mt_getCategoryList',
97                   'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
98                   'mt.getPostCategories' => 'this:mt_getPostCategories',
99                   'mt.setPostCategories' => 'this:mt_setPostCategories',
100                   'mt.supportedMethods' => 'this:mt_supportedMethods',
101                   'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
102                   'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
103                   'mt.publishPost' => 'this:mt_publishPost',
104
105                   // PingBack
106                   'pingback.ping' => 'this:pingback_ping',
107                   'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
108
109                   'demo.sayHello' => 'this:sayHello',
110                   'demo.addTwoNumbers' => 'this:addTwoNumbers'
111                 );
112                 $this->methods = apply_filters('xmlrpc_methods', $this->methods);
113                 $this->IXR_Server($this->methods);
114         }
115
116         function sayHello($args) {
117                 return 'Hello!';
118         }
119
120         function addTwoNumbers($args) {
121                 $number1 = $args[0];
122                 $number2 = $args[1];
123                 return $number1 + $number2;
124         }
125
126         function login_pass_ok($user_login, $user_pass) {
127           if (!user_pass_ok($user_login, $user_pass)) {
128             $this->error = new IXR_Error(403, 'Bad login/pass combination.');
129             return false;
130           }
131           return true;
132         }
133
134         function escape(&$array) {
135                 global $wpdb;
136
137                 foreach ( (array) $array as $k => $v ) {
138                         if (is_array($v)) {
139                                 $this->escape($array[$k]);
140                         } else if (is_object($v)) {
141                                 //skip
142                         } else {
143                                 $array[$k] = $wpdb->escape($v);
144                         }
145                 }
146         }
147
148         /* Blogger API functions
149          * specs on http://plant.blogger.com/api and http://groups.yahoo.com/group/bloggerDev/
150          */
151
152
153         /* blogger.getUsersBlogs will make more sense once we support multiple blogs */
154         function blogger_getUsersBlogs($args) {
155
156                 $this->escape($args);
157
158           $user_login = $args[1];
159           $user_pass  = $args[2];
160
161           if (!$this->login_pass_ok($user_login, $user_pass)) {
162             return $this->error;
163           }
164
165           set_current_user(0, $user_login);
166           $is_admin = current_user_can('level_8');
167
168           $struct = array(
169             'isAdmin'  => $is_admin,
170             'url'      => get_settings('home') . '/',
171             'blogid'   => '1',
172             'blogName' => get_settings('blogname')
173           );
174
175           return array($struct);
176         }
177
178
179         /* blogger.getUsersInfo gives your client some info about you, so you don't have to */
180         function blogger_getUserInfo($args) {
181
182                 $this->escape($args);
183
184           $user_login = $args[1];
185           $user_pass  = $args[2];
186
187           if (!$this->login_pass_ok($user_login, $user_pass)) {
188             return $this->error;
189           }
190
191           $user_data = get_userdatabylogin($user_login);
192
193           $struct = array(
194             'nickname'  => $user_data->nickname,
195             'userid'    => $user_data->ID,
196             'url'       => $user_data->user_url,
197             'email'     => $user_data->user_email,
198             'lastname'  => $user_data->last_name,
199             'firstname' => $user_data->first_name
200           );
201
202           return $struct;
203         }
204
205
206         /* blogger.getPost ...gets a post */
207         function blogger_getPost($args) {
208
209                 $this->escape($args);
210
211                 $post_ID    = (int) $args[1];
212                 $user_login = $args[2];
213                 $user_pass  = $args[3];
214
215           if (!$this->login_pass_ok($user_login, $user_pass)) {
216             return $this->error;
217           }
218
219           $user_data = get_userdatabylogin($user_login);
220           $post_data = wp_get_single_post($post_ID, ARRAY_A);
221
222           $categories = implode(',', wp_get_post_cats(1, $post_ID));
223
224           $content  = '<title>'.stripslashes($post_data['post_title']).'</title>';
225           $content .= '<category>'.$categories.'</category>';
226           $content .= stripslashes($post_data['post_content']);
227
228           $struct = array(
229             'userid'    => $post_data['post_author'],
230             'dateCreated' => new IXR_Date(mysql2date('Ymd\TH:i:s', $post_data['post_date'])),
231             'content'     => $content,
232             'postid'  => $post_data['ID']
233           );
234
235           return $struct;
236         }
237
238
239         /* blogger.getRecentPosts ...gets recent posts */
240         function blogger_getRecentPosts($args) {
241
242           global $wpdb;
243
244                 $this->escape($args);
245
246                 $blog_ID    = (int) $args[1]; /* though we don't use it yet */
247                 $user_login = $args[2];
248                 $user_pass  = $args[3];
249                 $num_posts  = $args[4];
250
251           if (!$this->login_pass_ok($user_login, $user_pass)) {
252             return $this->error;
253           }
254
255           $posts_list = wp_get_recent_posts($num_posts);
256
257           if (!$posts_list) {
258             $this->error = new IXR_Error(500, 'Either there are no posts, or something went wrong.');
259             return $this->error;
260           }
261
262           foreach ($posts_list as $entry) {
263           
264             $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
265             $categories = implode(',', wp_get_post_cats(1, $entry['ID']));
266
267             $content  = '<title>'.stripslashes($entry['post_title']).'</title>';
268             $content .= '<category>'.$categories.'</category>';
269             $content .= stripslashes($entry['post_content']);
270
271             $struct[] = array(
272               'userid' => $entry['post_author'],
273               'dateCreated' => new IXR_Date($post_date),
274               'content' => $content,
275               'postid' => $entry['ID'],
276             );
277
278           }
279
280           $recent_posts = array();
281           for ($j=0; $j<count($struct); $j++) {
282             array_push($recent_posts, $struct[$j]);
283           }
284
285           return $recent_posts;
286         }
287
288
289         /* blogger.getTemplate returns your blog_filename */
290         function blogger_getTemplate($args) {
291
292                 $this->escape($args);
293
294           $blog_ID    = (int) $args[1];
295           $user_login = $args[2];
296           $user_pass  = $args[3];
297           $template   = $args[4]; /* could be 'main' or 'archiveIndex', but we don't use it */
298
299           if (!$this->login_pass_ok($user_login, $user_pass)) {
300             return $this->error;
301           }
302
303           set_current_user(0, $user_login);
304           if ( !current_user_can('edit_themes') ) {
305             return new IXR_Error(401, 'Sorry, this user can not edit the template.');
306           }
307
308           /* warning: here we make the assumption that the weblog's URI is on the same server */
309           $filename = get_settings('home') . '/';
310           $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
311
312           $f = fopen($filename, 'r');
313           $content = fread($f, filesize($filename));
314           fclose($f);
315
316           /* so it is actually editable with a windows/mac client */
317           // 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); 
318
319           return $content;
320         }
321
322
323         /* blogger.setTemplate updates the content of blog_filename */
324         function blogger_setTemplate($args) {
325
326                 $this->escape($args);
327
328           $blog_ID    = (int) $args[1];
329           $user_login = $args[2];
330           $user_pass  = $args[3];
331           $content    = $args[4];
332           $template   = $args[5]; /* could be 'main' or 'archiveIndex', but we don't use it */
333
334           if (!$this->login_pass_ok($user_login, $user_pass)) {
335             return $this->error;
336           }
337
338           set_current_user(0, $user_login);
339           if ( !current_user_can('edit_themes') ) {
340             return new IXR_Error(401, 'Sorry, this user can not edit the template.');
341           }
342
343           /* warning: here we make the assumption that the weblog's URI is on the same server */
344           $filename = get_settings('home') . '/';
345           $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename);
346
347           if ($f = fopen($filename, 'w+')) {
348             fwrite($f, $content);
349             fclose($f);
350           } else {
351             return new IXR_Error(500, 'Either the file is not writable, or something wrong happened. The file has not been updated.');
352           }
353
354           return true;
355         }
356
357
358         /* blogger.newPost ...creates a new post */
359         function blogger_newPost($args) {
360
361           global $wpdb;
362
363                 $this->escape($args);
364
365           $blog_ID    = (int) $args[1]; /* though we don't use it yet */
366           $user_login = $args[2];
367           $user_pass  = $args[3];
368           $content    = $args[4];
369           $publish    = $args[5];
370
371           if (!$this->login_pass_ok($user_login, $user_pass)) {
372             return $this->error;
373           }
374           
375           $cap = ($publish) ? 'publish_posts' : 'edit_posts';
376           $user = set_current_user(0, $user_login);
377           if ( !current_user_can($cap) )
378             return new IXR_Error(401, 'Sorry, you can not post on this weblog or category.');
379
380           $post_status = ($publish) ? 'publish' : 'draft';
381
382           $post_author = $user->ID;
383
384           $post_title = xmlrpc_getposttitle($content);
385           $post_category = xmlrpc_getpostcategory($content);
386           $post_content = xmlrpc_removepostdata($content);
387
388           $post_date = current_time('mysql');
389           $post_date_gmt = current_time('mysql', 1);
390
391           $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status');
392
393           $post_ID = wp_insert_post($post_data);
394
395           if (!$post_ID) {
396             return new IXR_Error(500, 'Sorry, your entry could not be posted. Something wrong happened.');
397           }
398
399           logIO('O', "Posted ! ID: $post_ID");
400
401           return $post_ID;
402         }
403
404
405         /* blogger.editPost ...edits a post */
406         function blogger_editPost($args) {
407
408           global $wpdb;
409
410                 $this->escape($args);
411
412           $post_ID     = (int) $args[1];
413           $user_login  = $args[2];
414           $user_pass   = $args[3];
415           $content     = $args[4];
416           $publish     = $args[5];
417
418           if (!$this->login_pass_ok($user_login, $user_pass)) {
419             return $this->error;
420           }
421
422           $actual_post = wp_get_single_post($post_ID,ARRAY_A);
423
424           if (!$actual_post) {
425                 return new IXR_Error(404, 'Sorry, no such post.');
426           }
427
428                 $this->escape($actual_post);
429
430           set_current_user(0, $user_login);
431           if ( !current_user_can('edit_post', $post_ID) )
432             return new IXR_Error(401, 'Sorry, you do not have the right to edit this post.');
433
434           extract($actual_post, EXTR_SKIP);
435
436           if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
437                 return new IXR_Error(401, 'Sorry, you do not have the right to publish this post.');
438
439           $post_title = xmlrpc_getposttitle($content);
440           $post_category = xmlrpc_getpostcategory($content);
441           $post_content = xmlrpc_removepostdata($content);
442
443           $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt');
444
445           $result = wp_update_post($postdata);
446
447           if (!$result) {
448                 return new IXR_Error(500, 'For some strange yet very annoying reason, this post could not be edited.');
449           }
450
451           return true;
452         }
453
454
455         /* blogger.deletePost ...deletes a post */
456         function blogger_deletePost($args) {
457
458           global $wpdb;
459
460                 $this->escape($args);
461
462           $post_ID     = (int) $args[1];
463           $user_login  = $args[2];
464           $user_pass   = $args[3];
465           $publish     = $args[4];
466
467           if (!$this->login_pass_ok($user_login, $user_pass)) {
468             return $this->error;
469           }
470
471           $actual_post = wp_get_single_post($post_ID,ARRAY_A);
472
473           if (!$actual_post) {
474                 return new IXR_Error(404, 'Sorry, no such post.');
475           }
476
477           set_current_user(0, $user_login);
478           if ( !current_user_can('edit_post', $post_ID) )
479             return new IXR_Error(401, 'Sorry, you do not have the right to delete this post.');
480
481           $result = wp_delete_post($post_ID);
482
483           if (!$result) {
484                 return new IXR_Error(500, 'For some strange yet very annoying reason, this post could not be deleted.');
485           }
486
487           return true;
488         }
489
490
491
492         /* MetaWeblog API functions
493          * specs on wherever Dave Winer wants them to be
494          */
495
496         /* metaweblog.newPost creates a post */
497         function mw_newPost($args) {
498
499           global $wpdb, $post_default_category;
500
501                 $this->escape($args);
502
503           $blog_ID     = (int) $args[0]; // we will support this in the near future
504           $user_login  = $args[1];
505           $user_pass   = $args[2];
506           $content_struct = $args[3];
507           $publish     = $args[4];
508
509           if (!$this->login_pass_ok($user_login, $user_pass)) {
510             return $this->error;
511           }
512
513           $user = set_current_user(0, $user_login);
514           if ( !current_user_can('publish_posts') )
515             return new IXR_Error(401, 'Sorry, you can not post on this weblog or category.');
516
517           $post_author = $user->ID;
518
519           $post_title = $content_struct['title'];
520           $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
521           $post_status = $publish ? 'publish' : 'draft';
522
523           $post_excerpt = $content_struct['mt_excerpt'];
524           $post_more = $content_struct['mt_text_more'];
525
526           $comment_status = (empty($content_struct['mt_allow_comments'])) ?
527             get_settings('default_comment_status')
528             : $content_struct['mt_allow_comments'];
529
530           $ping_status = (empty($content_struct['mt_allow_pings'])) ?
531             get_settings('default_ping_status')
532             : $content_struct['mt_allow_pings'];
533
534           if ($post_more) {
535             $post_content = $post_content . "\n<!--more-->\n" . $post_more;
536           }
537
538           $to_ping = $content_struct['mt_tb_ping_urls'];
539           if ( is_array($to_ping) )
540                 $to_ping = implode(' ', $to_ping);
541
542           // Do some timestamp voodoo
543           $dateCreatedd = $content_struct['dateCreated'];
544           if (!empty($dateCreatedd)) {
545             $dateCreated = $dateCreatedd->getIso();
546             $post_date     = get_date_from_gmt(iso8601_to_datetime($dateCreated));
547             $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
548           } else {
549             $post_date     = current_time('mysql');
550             $post_date_gmt = current_time('mysql', 1);
551           }
552
553           $catnames = $content_struct['categories'];
554           logIO('O', 'Post cats: ' . printr($catnames,true));
555           $post_category = array();
556
557           if (is_array($catnames)) {
558             foreach ($catnames as $cat) {
559               $post_category[] = get_cat_ID($cat);
560             }
561           }
562                 
563           // We've got all the data -- post it:
564           $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');
565
566           $post_ID = wp_insert_post($postdata);
567
568           if (!$post_ID) {
569             return new IXR_Error(500, 'Sorry, your entry could not be posted. Something wrong happened.');
570           }
571
572           logIO('O', "Posted ! ID: $post_ID");
573
574           return strval($post_ID);
575         }
576
577
578         /* metaweblog.editPost ...edits a post */
579         function mw_editPost($args) {
580
581           global $wpdb, $post_default_category;
582
583                 $this->escape($args);
584
585           $post_ID     = (int) $args[0];
586           $user_login  = $args[1];
587           $user_pass   = $args[2];
588           $content_struct = $args[3];
589           $publish     = $args[4];
590
591           if (!$this->login_pass_ok($user_login, $user_pass)) {
592             return $this->error;
593           }
594
595           set_current_user(0, $user_login);
596           if ( !current_user_can('edit_post', $post_ID) )
597             return new IXR_Error(401, 'Sorry, you can not edit this post.');
598
599           $postdata = wp_get_single_post($post_ID, ARRAY_A);
600                 $this->escape($postdata);
601                 extract($postdata, EXTR_SKIP);
602
603           $post_title = $content_struct['title'];
604           $post_content = apply_filters( 'content_save_pre', $content_struct['description'] );
605           $catnames = $content_struct['categories'];
606
607           $post_category = array();
608                 
609           if (is_array($catnames)) {
610             foreach ($catnames as $cat) {
611               $post_category[] = get_cat_ID($cat);
612             }
613           }
614
615           $post_excerpt = $content_struct['mt_excerpt'];
616           $post_more = $content_struct['mt_text_more'];
617           $post_status = $publish ? 'publish' : 'draft';
618
619
620           if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
621                 return new IXR_Error(401, 'Sorry, you do not have the right to publish this post.');
622
623           if ($post_more) {
624             $post_content = $post_content . "\n<!--more-->\n" . $post_more;
625           }
626
627           $to_ping = $content_struct['mt_tb_ping_urls'];
628           if ( is_array($to_ping) )
629                 $to_ping = implode(' ', $to_ping);
630           
631           $comment_status = (empty($content_struct['mt_allow_comments'])) ?
632             get_settings('default_comment_status')
633             : $content_struct['mt_allow_comments'];
634
635           $ping_status = (empty($content_struct['mt_allow_pings'])) ?
636             get_settings('default_ping_status')
637             : $content_struct['mt_allow_pings'];
638
639           // Do some timestamp voodoo
640           $dateCreatedd = $content_struct['dateCreated'];
641           if (!empty($dateCreatedd)) {
642             $dateCreated = $dateCreatedd->getIso();
643             $post_date     = get_date_from_gmt(iso8601_to_datetime($dateCreated));
644             $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
645           } else {
646             $post_date     = $postdata['post_date'];
647             $post_date_gmt = $postdata['post_date_gmt'];
648           }
649
650           // We've got all the data -- post it:
651           $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping');
652
653           $result = wp_update_post($newpost);
654           if (!$result) {
655             return new IXR_Error(500, 'Sorry, your entry could not be edited. Something wrong happened.');
656           }
657
658           logIO('O',"(MW) Edited ! ID: $post_ID");
659
660           return true;
661         }
662
663
664         /* metaweblog.getPost ...returns a post */
665         function mw_getPost($args) {
666
667           global $wpdb;
668
669                 $this->escape($args);
670
671           $post_ID     = (int) $args[0];
672           $user_login  = $args[1];
673           $user_pass   = $args[2];
674
675           if (!$this->login_pass_ok($user_login, $user_pass)) {
676             return $this->error;
677           }
678
679           $postdata = wp_get_single_post($post_ID, ARRAY_A);
680
681           if ($postdata['post_date'] != '') {
682
683             $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date']);
684
685             $categories = array();
686             $catids = wp_get_post_cats('', $post_ID);
687             foreach($catids as $catid) {
688               $categories[] = get_cat_name($catid);
689             }
690
691             $post = get_extended($postdata['post_content']);
692             $link = post_permalink($postdata['ID']);
693
694             $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
695             $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0;
696
697             $resp = array(
698               'dateCreated' => new IXR_Date($post_date),
699               'userid' => $postdata['post_author'],
700               'postid' => $postdata['ID'],
701               'description' => $post['main'],
702               'title' => $postdata['post_title'],
703               'link' => $link,
704               'permaLink' => $link,
705 // commented out because no other tool seems to use this
706 //            'content' => $entry['post_content'],
707               'categories' => $categories,
708               'mt_excerpt' => $postdata['post_excerpt'],
709               'mt_text_more' => $post['extended'],
710               'mt_allow_comments' => $allow_comments,
711               'mt_allow_pings' => $allow_pings
712             );
713
714             return $resp;
715           } else {
716                 return new IXR_Error(404, 'Sorry, no such post.');
717           }
718         }
719
720
721         /* metaweblog.getRecentPosts ...returns recent posts */
722         function mw_getRecentPosts($args) {
723
724                 $this->escape($args);
725
726                 $blog_ID     = (int) $args[0];
727                 $user_login  = $args[1];
728                 $user_pass   = $args[2];
729                 $num_posts   = (int) $args[3];
730
731           if (!$this->login_pass_ok($user_login, $user_pass)) {
732             return $this->error;
733           }
734
735           $posts_list = wp_get_recent_posts($num_posts);
736
737           if (!$posts_list) {
738             $this->error = new IXR_Error(500, 'Either there are no posts, or something went wrong.');
739             return $this->error;
740           }
741
742           foreach ($posts_list as $entry) {
743           
744             $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
745             $categories = array();
746             $catids = wp_get_post_cats('', $entry['ID']);
747             foreach($catids as $catid) {
748               $categories[] = get_cat_name($catid);
749             }
750
751             $post = get_extended($entry['post_content']);
752             $link = post_permalink($entry['ID']);
753
754             $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
755             $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0;
756
757             $struct[] = array(
758               'dateCreated' => new IXR_Date($post_date),
759               'userid' => $entry['post_author'],
760               'postid' => $entry['ID'],
761               'description' => $post['main'],
762               'title' => $entry['post_title'],
763               'link' => $link,
764               'permaLink' => $link,
765 // commented out because no other tool seems to use this
766 //            'content' => $entry['post_content'],
767               'categories' => $categories,
768               'mt_excerpt' => $entry['post_excerpt'],
769               'mt_text_more' => $post['extended'],
770               'mt_allow_comments' => $allow_comments,
771               'mt_allow_pings' => $allow_pings
772             );
773
774           }
775
776           $recent_posts = array();
777           for ($j=0; $j<count($struct); $j++) {
778             array_push($recent_posts, $struct[$j]);
779           }
780           
781           return $recent_posts;
782         }
783
784
785         /* metaweblog.getCategories ...returns the list of categories on a given weblog */
786         function mw_getCategories($args) {
787
788           global $wpdb;
789
790                 $this->escape($args);
791
792                 $blog_ID     = (int) $args[0];
793                 $user_login  = $args[1];
794                 $user_pass   = $args[2];
795
796           if (!$this->login_pass_ok($user_login, $user_pass)) {
797             return $this->error;
798           }
799
800           $categories_struct = array();
801
802           // FIXME: can we avoid using direct SQL there?
803           if ($cats = $wpdb->get_results("SELECT cat_ID,cat_name FROM $wpdb->categories", ARRAY_A)) {
804             foreach ($cats as $cat) {
805               $struct['categoryId'] = $cat['cat_ID'];
806               $struct['description'] = $cat['cat_name'];
807               $struct['categoryName'] = $cat['cat_name'];
808               $struct['htmlUrl'] = wp_specialchars(get_category_link($cat['cat_ID']));
809               $struct['rssUrl'] = wp_specialchars(get_category_rss_link(false, $cat['cat_ID'], $cat['cat_name']));
810
811               $categories_struct[] = $struct;
812             }
813           }
814
815           return $categories_struct;
816         }
817
818
819         /* metaweblog.newMediaObject uploads a file, following your settings */
820         function mw_newMediaObject($args) {
821                 // adapted from a patch by Johann Richard
822                 // http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
823
824                 global $wpdb;
825
826                 $blog_ID     = (int) $args[0];
827                 $user_login  = $wpdb->escape($args[1]);
828                 $user_pass   = $wpdb->escape($args[2]);
829                 $data        = $args[3];
830
831                 $name = $data['name'];
832                 $type = $data['type'];
833                 $bits = $data['bits'];
834
835                 logIO('O', '(MW) Received '.strlen($bits).' bytes');
836
837                 if ( !$this->login_pass_ok($user_login, $user_pass) )
838                         return $this->error;
839
840                 set_current_user(0, $user_login);
841                 if ( !current_user_can('upload_files') ) {
842                         logIO('O', '(MW) User does not have upload_files capability');
843                         $this->error = new IXR_Error(401, 'You are not allowed to upload files to this site.');
844                         return $this->error;
845                 }
846
847                 $upload = wp_upload_bits($name, $type, $bits);
848                 if ( ! empty($upload['error']) ) {
849                         logIO('O', '(MW) Could not write file '.$name);
850                         return new IXR_Error(500, 'Could not write file '.$name);
851                 }
852                 
853                 return array('url' => $upload['url']);
854         }
855
856
857         /* MovableType API functions
858          * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
859          */
860
861         /* mt.getRecentPostTitles ...returns recent posts' titles */
862         function mt_getRecentPostTitles($args) {
863
864                 $this->escape($args);
865
866                 $blog_ID     = (int) $args[0];
867                 $user_login  = $args[1];
868                 $user_pass   = $args[2];
869                 $num_posts   = (int) $args[3];
870
871           if (!$this->login_pass_ok($user_login, $user_pass)) {
872             return $this->error;
873           }
874
875           $posts_list = wp_get_recent_posts($num_posts);
876
877           if (!$posts_list) {
878             $this->error = new IXR_Error(500, 'Either there are no posts, or something went wrong.');
879             return $this->error;
880           }
881
882           foreach ($posts_list as $entry) {
883           
884             $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
885
886             $struct[] = array(
887               'dateCreated' => new IXR_Date($post_date),
888               'userid' => $entry['post_author'],
889               'postid' => $entry['ID'],
890               'title' => $entry['post_title'],
891             );
892
893           }
894
895           $recent_posts = array();
896           for ($j=0; $j<count($struct); $j++) {
897             array_push($recent_posts, $struct[$j]);
898           }
899           
900           return $recent_posts;
901         }
902
903
904         /* mt.getCategoryList ...returns the list of categories on a given weblog */
905         function mt_getCategoryList($args) {
906
907           global $wpdb;
908
909                 $this->escape($args);
910
911                 $blog_ID     = (int) $args[0];
912                 $user_login  = $args[1];
913                 $user_pass   = $args[2];
914
915           if (!$this->login_pass_ok($user_login, $user_pass)) {
916             return $this->error;
917           }
918
919           $categories_struct = array();
920
921           // FIXME: can we avoid using direct SQL there?
922           if ($cats = $wpdb->get_results("SELECT cat_ID, cat_name FROM $wpdb->categories", ARRAY_A)) {
923             foreach ($cats as $cat) {
924               $struct['categoryId'] = $cat['cat_ID'];
925               $struct['categoryName'] = $cat['cat_name'];
926
927               $categories_struct[] = $struct;
928             }
929           }
930
931           return $categories_struct;
932         }
933
934
935         /* mt.getPostCategories ...returns a post's categories */
936         function mt_getPostCategories($args) {
937
938                 $this->escape($args);
939
940                 $post_ID     = (int) $args[0];
941                 $user_login  = $args[1];
942                 $user_pass   = $args[2];
943
944           if (!$this->login_pass_ok($user_login, $user_pass)) {
945             return $this->error;
946           }
947
948           $categories = array();
949           $catids = wp_get_post_cats('', intval($post_ID));
950           // first listed category will be the primary category
951           $isPrimary = true;
952           foreach($catids as $catid) {
953             $categories[] = array(
954               'categoryName' => get_cat_name($catid),
955               'categoryId' => $catid,
956               'isPrimary' => $isPrimary
957             );
958             $isPrimary = false;
959           }
960  
961           return $categories;
962         }
963
964
965         /* mt.setPostCategories ...sets a post's categories */
966         function mt_setPostCategories($args) {
967
968                 $this->escape($args);
969
970                 $post_ID     = (int) $args[0];
971                 $user_login  = $args[1];
972                 $user_pass   = $args[2];
973                 $categories  = $args[3];
974
975           if (!$this->login_pass_ok($user_login, $user_pass)) {
976             return $this->error;
977           }
978
979           set_current_user(0, $user_login);
980           if ( !current_user_can('edit_post', $post_ID) )
981             return new IXR_Error(401, 'Sorry, you can not edit this post.');
982
983           foreach($categories as $cat) {
984             $catids[] = $cat['categoryId'];
985           }
986         
987           wp_set_post_cats('', $post_ID, $catids);
988
989           return true;
990         }
991
992
993         /* mt.supportedMethods ...returns an array of methods supported by this server */
994         function mt_supportedMethods($args) {
995
996           $supported_methods = array();
997           foreach($this->methods as $key=>$value) {
998             $supported_methods[] = $key;
999           }
1000
1001           return $supported_methods;
1002         }
1003
1004
1005         /* mt.supportedTextFilters ...returns an empty array because we don't
1006            support per-post text filters yet */
1007         function mt_supportedTextFilters($args) {
1008           return array();
1009         }
1010
1011
1012         /* mt.getTrackbackPings ...returns trackbacks sent to a given post */
1013         function mt_getTrackbackPings($args) {
1014
1015           global $wpdb;
1016
1017           $post_ID = intval($args);
1018
1019           $actual_post = wp_get_single_post($post_ID, ARRAY_A);
1020
1021           if (!$actual_post) {
1022                 return new IXR_Error(404, 'Sorry, no such post.');
1023           }
1024
1025           $comments = $wpdb->get_results("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = $post_ID");
1026
1027           if (!$comments) {
1028                 return array();
1029           }
1030
1031           $trackback_pings = array();
1032           foreach($comments as $comment) {
1033             if ( 'trackback' == $comment->comment_type ) {
1034               $content = $comment->comment_content;
1035               $title = substr($content, 8, (strpos($content, '</strong>') - 8));
1036               $trackback_pings[] = array(
1037                 'pingTitle' => $title,
1038                 'pingURL'   => $comment->comment_author_url,
1039                 'pingIP'    => $comment->comment_author_IP
1040               );
1041                 }
1042           }
1043
1044           return $trackback_pings;
1045         }
1046
1047
1048         /* mt.publishPost ...sets a post's publish status to 'publish' */
1049         function mt_publishPost($args) {
1050
1051                 $this->escape($args);
1052
1053                 $post_ID     = (int) $args[0];
1054                 $user_login  = $args[1];
1055                 $user_pass   = $args[2];
1056
1057           if (!$this->login_pass_ok($user_login, $user_pass)) {
1058             return $this->error;
1059           }
1060
1061           set_current_user(0, $user_login);
1062           if ( !current_user_can('edit_post', $post_ID) )
1063             return new IXR_Error(401, 'Sorry, you can not edit this post.');
1064
1065           $postdata = wp_get_single_post($post_ID,ARRAY_A);
1066
1067           $postdata['post_status'] = 'publish';
1068
1069           // retain old cats
1070           $cats = wp_get_post_cats('',$post_ID);
1071           $postdata['post_category'] = $cats;
1072                 $this->escape($postdata);
1073
1074           $result = wp_update_post($postdata);
1075
1076           return $result;
1077         }
1078
1079
1080
1081         /* PingBack functions
1082          * specs on www.hixie.ch/specs/pingback/pingback
1083          */
1084
1085         /* pingback.ping gets a pingback and registers it */
1086         function pingback_ping($args) {
1087                 global $wpdb, $wp_version; 
1088
1089                 $this->escape($args);
1090
1091                 $pagelinkedfrom = $args[0];
1092                 $pagelinkedto   = $args[1];
1093
1094                 $title = '';
1095
1096                 $pagelinkedfrom = str_replace('&amp;', '&', $pagelinkedfrom);
1097                 $pagelinkedto   = preg_replace('#&([^amp\;])#is', '&amp;$1', $pagelinkedto);
1098
1099                 $error_code = -1;
1100
1101                 // Check if the page linked to is in our site
1102                 $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_settings('home')));
1103                 if( !$pos1 )
1104                         return new IXR_Error(0, 'Is there no link to us?');
1105
1106                 // let's find which post is linked to
1107                 // FIXME: does url_to_postid() cover all these cases already?
1108                 //        if so, then let's use it and drop the old code.
1109                 $urltest = parse_url($pagelinkedto);
1110                 if ($post_ID = url_to_postid($pagelinkedto)) {
1111                         $way = 'url_to_postid()';
1112                 } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) {
1113                         // the path defines the post_ID (archives/p/XXXX)
1114                         $blah = explode('/', $match[0]);
1115                         $post_ID = (int) $blah[1];
1116                         $way = 'from the path';
1117                 } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) {
1118                         // the querystring defines the post_ID (?p=XXXX)
1119                         $blah = explode('=', $match[0]);
1120                         $post_ID = (int) $blah[1];
1121                         $way = 'from the querystring';
1122                 } elseif (isset($urltest['fragment'])) {
1123                         // an #anchor is there, it's either...
1124                         if (intval($urltest['fragment'])) {
1125                                 // ...an integer #XXXX (simpliest case)
1126                                 $post_ID = (int) $urltest['fragment'];
1127                                 $way = 'from the fragment (numeric)';
1128                         } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) {
1129                                 // ...a post id in the form 'post-###'
1130                                 $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']);
1131                                 $way = 'from the fragment (post-###)';
1132                         } elseif (is_string($urltest['fragment'])) {
1133                                 // ...or a string #title, a little more complicated
1134                                 $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']);
1135                                 $sql = "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE '$title'";
1136                                 if (! ($post_ID = $wpdb->get_var($sql)) ) {
1137                                         // returning unknown error '0' is better than die()ing
1138                                         return new IXR_Error(0, '');
1139                                 }
1140                                 $way = 'from the fragment (title)';
1141                         }
1142                 } else {
1143                         // TODO: Attempt to extract a post ID from the given URL
1144                         return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.');
1145                 }
1146                 $post_ID = (int) $post_ID;
1147
1148
1149                 logIO("O","(PB) URI='$pagelinkedto' ID='$post_ID' Found='$way'");
1150
1151                 $post = get_post($post_ID);
1152
1153                 if ( !$post ) // Post_ID not found
1154                         return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.');
1155
1156                 if ( $post_ID == url_to_postid($pagelinkedfrom) )
1157                         return new IXR_Error(0, 'The source URI and the target URI cannot both point to the same resource.');
1158
1159                 // Check if pings are on
1160                 if ( 'closed' == $post->ping_status )
1161                         return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.');
1162
1163                 // Let's check that the remote site didn't already pingback this entry
1164                 $result = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post_ID' AND comment_author_url = '$pagelinkedfrom'");
1165
1166                 if ( $wpdb->num_rows ) // We already have a Pingback from this URL
1167                         return new IXR_Error(48, 'The pingback has already been registered.');
1168
1169                 // very stupid, but gives time to the 'from' server to publish !
1170                 sleep(1);
1171
1172                 // Let's check the remote site
1173                 $linea = wp_remote_fopen( $pagelinkedfrom );
1174                 if ( !$linea )
1175                         return new IXR_Error(16, 'The source URI does not exist.');
1176
1177                 // Work around bug in strip_tags():
1178                 $linea = str_replace('<!DOC', '<DOC', $linea);
1179                 $linea = preg_replace( '/[\s\r\n\t]+/', ' ', $linea ); // normalize spaces
1180                 $linea = preg_replace( "/ <(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea );
1181
1182                 preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle);
1183                 $title = $matchtitle[1];
1184                 if ( empty( $title ) )
1185                         return new IXR_Error(32, 'We cannot find a title on that page.');
1186
1187                 $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
1188
1189                 $p = explode( "\n\n", $linea );
1190                 
1191                 $sem_regexp_pb = "/(\\/|\\\|\*|\?|\+|\.|\^|\\$|\(|\)|\[|\]|\||\{|\})/";
1192                 $sem_regexp_fix = "\\\\$1";
1193                 $link = preg_replace( $sem_regexp_pb, $sem_regexp_fix, $pagelinkedfrom );
1194                 
1195                 $finished = false;
1196                 foreach ( $p as $para ) {
1197                         if ( $finished )
1198                                 continue;
1199                         if ( strstr( $para, $pagelinkedto ) ) {
1200                                 $context = preg_replace( "/.*<a[^>]+".$link."[^>]*>([^>]+)<\/a>.*/", "$1", $para );
1201                                 $excerpt = strip_tags( $para );
1202                                 $excerpt = trim( $excerpt );
1203                                 $use     = preg_quote( $context );
1204                                 $excerpt = preg_replace("|.*?\s(.{0,100}$use.{0,100})\s|s", "$1", $excerpt);
1205                                 $finished = true;
1206                         }
1207                 }
1208
1209                 if ( empty($context) ) // URL pattern not found
1210                         return new IXR_Error(17, 'The source URI does not contain a link to the target URI, and so cannot be used as a source.');
1211
1212                 $pagelinkedfrom = preg_replace('#&([^amp\;])#is', '&amp;$1', $pagelinkedfrom);
1213
1214                 $context = '[...] ' . wp_specialchars( $excerpt ) . ' [...]';
1215                 $original_pagelinkedfrom = $pagelinkedfrom;
1216                 $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom );
1217                 $original_title = $title;
1218
1219                 $comment_post_ID = (int) $post_ID;
1220                 $comment_author = $title;
1221                 $this->escape($comment_author);
1222                 $comment_author_url = $pagelinkedfrom;
1223                 $comment_content = $context;
1224                 $this->escape($comment_content);
1225                 $comment_type = 'pingback';
1226
1227                 $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type');
1228
1229                 wp_new_comment($commentdata);
1230                 do_action('pingback_post', $wpdb->insert_id);
1231                 
1232                 return "Pingback from $pagelinkedfrom to $pagelinkedto registered. Keep the web talking! :-)";
1233         }
1234
1235
1236         /* pingback.extensions.getPingbacks returns an array of URLs
1237            that pingbacked the given URL
1238            specs on http://www.aquarionics.com/misc/archives/blogite/0198.html */
1239         function pingback_extensions_getPingbacks($args) {
1240
1241                 global $wpdb;
1242
1243                 $this->escape($args);
1244
1245                 $url = $args;
1246
1247                 $post_ID = url_to_postid($url);
1248                 if (!$post_ID) {
1249                         // We aren't sure that the resource is available and/or pingback enabled
1250                         return new IXR_Error(33, 'The specified target URI cannot be used as a target. It either doesn\'t exist, or it is not a pingback-enabled resource.');
1251                 }
1252
1253                 $actual_post = wp_get_single_post($post_ID, ARRAY_A);
1254
1255                 if (!$actual_post) {
1256                         // No such post = resource not found
1257                         return new IXR_Error(32, 'The specified target URI does not exist.');
1258                 }
1259
1260                 $comments = $wpdb->get_results("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = $post_ID");
1261
1262                 if (!$comments) {
1263                         return array();
1264                 }
1265
1266                 $pingbacks = array();
1267                 foreach($comments as $comment) {
1268                         if ( 'pingback' == $comment->comment_type )
1269                                 $pingbacks[] = $comment->comment_author_url;
1270                 }
1271
1272                 return $pingbacks;
1273         }
1274 }
1275
1276
1277 $wp_xmlrpc_server = new wp_xmlrpc_server();
1278
1279 ?>