Controller.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php if ( ! defined( 'ABSPATH' ) ) exit;
  2. /**
  3. * A controller extensions for mapping REST requests to an admin-ajax action.
  4. */
  5. abstract class NF_AJAX_REST_Controller extends NF_Abstracts_Controller
  6. {
  7. /**
  8. * The name of the admin-ajax action.
  9. * @var string
  10. */
  11. protected $action;
  12. /**
  13. * Setup admin-ajax to access the endpoint router.
  14. */
  15. public function __construct()
  16. {
  17. if( $this->action ) {
  18. add_action('wp_ajax_' . $this->action, array($this, 'route'));
  19. }
  20. }
  21. /**
  22. * Map admin-ajax requests to the corresponding method callback.
  23. */
  24. public function route()
  25. {
  26. register_shutdown_function( array( $this, 'shutdown' ) );
  27. $method = strtolower( $_SERVER['REQUEST_METHOD'] );
  28. /*
  29. * Request Method Override
  30. * Allows for a POST request to function as another Request Method
  31. * by passing a `method_override` value as a request parameter.
  32. * For example, some servers do not support the DELETE request method.
  33. */
  34. if( 'post' == $method and isset( $_REQUEST[ 'method_override' ] ) ){
  35. $method = sanitize_text_field( $_REQUEST[ 'method_override' ] );
  36. }
  37. if( ! method_exists( $this, $method ) ){
  38. $this->_errors[] = __( 'Endpoint does not exist.', 'ninja-forms' );
  39. $this->_respond();
  40. }
  41. $request_data = $this->get_request_data();
  42. try {
  43. $data = $this->$method($request_data);
  44. $this->_respond( $data );
  45. } catch( Exception $e ) {
  46. $this->_errors[] = $e->getMessage();
  47. }
  48. $this->_respond();
  49. }
  50. /**
  51. * [OVERRIDE THIS] Get sanitized request data for use in method callbacks.
  52. * @return array
  53. */
  54. protected function get_request_data()
  55. {
  56. // This section intentionally left blank.
  57. /*
  58. * [Example] FORM ID
  59. */
  60. // if( isset( $_REQUEST[ 'form_id' ] ) && $_REQUEST[ 'form_id' ] ){
  61. // $request_data[ 'form_id' ] = absint( $_REQUEST[ 'form_id' ] );
  62. // }
  63. return array();
  64. }
  65. /**
  66. * Returns debugging data when a fatal error is triggered.
  67. */
  68. public function shutdown()
  69. {
  70. $error = error_get_last();
  71. if( $error !== NULL && in_array( $error[ 'type' ], array( E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR ) ) ) {
  72. $this->_errors[ 'form' ][ 'last' ] = __( 'The server encountered an error during processing.', 'ninja-forms' );
  73. if( current_user_can( 'manage_options' ) && isset( $error[ 'message' ] ) ){
  74. $this->_errors[ 'form' ][ 'last_admin' ] = '<pre>' . $error[ 'message' ] . '</pre>';
  75. }
  76. $this->_errors[ 'last' ] = $error;
  77. $this->_respond();
  78. }
  79. }
  80. }