You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.9 KiB

  1. <?php
  2. $app->post('/mailgun', function() use($app) {
  3. $params = $app->request()->params();
  4. // Find the user for this email
  5. if(!preg_match('/([^ <>]+)@'.Config::$hostname.'/', $params['To'], $match)) {
  6. $app->response()->body('invalid recipient');
  7. return;
  8. }
  9. $user = ORM::for_table('users')->where('email_username', $match[1])->find_one();
  10. if(!$user) {
  11. $app->response()->body('user not found');
  12. return;
  13. }
  14. if(!$user->micropub_access_token) {
  15. $app->response()->body('user has no access token');
  16. return;
  17. }
  18. $data = array(
  19. 'published' => (k($params, 'Date') ? date('c', strtotime(k($params, 'Date'))) : date('c'))
  20. );
  21. if(k($params, 'Subject'))
  22. $data['name'] = k($params, 'Subject');
  23. if(k($params['body-plain'])
  24. $data['content'] = k($params, 'body-plain');
  25. // Set tags for any hashtags used in the body
  26. if(preg_match_all('/#([^ ]+)/', $data['content'], $matches)) {
  27. $tags = array();
  28. foreach($matches[1] as $m)
  29. $tags[] = $m;
  30. if($tags) {
  31. if($user->send_category_as_array != 1) {
  32. $data['category'] = $tags;
  33. } else {
  34. $data['category'] = implode(',', $tags);
  35. }
  36. }
  37. }
  38. // Handle attachments
  39. $filename = false;
  40. foreach($_FILES as $file) {
  41. // If a photo was included, set the filename to the downloaded file
  42. if(preg_match('/image/', $file['type'])) {
  43. $filename = $file['tmp_name'];
  44. }
  45. // Sometimes MMSs are sent with a txt file attached instead of in the body
  46. if(preg_match('/text\/plain/', $file['type'])) {
  47. $content = trim(file_get_contents($file['tmp_name']));
  48. if($content) {
  49. $data['content'] = $content;
  50. }
  51. }
  52. }
  53. $r = micropub_post_for_user($user, $data, $filename);
  54. if(k($r, 'location'))
  55. $result = 'created post at ' . $r['location'];
  56. else
  57. $result = 'error creating post';
  58. $app->response()->body($result);
  59. });