sms.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. define('DEBUG', true);
  3. define('PARAMS', array('to', 'from', 'body', 'is_mms'));
  4. define('PARAMS_MMS', array('url', 'file_name', 'mime_type', 'file_size'));
  5. debug_log('READ');
  6. $data = @file_get_contents('php://input');
  7. if (!$data) {
  8. fail('READ');
  9. }
  10. debug_log('JSON');
  11. $data = @json_decode($data);
  12. if (!$data || !is_object($data)) {
  13. fail('JSON');
  14. }
  15. debug_log('FIND');
  16. if (!property_exists($data, 'data') || !is_object($data->{'data'}) ||
  17. !property_exists($data->{'data'}, 'attributes') ||
  18. !is_object($data->{'data'}->{'attributes'})
  19. ) {
  20. fail('FIND');
  21. }
  22. $msg = $data->{'data'}->{'attributes'};
  23. debug_log('PARSE');
  24. foreach (PARAMS as $param) {
  25. if (!property_exists($msg, $param)) {
  26. fail('PARSE: ' . $param);
  27. }
  28. }
  29. $sms = array();
  30. foreach (PARAMS as $param) {
  31. $sms[$param] = $msg->{$param};
  32. }
  33. unset($msg);
  34. if ($sms['is_mms']) {
  35. debug_log('FIND_MMS');
  36. if (!property_exists($data, 'included') || !is_array($data->{'included'})) {
  37. fail('FIND_MMS');
  38. }
  39. $msg = $data->{'included'};
  40. foreach ($msg as $part) {
  41. if (!property_exists($part, 'attributes') || !is_object($part->{'attributes'})) {
  42. fail('FIND_MMS_PART');
  43. }
  44. $part = $part->{'attributes'};
  45. debug_log('PARSE_MMS');
  46. foreach (PARAMS_MMS as $param) {
  47. if (!property_exists($part, $param)) {
  48. fail('PARSE_MMS: ' . $param);
  49. }
  50. }
  51. $media = array();
  52. foreach (PARAMS_MMS as $param) {
  53. $media[$param] = $part->{$param};
  54. }
  55. $sms['media'][] = $media;
  56. unset($msg);
  57. }
  58. }
  59. if (DEBUG) {
  60. debug_log('DEBUG');
  61. debug_log(print_r($sms, true));
  62. $file = @tempnam('/var/tmp', 'sms.');
  63. if (!$file) {
  64. fail('STORE_INIT');
  65. }
  66. debug_log('File: ' . $file);
  67. if (!@file_put_contents($file . '.raw', print_r($data, true))) {
  68. fail('STORE_RAW');
  69. }
  70. if (!@file_put_contents($file, print_r($sms, true))) {
  71. fail('STORE_PARSED');
  72. }
  73. }
  74. function fail($msg = 'Unknown error', $code = 500) {
  75. http_response_code($code);
  76. echo 'Unable to process request: ' . $msg . "\n";
  77. exit(0);
  78. }
  79. function debug_log($msg) {
  80. if (! DEBUG) {
  81. return;
  82. }
  83. echo $msg . "\n";
  84. }
  85. ?>