router.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. require('config.php');
  3. class BogusAction {
  4. public $action;
  5. public $method;
  6. public $data;
  7. public $tid;
  8. }
  9. $isForm = false;
  10. $isUpload = false;
  11. if(isset($HTTP_RAW_POST_DATA)){
  12. header('Content-Type: text/javascript');
  13. $data = json_decode($HTTP_RAW_POST_DATA);
  14. }else if(isset($_POST['extAction'])){ // form post
  15. $isForm = true;
  16. $isUpload = $_POST['extUpload'] == 'true';
  17. $data = new BogusAction();
  18. $data->action = $_POST['extAction'];
  19. $data->method = $_POST['extMethod'];
  20. $data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null; // not set for upload
  21. $data->data = array($_POST, $_FILES);
  22. }else{
  23. die('Invalid request.');
  24. }
  25. function doRpc($cdata){
  26. global $API;
  27. try {
  28. if(!isset($API[$cdata->action])){
  29. throw new Exception('Call to undefined action: ' . $cdata->action);
  30. }
  31. $action = $cdata->action;
  32. $a = $API[$action];
  33. doAroundCalls($a['before'], $cdata);
  34. $method = $cdata->method;
  35. $mdef = $a['methods'][$method];
  36. if(!$mdef){
  37. throw new Exception("Call to undefined method: $method on action $action");
  38. }
  39. doAroundCalls($mdef['before'], $cdata);
  40. $r = array(
  41. 'type'=>'rpc',
  42. 'tid'=>$cdata->tid,
  43. 'action'=>$action,
  44. 'method'=>$method
  45. );
  46. require_once("classes/$action.php");
  47. $o = new $action();
  48. if (isset($mdef['len'])) {
  49. $params = isset($cdata->data) && is_array($cdata->data) ? $cdata->data : array();
  50. } else {
  51. $params = array($cdata->data);
  52. }
  53. $r['result'] = call_user_func_array(array($o, $method), $params);
  54. doAroundCalls($mdef['after'], $cdata, $r);
  55. doAroundCalls($a['after'], $cdata, $r);
  56. }
  57. catch(Exception $e){
  58. $r['type'] = 'exception';
  59. $r['message'] = $e->getMessage();
  60. $r['where'] = $e->getTraceAsString();
  61. }
  62. return $r;
  63. }
  64. function doAroundCalls(&$fns, &$cdata, &$returnData=null){
  65. if(!$fns){
  66. return;
  67. }
  68. if(is_array($fns)){
  69. foreach($fns as $f){
  70. $f($cdata, $returnData);
  71. }
  72. }else{
  73. $fns($cdata, $returnData);
  74. }
  75. }
  76. $response = null;
  77. if(is_array($data)){
  78. $response = array();
  79. foreach($data as $d){
  80. $response[] = doRpc($d);
  81. }
  82. }else{
  83. $response = doRpc($data);
  84. }
  85. if($isForm && $isUpload){
  86. echo '<html><body><textarea>';
  87. echo json_encode($response);
  88. echo '</textarea></body></html>';
  89. }else{
  90. echo json_encode($response);
  91. }