root/trunk/xmlrpc.php

Revision 994, 54.0 kB (checked in by donncha, 6 days ago)

Mostly merge xmlrpc.php from wp to 5651

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