summaryrefslogtreecommitdiffstats
path: root/modules/blogapi.module
blob: 6cac8b7418c21eebf00d3663bc90124fdc801dea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
<?php

/**
 * @file
 * Enable users to post using applications that support XML-RPC blog APIs.
 */

/**
 * Implementation of hook_help().
 */
function blogapi_help($section) {
  switch ($section) {
    case 'admin/help#blogapi':
      $output = '<p>'. t('The blog API module enables a post to be posted to a site via external GUI applications.  Many users prefer to use external tools to improve their ability to read and post responses in a customized way.   The blog api provides users the freedom to use the blogging tools they want but still have the blogging server of choice.') .'</p>';
      $output .= '<p>'. t('When this module is enabled and configured you can use programs like <a href="%external-http-ecto-kung-foo-tv">Ecto</a> to create and publish posts from your desktop. Blog API module supports several XML-RPC based blogging APIs such as the <a href="%-">Blogger API</a>, <a href="%external-http-www-xmlrpc-com-metaWeblogApi">MetaWeblog API</a>, and most of the <a href="%external-http-www-movabletype-org-docs-mtmanual_programmatic-html">Movable Type API</a>. Any desktop blogging tools or other services (e.g. <a href="%external-http-www-flickr-com">Flickr\'s</a> "post to blog") that support these APIs should work with this site.', array('%external-http-ecto-kung-foo-tv' => 'http://ecto.kung-foo.tv/', '%-' => url('http://www.blogger.com/developers/api/1_docs/'), '%external-http-www-xmlrpc-com-metaWeblogApi' => 'http://www.xmlrpc.com/metaWeblogApi', '%external-http-www-movabletype-org-docs-mtmanual_programmatic-html' => 'http://www.movabletype.org/docs/mtmanual_programmatic.html', '%external-http-www-flickr-com' => 'http://www.flickr.com')) .'</p>';
      $output .= '<p>'. t('This module also allows site administrators to configure which content types can be posted via the external applications. So, for instance, users can post forum topics as well as blog posts. Where supported, the external applications will display each content type as a separate "blog".<!--break-->') .'</p>';
      $output .= t('<p>You can</p>
<ul>
<li>view the XML-RPC page on your site at &gt;&gt; <a href="%file-xmlrpc">xmlrpc.php</a>.</li>
<li><a href="%admin-settings-blogapi">administer &gt;&gt; settings &gt;&gt; blog api</a>.</li>
</ul>
', array('%file-xmlrpc' => 'xmlrpc.php', '%admin-settings-blogapi' => url('admin/settings/blogapi')));
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%blogapi">BlogApi page</a>.', array('%blogapi' => 'http://drupal.org/handbook/modules/blogapi/')) .'</p>';
      return $output;
    case 'admin/modules#description':
      return t('Allows users to post content using applications that support XML-RPC blog APIs.');
  }
}

/**
 * Implementation of hook_xmlrpc().
 */
function blogapi_xmlrpc() {
  return array(
    array(
      'blogger.getUsersBlogs',
      'blogapi_blogger_get_users_blogs',
      array('array', 'string', 'string', 'string'),
      t('Returns a list of weblogs to which an author has posting privileges.')),
    array(
      'blogger.getUserInfo',
      'blogapi_blogger_get_user_info',
      array('struct', 'string', 'string', 'string'),
      t('Returns information about an author in the system.')),
    array(
      'blogger.newPost',
      'blogapi_blogger_new_post',
      array('string', 'string', 'string', 'string', 'string', 'string', 'boolean'),
      t('Creates a new post, and optionally publishes it.')),
    array(
      'blogger.editPost',
      'blogapi_blogger_edit_post',
      array('boolean', 'string', 'string', 'string', 'string', 'string', 'boolean'),
      t('Updates the information about an existing post.')),
    array(
      'blogger.getPost',
      'blogapi_blogger_get_post',
      array('struct', 'string', 'string', 'string', 'string'),
      t('Returns information about a specific post.')),
    array(
      'blogger.deletePost',
      'blogapi_blogger_delete_post',
      array('boolean', 'string', 'string', 'string', 'string', 'boolean'),
      t('Deletes a post.')),
    array(
      'blogger.getRecentPosts',
      'blogapi_blogger_get_recent_posts',
      array('array', 'string', 'string', 'string', 'string', 'int'),
      t('Returns a list of the most recent posts in the system.')),
    array(
      'metaWeblog.newPost',
      'blogapi_metaweblog_new_post',
      array('string', 'string', 'string', 'string', 'struct', 'boolean'),
      t('Creates a new post, and optionally publishes it.')),
    array(
      'metaWeblog.editPost',
      'blogapi_metaweblog_edit_post',
      array('boolean', 'string', 'string', 'string', 'struct', 'boolean'),
      t('Updates information about an existing post.')),
    array(
      'metaWeblog.getPost',
      'blogapi_metaweblog_get_post',
      array('struct', 'string', 'string', 'string'),
      t('Returns information about a specific post.')),
    array(
      'metaWeblog.newMediaObject',
      'blogapi_metaweblog_new_media_object',
      array('string', 'string', 'string', 'string', 'struct'),
      t('Uploads a file to your webserver.')),
    array(
      'metaWeblog.getCategories',
      'blogapi_metaweblog_get_category_list',
      array('struct', 'string', 'string', 'string'),
      t('Returns a list of all categories to which the post is assigned.')),
    array(
      'metaWeblog.getRecentPosts',
      'blogapi_metaweblog_get_recent_posts',
      array('array', 'string', 'string', 'string', 'int'),
      t('Returns a list of the most recent posts in the system.')),
    array(
      'mt.getRecentPostTitles',
      'blogapi_mt_get_recent_post_titles',
      array('array', 'string', 'string', 'string', 'int'),
      t('Returns a bandwidth-friendly list of the most recent posts in the system.')),
    array(
      'mt.getCategoryList',
      'blogapi_mt_get_category_list',
      array('array', 'string', 'string', 'string'),
      t('Returns a list of all categories defined in the weblog.')),
    array(
      'mt.getPostCategories',
      'blogapi_mt_get_post_categories',
      array('array', 'string', 'string', 'string'),
      t('Returns a list of all categories to which the post is assigned.')),
    array(
      'mt.setPostCategories',
      'blogapi_mt_set_post_categories',
      array('boolean', 'string', 'string', 'string', 'array'),
      t('Sets the categories for a post.')),
    array(
      'mt.supportedMethods',
      'xmlrpc_server_list_methods',
      array('array'),
      t('Retrieve information about the XML-RPC methods supported by the server.')),
    array(
      'mt.supportedTextFilters',
      'blogapi_mt_supported_text_filters',
      array('array'),
      t('Retrieve information about the text formatting plugins supported by the server.')),
    array(
      'mt.getTrackbackPings',
      'blogapi_mt_get_trackback_pings',
      array('array', 'string'),
      t('Retrieve the list of TrackBack pings posted to a particular entry. This could be used to programmatically retrieve the list of pings for a particular entry, then iterate through each of those pings doing the same, until one has built up a graph of the web of entries referencing one another on a particular topic.')),
    array(
      'mt.publishPost',
      'blogap_mti_publish_post',
      array('boolean', 'string', 'string', 'string'),
      t('Publish (rebuild) all of the static files related to an entry from your weblog. Equivalent to saving an entry in the system (but without the ping).')));
}

/**
 * Blogging API callback. Finds the URL of a user's blog.
 */

function blogapi_blogger_get_users_blogs($appid, $username, $password) {

  $user = blogapi_validate_user($username, $password);
  if ($user->uid) {
    $types = _blogapi_get_node_types();
    $structs = array();
    foreach ($types as $type) {
      $structs[] = array('url' => url('blog/' . $user->uid, NULL, NULL, true), 'blogid' => $type, 'blogName' => $user->name . ": " . $type);
    }
    return $structs;
  }
  else {
    return blogapi_error($user);
  }
}

/**
 * Blogging API callback. Returns profile information about a user.
 */
function blogapi_blogger_get_user_info($appkey, $username, $password) {
  $user = blogapi_validate_user($username, $password);

  if ($user->uid) {
    $name = explode(' ', $user->realname ? $user->realname : $user->name, 2);
    return array(
      'userid' => $user->uid,
      'lastname' => $name[1],
      'firstname' => $name[0],
      'nickname' => $user->name,
      'email' => $user->mail,
      'url' => url('blog/' . $user->uid, NULL, NULL, true));
  }
  else {
    return blogapi_error($user);
  }
}

/**
 * Blogging API callback. Inserts a new blog post as a node.
 */
function blogapi_blogger_new_post($appkey, $blogid, $username, $password, $content, $publish) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  $edit = array();
  $edit['type'] = _blogapi_blogid($blogid);
  // get the node type defaults
  $node_type_default = variable_get('node_options_'. $edit['type'], array('status', 'promote'));
  $edit['uid'] = $user->uid;
  $edit['name'] = $user->name;
  $edit['promote'] = in_array('promote', $node_type_default);
  $edit['comment'] = variable_get('comment_'. $edit['type'], 2);
  $edit['moderate'] = in_array('moderate', $node_type_default);
  $edit['revision'] = in_array('revision', $node_type_default);
  $edit['format'] = FILTER_FORMAT_DEFAULT;
  $edit['status'] = $publish;

  // check for bloggerAPI vs. metaWeblogAPI
  if (is_array($content)) {
    $edit['title'] = $content['title'];
    $edit['body'] = $content['description'];
    _blogapi_mt_extra($edit, $content);
  }
  else {
    $edit['title'] = blogapi_blogger_title($content);
    $edit['body'] = $content;
  }

  if (!node_access('create', $edit['type'])) {
    return blogapi_error(t('You do not have permission to create the type of post you wanted to create.'));
  }

  if (user_access('administer nodes') && !isset($edit['date'])) {
    $edit['date'] = format_date(time(), 'custom', 'Y-m-d H:i:s O');
  }

  node_validate($edit);
  if ($errors = form_get_errors()) {
    return blogapi_error(implode("\n", $errors));
  }

  $node = node_submit($edit);
  node_save($node);
  if ($node->nid) {
    watchdog('content', t('%type: added %title using blog API.', array('%type' => '<em>'. t($node->type) .'</em>', '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
    // blogger.newPost returns a string so we cast the nid to a string by putting it in double quotes:
    return "$node->nid";
  }

  return blogapi_error(t('Error storing post.'));
}

/**
 * Blogging API callback. Modifies the specified blog node.
 */
function blogapi_blogger_edit_post($appkey, $postid, $username, $password, $content, $publish) {

  $user = blogapi_validate_user($username, $password);

  if (!$user->uid) {
    return blogapi_error($user);
  }

  $node = node_load($postid);
  if (!$node) {
    return blogapi_error(message_na());
  }
  // Let the teaser be re-generated.
  unset($node->teaser);

  if (!node_access('update', $node)) {
    return blogapi_error(t('You do not have permission to update this post.'));
  }

  $node->status = $publish;

  // check for bloggerAPI vs. metaWeblogAPI
  if (is_array($content)) {
    $node->title = $content['title'];
    $node->body = $content['description'];
    _blogapi_mt_extra($node, $content);
  }
  else {
    $node->title = blogapi_blogger_title($content);
    $node->body = $content;
  }

  node_validate($node);
  if ($errors = form_get_errors()) {
    return blogapi_error(implode("\n", $errors));
  }

  if (user_access('administer nodes') && !isset($edit['date'])) {
    $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
  }
  $node = node_submit($node);
  node_save($node);
  if ($node->nid) {
    watchdog('content', t('%type: updated %title using blog API.', array('%type' => '<em>'. t($node->type) .'</em>', '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
    return true;
  }

  return blogapi_error(t('Error storing post.'));
}

/**
 * Blogging API callback. Returns a specified blog node.
 */
function blogapi_blogger_get_post($appkey, $postid, $username, $password) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  $node = node_load($postid);

  return _blogapi_get_post($node, true);
}

/**
 * Blogging API callback. Removes the specified blog node.
 */
function blogapi_blogger_delete_post($appkey, $postid, $username, $password, $publish) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  node_delete($postid);
  return true;
}

/**
 * Blogging API callback. Returns the latest few postings in a user's blog. $bodies TRUE
 * <a href="http://movabletype.org/docs/mtmanual_programmatic.html#item_mt%2EgetRecentPostTitles">
 * returns a bandwidth-friendly list</a>.
 */
function blogapi_blogger_get_recent_posts($appkey, $blogid, $username, $password, $number_of_posts, $bodies = TRUE) {
  // Remove unused appkey (from bloggerAPI).
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  $type = _blogapi_blogid($blogid);
  if ($bodies) {
    $result = db_query_range("SELECT n.nid, n.title, r.body, r.format, n.comment, n.created, u.name FROM {node} n, {node_revisions} r, {users} u WHERE n.uid = u.uid AND n.vid = r.vid AND n.type = '%s' AND n.uid = %d ORDER BY n.created DESC",  $type, $user->uid, 0, $number_of_posts);
  }
  else {
    $result = db_query_range("SELECT n.nid, n.title, n.created, u.name FROM {node} n, {users} u WHERE n.uid = u.uid AND n.type = '%s' AND n.uid = %d ORDER BY n.created DESC", $type, $user->uid, 0, $number_of_posts);
  }
  $blogs = array ();
  while ($blog = db_fetch_object($result)) {
    $blogs[] = _blogapi_get_post($blog, $bodies);
  }
  return $blogs;
}

function blogapi_metaweblog_new_post($blogid, $username, $password, $content, $publish) {
  return blogapi_blogger_new_post('0123456789ABCDEF', $blogid, $username, $password, $content, $publish);
}

function blogapi_metaweblog_edit_post($postid, $username, $password, $content, $publish) {
  return blogapi_blogger_edit_post('0123456789ABCDEF', $postid, $username, $password, $content, $publish);
}

function blogapi_metaweblog_get_post($postid, $username, $password) {
  return blogapi_blogger_get_post('01234567890ABCDEF', $postid, $username, $password);
}

/**
 * Blogging API callback. Inserts a file into Drupal.
 */
function blogapi_metaweblog_new_media_object($blogid, $username, $password, $file) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  $name = basename($file['name']);
  $data = $file['bits'];

  if (!$data) {
    return blogapi_error(t('No file sent.'));
  }

  if (!$file = file_save_data($data, $name)) {
    return blogapi_error(t('Error storing file.'));
  }

  // Return the successful result.
  return array('url' => file_create_url($file), 'struct');
}
/**
 * Blogging API callback. Returns a list of the taxonomy terms that can be
 * associated with a blog node.
 */
function blogapi_metaweblog_get_category_list($blogid, $username, $password) {
  $type = _blogapi_blogid($blogid);
  $vocabularies = module_invoke('taxonomy', 'get_vocabularies', $type, 'vid');
  $categories = array();
  if ($vocabularies) {
    foreach ($vocabularies as $vocabulary) {
      $terms = module_invoke('taxonomy', 'get_tree', $vocabulary->vid, 0, -1);
      foreach ($terms as $term) {
        $term_name = $term->name;
        foreach (module_invoke('taxonomy', 'get_parents', $term->tid, 'tid') as $parent) {
          $term_name = $parent->name . '/' . $term_name;
        }
        $categories[] = array('categoryName' => $term_name, 'categoryId' => $term->tid);
      }
    }
  }
  return $categories;
}

function blogapi_metaweblog_get_recent_posts($blogid, $username, $password, $number_of_posts) {
  return blogapi_blogger_get_recent_posts('0123456789ABCDEF', $blogid, $username, $password, $number_of_posts, TRUE);
}

// see above
function blogapi_mt_get_recent_post_titles($blogid, $username, $password, $number_of_posts) {
  return blogapi_blogger_get_recent_posts('0123456789ABCDEF', $blogid, $username, $password, $number_of_posts, FALSE);
}

/* **** */
function blogapi_mt_get_category_list($blogid, $username, $password) {
  return blogapi_metaweblog_get_category_list($blogid, $username, $password);
}

/**
 * Blogging API callback. Returns a list of the taxonomy terms that are
 * assigned to a particular node.
 */
function blogapi_mt_get_post_categories($postid, $username, $password) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  $terms = module_invoke('taxonomy', 'node_get_terms', $postid, 'tid');
  $categories = array();
  foreach ($terms as $term) {
    $term_name = $term->name;
    foreach (module_invoke('taxonomy', 'get_parents', $term->tid, 'tid') as $parent) {
      $term_name = $parent->name . '/' . $term_name;
    }
    $categories[] = array('categoryName' => $term_name, 'categoryId' => $term->tid, 'isPrimary' => true);
  }
  return $categories;
}

/**
 * Blogging API callback. Assigns taxonomy terms to a particular node.
 */
function blogapi_mt_set_post_categories($postid, $username, $password, $categories) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }

  $node = node_load($postid);
  $node->taxonomy = array();
  foreach ($categories as $category) {
    $node->taxonomy[] = $category['categoryId'];
  }
  node_save($node);
  return TRUE;
}

/**
 * Blogging API callback. Sends a list of available input formats.
 */
function blogapi_mt_supported_text_filters() {
  // NOTE: we're only using anonymous' formats because the MT spec
  // does not allow for per-user formats.
  $formats = filter_formats();

  $filters = array();
  foreach ($formats as $format) {
    $filter['key'] = $format->format;
    $filter['label'] = $format->name;
    $filters[] = $filter;
  }

  return $filters;
}

/**
 * Blogging API callback. Can not be implemented without support from
 * trackback module.
 */
function blogapi_mt_get_trackback_pings() {
  return blogapi_error(t('Not implemented.'));
}

/**
 * Blogging API callback. Publishes the given node
 */
function blogap_mti_publish_post($postid, $username, $password) {
  $user = blogapi_validate_user($username, $password);
  if (!$user->uid) {
    return blogapi_error($user);
  }
  $node = node_load($postid);
  if (!$node) {
    return blogapi_error(t('Invalid post.'));
  }

  $node->status = 1;
  if (!node_access('update', $node)) {
    return blogapi_error(t('You do not have permission to update this post.'));
  }

  node_save($node);

  return true;
}

/**
 * Prepare an error message for returning to the XMLRPC caller.
 */
function blogapi_error($message) {
  static $xmlrpcusererr;
  if (!is_array($message)) {
    $message = array($message);
  }

  $message = implode(' ', $message);

  return xmlrpc_error($xmlrpcusererr + 1, strip_tags($message));
}

/**
 * Ensure that the given user has permission to edit a blog.
 */
function blogapi_validate_user($username, $password) {
  global $user;

  $user = user_authenticate($username, $password);

  if ($user->uid) {
    if (user_access('edit own blog', $user)) {
      return $user;
    }
    else {
      return t("You either tried to edit somebody else's blog or you don't have permission to edit your own blog.");
    }
  }
  else {
    return t('Wrong username or password.');
  }
}

/**
 * For the blogger API, extract the node title from the contents field.
 */
function blogapi_blogger_title(&$contents) {
  if (eregi('<title>([^<]*)</title>', $contents, $title)) {
    $title = strip_tags($title[0]);
    $contents = ereg_replace('<title>[^<]*</title>', '', $contents);
  }
  else {
    list($title, $contents) = explode("\n", $contents, 2);
  }
  return $title;
}

function blogapi_settings() {
  $form['blogapi_engine'] = array(
    '#type' => 'select', '#title' => t('XML-RPC Engine'), '#default_value' => variable_get('blogapi_engine', 0),
    '#options' => array(0 => 'Blogger', 1 => 'MetaWeblog', 2 => 'Movabletype'),
    '#description' => t('RSD or Really-Simple-Discovery is a mechanism which allows external blogger tools to discover the APIs they can use to interact with Drupal. Here you can set the preferred method for blogger tools to interact with your site. The common XML-RPC engines are Blogger, MetaWeblog and Movabletype. If you are not sure which is the correct setting, choose Blogger.')
  );

  $node_types = node_get_types();
  $defaults = isset($node_types['blog']) ? array('blog' => 1) : array();
  $form['blogapi_node_types'] = array(
    '#type' => 'checkboxes', '#title' => t('Blog types'), '#required' => TRUE,
    '#default_value' => variable_get('blogapi_node_types', $defaults), '#options' => $node_types,
    '#description' => t('Select the content types for which you wish to enable posting via blogapi. Each type will appear as a different "blog" in the client application (if supported).')
  );

  return $form;
}

function blogapi_menu($may_cache) {
  $items = array();

  if (drupal_is_front_page()) {
    drupal_add_link(array('rel' => 'EditURI',
                          'type' => 'application/rsd+xml',
                          'title' => t('RSD'),
                          'href' => url('blogapi/rsd', NULL, NULL, TRUE)));
  }

  if ($may_cache) {
    $items[] = array('path' => 'blogapi', 'title' => t('RSD'), 'callback' => 'blogapi_blogapi', 'access' => user_access('access content'), 'type' => MENU_CALLBACK);
  }

  return $items;
}

function blogapi_blogapi() {
  switch (arg(1)) {
    case 'rsd':
      blogapi_rsd();
      break;
    default:
      drupal_not_found();
      break;
  }
}

function blogapi_rsd() {
  global $base_url;

  $xmlrpc = $base_url .'/'. 'xmlrpc.php';
  $base = url('', NULL, NULL, TRUE);
  $blogid = 1; # until we figure out how to handle multiple bloggers

  drupal_set_header('Content-Type: application/rsd+xml; charset=utf-8');
  print <<<__RSD__
<?xml version="1.0"?>
<rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd">
  <service>
    <engineName>Drupal</engineName>
    <engineLink>http://drupal.org/</engineLink>
    <homePageLink>$base</homePageLink>
    <apis>
      <api name="MetaWeblog" preferred="false" apiLink="$xmlrpc" blogID="$blogid" />
      <api name="Blogger" preferred="true" apiLink="$xmlrpc" blogID="$blogid" />
      <api name="MovableType" preferred="false" apiLink="$xmlrpc" blogID="$blogid" />
    </apis>
  </service>
</rsd>
__RSD__;
}

/**
 * Handles extra information sent by clients according to MovableType's spec.
 */
function _blogapi_mt_extra(&$node, $struct) {
  if (is_array($node)) {
    $was_array = true;
    $node = (object)$node;
  }

  // mt_allow_comments
  if (array_key_exists('mt_allow_comments', $struct)) {
    switch ($struct['mt_allow_comments']) {
      case 0:
        $node->comment = COMMENT_NODE_DISABLED;
        break;
      case 1:
        $node->comment = COMMENT_NODE_READ_WRITE;
        break;
      case 2:
        $node->comment = COMMENT_NODE_READ_ONLY;
        break;
    }
  }

  // merge the 3 body sections (description, mt_excerpt, mt_text_more) into
  // one body
  if ($struct['mt_excerpt']) {
    $node->body = $struct['mt_excerpt'] .'<!--break-->'.$node->body;
  }
  if ($struct['mt_text_more']) {
    $node->body = $node->body . '<!--extended-->' . $struct['mt_text_more'];
  }

  // mt_tb_ping_urls
  if (function_exists('trackback_send')) {
    if (is_array($struct['mt_tb_ping_urls'])) {
      foreach ($struct['mt_tb_ping_urls'] as $tb_ping_url) {
        $node->tb_url = $tb_ping_url->getVal();
        trackback_send($node);
        unset($node->tb_url); // make sure we don't ping twice
      }
    }
    else {
      $node->tb_url = $struct['mt_tb_ping_urls'];
    }
  }

  // mt_convert_breaks
  if ($struct['mt_convert_breaks']) {
    $node->format = $struct['mt_convert_breaks'];
  }

  // dateCreated
  if ($struct['dateCreated']) {
    $node->date = format_date(mktime($struct['dateCreated']->hour, $struct['dateCreated']->minute, $struct['dateCreated']->second, $struct['dateCreated']->month, $struct['dateCreated']->day, $struct['dateCreated']->year), 'custom', 'Y-m-d H:i:s O');
  }

  if ($was_array) {
    $node = (array)$node;
  }
}

function _blogapi_get_post($node, $bodies = true) {
  $xmlrpcval = array (
    'userid' => $node->name,
    'dateCreated' => xmlrpc_date($node->created),
    'title' => $node->title,
    'postid' => $node->nid,
    'link' => url('node/'.$node->nid, NULL, NULL, true),
    'permaLink' => url('node/'.$node->nid, NULL, NULL, true),
  );
  if ($bodies) {
    if ($node->comment == 1) {
      $comment = 2;
    }
    else if ($node->comment == 2) {
      $comment = 1;
    }

    $xmlrpcval['content'] = "<title>$node->title</title>$node->body";
    $xmlrpcval['description'] = $node->body;
    // Add MT specific fields
    $xmlrpcval['mt_allow_comments'] = (int)$comment;
    $xmlrpcval['mt_convert_breaks'] = $node->format;
  }

  return $xmlrpcval;
}

function _blogapi_blogid($id) {
  if (is_numeric($id)) {
    return 'blog';
  }
  else {
    return $id;
  }
}

function _blogapi_get_node_types() {
  $available_types = array_keys(array_filter(variable_get('blogapi_node_types', array('blog' => 1))));
  $types = array();
  foreach (node_get_types() as $type => $name) {
    if (node_access('create', $type) && in_array($type, $available_types)) {
      $types[] = $type;
    }
  }

  return $types;
}