ajax.php
4 years ago
delete_data_ajax.php
4 years ago
export_geo_ajax.php
4 years ago
export_referrers_ajax.php
4 years ago
export_views_ajax.php
4 years ago
filters_ajax.php
4 years ago
migration_status_ajax.php
4 years ago
ajax.php
90 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWP; |
| 4 | |
| 5 | abstract class AJAX |
| 6 | { |
| 7 | public function __construct() |
| 8 | { |
| 9 | add_action('wp_ajax_' . $this->action_name(), [$this, 'intercept_ajax']); |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * Classes must define an action name for the ajax request |
| 14 | * |
| 15 | * The required nonce for the ajax request will be the action name with a "_nonce" postfix |
| 16 | * Example: "iawp_delete_data" require a "iawp_delete_data_nonce" nonce field |
| 17 | * |
| 18 | * @return string |
| 19 | */ |
| 20 | abstract protected function action_name(): string; |
| 21 | |
| 22 | /** |
| 23 | * Classes must define an action callback to run when an ajax request is made |
| 24 | * |
| 25 | * @return void |
| 26 | */ |
| 27 | abstract protected function action_callback(): void; |
| 28 | |
| 29 | /** |
| 30 | * Classes can define a set of required fields for an ajax request |
| 31 | * |
| 32 | * @return array |
| 33 | */ |
| 34 | protected function action_required_fields(): array |
| 35 | { |
| 36 | return []; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * This is the direct handler for ajax requests. |
| 41 | * Permissions and nonce values are checked before executing the ajax action_callback function. |
| 42 | * |
| 43 | * @return void |
| 44 | */ |
| 45 | final public function intercept_ajax(): void |
| 46 | { |
| 47 | if (!IAWP()->min_permission_level('admin') || Migration::is_migrating() || $this->missing_fields()) { |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | check_ajax_referer($this->action_name(), $this->action_name() . '_nonce'); |
| 52 | |
| 53 | $this->action_callback(); |
| 54 | |
| 55 | wp_die(); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Get a field value. This method supports text and arrays. Returns array if no field found. |
| 60 | * |
| 61 | * @param $field_name |
| 62 | * @return array|string|null |
| 63 | */ |
| 64 | final protected function get_field($field_name) |
| 65 | { |
| 66 | if (!array_key_exists($field_name, $_POST)) { |
| 67 | return null; |
| 68 | } |
| 69 | |
| 70 | $type = gettype($_POST[$field_name]); |
| 71 | |
| 72 | if ($type == 'array') { |
| 73 | return rest_sanitize_array($_POST[$field_name]); |
| 74 | } else { |
| 75 | return sanitize_text_field($_POST[$field_name]); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | private function missing_fields(): bool |
| 80 | { |
| 81 | foreach ($this->action_required_fields() as $required_field) { |
| 82 | if (!array_key_exists($required_field, $_POST)) { |
| 83 | return true; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | return false; |
| 88 | } |
| 89 | } |
| 90 |