Completed
Branch dev (588c07)
by
unknown
24:15 queued 17:27
created
core/services/database/OptionEngine.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -12,75 +12,75 @@
 block discarded – undo
12 12
  */
13 13
 class OptionEngine
14 14
 {
15
-    /**
16
-     * @var   bool
17
-     */
18
-    private $is_network_option;
15
+	/**
16
+	 * @var   bool
17
+	 */
18
+	private $is_network_option;
19 19
 
20
-    /**
21
-     * @var   int
22
-     */
23
-    private $network_ID;
20
+	/**
21
+	 * @var   int
22
+	 */
23
+	private $network_ID;
24 24
 
25 25
 
26
-    /**
27
-     * @param bool $is_network_option
28
-     */
29
-    public function __construct(bool $is_network_option = false)
30
-    {
31
-        $this->is_network_option = $is_network_option;
32
-        $this->network_ID        = get_current_network_id();
33
-    }
26
+	/**
27
+	 * @param bool $is_network_option
28
+	 */
29
+	public function __construct(bool $is_network_option = false)
30
+	{
31
+		$this->is_network_option = $is_network_option;
32
+		$this->network_ID        = get_current_network_id();
33
+	}
34 34
 
35 35
 
36
-    /**
37
-     * @param string $option_name
38
-     * @param mixed  $default_value
39
-     * @return false|mixed|void
40
-     */
41
-    public function getOption(string $option_name, $default_value)
42
-    {
43
-        return $this->is_network_option
44
-            ? get_network_option($this->network_ID, $option_name, $default_value)
45
-            : get_option($option_name, $default_value);
46
-    }
36
+	/**
37
+	 * @param string $option_name
38
+	 * @param mixed  $default_value
39
+	 * @return false|mixed|void
40
+	 */
41
+	public function getOption(string $option_name, $default_value)
42
+	{
43
+		return $this->is_network_option
44
+			? get_network_option($this->network_ID, $option_name, $default_value)
45
+			: get_option($option_name, $default_value);
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * @param string $option_name
51
-     * @param mixed  $value
52
-     * @param string $autoload
53
-     * @return bool
54
-     */
55
-    public function addOption(string $option_name, $value, string $autoload): bool
56
-    {
57
-        return $this->is_network_option
58
-            ? add_network_option($this->network_ID, $option_name, $value)
59
-            : add_option($option_name, $value, '', $autoload);
60
-    }
49
+	/**
50
+	 * @param string $option_name
51
+	 * @param mixed  $value
52
+	 * @param string $autoload
53
+	 * @return bool
54
+	 */
55
+	public function addOption(string $option_name, $value, string $autoload): bool
56
+	{
57
+		return $this->is_network_option
58
+			? add_network_option($this->network_ID, $option_name, $value)
59
+			: add_option($option_name, $value, '', $autoload);
60
+	}
61 61
 
62 62
 
63
-    /**
64
-     * @param string $option_name
65
-     * @param mixed  $value
66
-     * @return bool
67
-     */
68
-    public function updateOption(string $option_name, $value): bool
69
-    {
70
-        return $this->is_network_option
71
-            ? update_network_option($this->network_ID, $option_name, $value)
72
-            : update_option($option_name, $value);
73
-    }
63
+	/**
64
+	 * @param string $option_name
65
+	 * @param mixed  $value
66
+	 * @return bool
67
+	 */
68
+	public function updateOption(string $option_name, $value): bool
69
+	{
70
+		return $this->is_network_option
71
+			? update_network_option($this->network_ID, $option_name, $value)
72
+			: update_option($option_name, $value);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * @param string $option_name
78
-     * @return bool
79
-     */
80
-    public function deleteOption(string $option_name): bool
81
-    {
82
-        return $this->is_network_option
83
-            ? delete_network_option($this->network_ID, $option_name)
84
-            : delete_option($option_name);
85
-    }
76
+	/**
77
+	 * @param string $option_name
78
+	 * @return bool
79
+	 */
80
+	public function deleteOption(string $option_name): bool
81
+	{
82
+		return $this->is_network_option
83
+			? delete_network_option($this->network_ID, $option_name)
84
+			: delete_option($option_name);
85
+	}
86 86
 }
Please login to merge, or discard this patch.
core/services/database/WordPressOption.php 1 patch
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -17,181 +17,181 @@
 block discarded – undo
17 17
  */
18 18
 abstract class WordPressOption
19 19
 {
20
-    const NOT_SET_YET = 'wordpress-option-value-not-yet-set';
21
-
22
-    /**
23
-     * WordPress makes it difficult to determine if an option successfully saved or not,
24
-     * which is sometimes really important to know, especially if the information you are saving is critical.
25
-     * The following options allow us to have a better chance of knowing when an update actually failed
26
-     * or when everything is OK but it just didn't update because the value hasn't changed.
27
-     */
28
-    const UPDATE_SUCCESS = 1;
29
-
30
-    const UPDATE_NONE    = 0;
31
-
32
-    const UPDATE_ERROR   = -1;
33
-
34
-    /**
35
-     * @var boolean
36
-     */
37
-    private $autoload = false;
38
-
39
-    /**
40
-     * @var mixed
41
-     */
42
-    private $default_value = null;
43
-
44
-    /**
45
-     * @var string
46
-     */
47
-    private $option_name = '';
48
-
49
-    /**
50
-     * @var mixed
51
-     */
52
-    private $value = WordPressOption::NOT_SET_YET;
53
-
54
-    /**
55
-     * @var OptionEngine
56
-     */
57
-    private $option_engine;
58
-
59
-
60
-    /**
61
-     * WordPressOption constructor.
62
-     *
63
-     * @param string $option_name
64
-     * @param mixed  $default_value
65
-     * @param bool   $autoload              if true, will load the option on EVERY request
66
-     * @param bool   $is_network_option     if true, will save the option to the network as opposed to the current blog
67
-     */
68
-    public function __construct(
69
-        string $option_name,
70
-        $default_value,
71
-        bool $autoload = false,
72
-        bool $is_network_option = false
73
-    ) {
74
-        $this->setAutoload($autoload);
75
-        $this->setDefaultValue($default_value);
76
-        $this->setOptionName($option_name);
77
-        $this->option_engine = new OptionEngine($is_network_option);
78
-    }
79
-
80
-
81
-    /**
82
-     * @param bool|string $autoload
83
-     */
84
-    public function setAutoload($autoload): void
85
-    {
86
-        $this->autoload = filter_var($autoload, FILTER_VALIDATE_BOOLEAN);
87
-    }
88
-
89
-
90
-    /**
91
-     * @param mixed $default_value
92
-     */
93
-    public function setDefaultValue($default_value): void
94
-    {
95
-        $this->default_value = $default_value;
96
-    }
97
-
98
-
99
-    /**
100
-     * @param string $option_name
101
-     */
102
-    public function setOptionName(string $option_name): void
103
-    {
104
-        $this->option_name = sanitize_key($option_name);
105
-    }
106
-
107
-
108
-    /**
109
-     * @return string
110
-     */
111
-    public function optionExists(): string
112
-    {
113
-        return $this->option_engine->getOption(
114
-            $this->option_name,
115
-            WordPressOption::NOT_SET_YET
116
-        ) !== WordPressOption::NOT_SET_YET;
117
-    }
118
-
119
-
120
-    /**
121
-     * @return string
122
-     */
123
-    public function getOptionName(): string
124
-    {
125
-        return $this->option_name;
126
-    }
127
-
128
-
129
-    /**
130
-     * @return false|mixed|void
131
-     */
132
-    public function loadOption()
133
-    {
134
-        if ($this->value === WordPressOption::NOT_SET_YET) {
135
-            $this->value = $this->option_engine->getOption($this->option_name, $this->default_value);
136
-        }
137
-        return $this->value;
138
-    }
139
-
140
-
141
-    /**
142
-     * @param $value
143
-     * @return int
144
-     */
145
-    public function updateOption($value): int
146
-    {
147
-        // don't update if value has not changed since last update
148
-        if ($this->valueIsUnchanged($value)) {
149
-            return WordPressOption::UPDATE_NONE;
150
-        }
151
-        $this->value = $value;
152
-        // because the options for updating differ when adding an option for the first time
153
-        // we use the WordPressOption::NOT_SET_YET to determine if things already exist in the db
154
-        $updated = $this->optionExists()
155
-            ? $this->option_engine->updateOption($this->option_name, $this->value)
156
-            : $this->option_engine->addOption($this->option_name, $this->value, $this->autoload());
157
-
158
-        if ($updated) {
159
-            return WordPressOption::UPDATE_SUCCESS;
160
-        }
161
-        return WordPressOption::UPDATE_ERROR;
162
-    }
163
-
164
-
165
-    private function valueIsUnchanged($value): bool
166
-    {
167
-        if (is_array($value) && is_array($this->value)) {
168
-            $diff = EEH_Array::array_diff_recursive($value, $this->value);
169
-            // $diff = array_diff($value, $this->value);
170
-            return empty($diff);
171
-        }
172
-        // emulate WP's method for checking equality
173
-        return $value === $this->value && maybe_serialize($value) === maybe_serialize($this->value);
174
-    }
175
-
176
-
177
-    /**
178
-     * @return string
179
-     */
180
-    private function autoload(): string
181
-    {
182
-        return $this->autoload ? 'yes' : 'no';
183
-    }
184
-
185
-
186
-    /**
187
-     * Deletes the option from the database
188
-     * for the rest of the request
189
-     *
190
-     * @return bool
191
-     * @since  $VID:$
192
-     */
193
-    public function deleteOption(): bool
194
-    {
195
-        return $this->option_engine->deleteOption($this->option_name);
196
-    }
20
+	const NOT_SET_YET = 'wordpress-option-value-not-yet-set';
21
+
22
+	/**
23
+	 * WordPress makes it difficult to determine if an option successfully saved or not,
24
+	 * which is sometimes really important to know, especially if the information you are saving is critical.
25
+	 * The following options allow us to have a better chance of knowing when an update actually failed
26
+	 * or when everything is OK but it just didn't update because the value hasn't changed.
27
+	 */
28
+	const UPDATE_SUCCESS = 1;
29
+
30
+	const UPDATE_NONE    = 0;
31
+
32
+	const UPDATE_ERROR   = -1;
33
+
34
+	/**
35
+	 * @var boolean
36
+	 */
37
+	private $autoload = false;
38
+
39
+	/**
40
+	 * @var mixed
41
+	 */
42
+	private $default_value = null;
43
+
44
+	/**
45
+	 * @var string
46
+	 */
47
+	private $option_name = '';
48
+
49
+	/**
50
+	 * @var mixed
51
+	 */
52
+	private $value = WordPressOption::NOT_SET_YET;
53
+
54
+	/**
55
+	 * @var OptionEngine
56
+	 */
57
+	private $option_engine;
58
+
59
+
60
+	/**
61
+	 * WordPressOption constructor.
62
+	 *
63
+	 * @param string $option_name
64
+	 * @param mixed  $default_value
65
+	 * @param bool   $autoload              if true, will load the option on EVERY request
66
+	 * @param bool   $is_network_option     if true, will save the option to the network as opposed to the current blog
67
+	 */
68
+	public function __construct(
69
+		string $option_name,
70
+		$default_value,
71
+		bool $autoload = false,
72
+		bool $is_network_option = false
73
+	) {
74
+		$this->setAutoload($autoload);
75
+		$this->setDefaultValue($default_value);
76
+		$this->setOptionName($option_name);
77
+		$this->option_engine = new OptionEngine($is_network_option);
78
+	}
79
+
80
+
81
+	/**
82
+	 * @param bool|string $autoload
83
+	 */
84
+	public function setAutoload($autoload): void
85
+	{
86
+		$this->autoload = filter_var($autoload, FILTER_VALIDATE_BOOLEAN);
87
+	}
88
+
89
+
90
+	/**
91
+	 * @param mixed $default_value
92
+	 */
93
+	public function setDefaultValue($default_value): void
94
+	{
95
+		$this->default_value = $default_value;
96
+	}
97
+
98
+
99
+	/**
100
+	 * @param string $option_name
101
+	 */
102
+	public function setOptionName(string $option_name): void
103
+	{
104
+		$this->option_name = sanitize_key($option_name);
105
+	}
106
+
107
+
108
+	/**
109
+	 * @return string
110
+	 */
111
+	public function optionExists(): string
112
+	{
113
+		return $this->option_engine->getOption(
114
+			$this->option_name,
115
+			WordPressOption::NOT_SET_YET
116
+		) !== WordPressOption::NOT_SET_YET;
117
+	}
118
+
119
+
120
+	/**
121
+	 * @return string
122
+	 */
123
+	public function getOptionName(): string
124
+	{
125
+		return $this->option_name;
126
+	}
127
+
128
+
129
+	/**
130
+	 * @return false|mixed|void
131
+	 */
132
+	public function loadOption()
133
+	{
134
+		if ($this->value === WordPressOption::NOT_SET_YET) {
135
+			$this->value = $this->option_engine->getOption($this->option_name, $this->default_value);
136
+		}
137
+		return $this->value;
138
+	}
139
+
140
+
141
+	/**
142
+	 * @param $value
143
+	 * @return int
144
+	 */
145
+	public function updateOption($value): int
146
+	{
147
+		// don't update if value has not changed since last update
148
+		if ($this->valueIsUnchanged($value)) {
149
+			return WordPressOption::UPDATE_NONE;
150
+		}
151
+		$this->value = $value;
152
+		// because the options for updating differ when adding an option for the first time
153
+		// we use the WordPressOption::NOT_SET_YET to determine if things already exist in the db
154
+		$updated = $this->optionExists()
155
+			? $this->option_engine->updateOption($this->option_name, $this->value)
156
+			: $this->option_engine->addOption($this->option_name, $this->value, $this->autoload());
157
+
158
+		if ($updated) {
159
+			return WordPressOption::UPDATE_SUCCESS;
160
+		}
161
+		return WordPressOption::UPDATE_ERROR;
162
+	}
163
+
164
+
165
+	private function valueIsUnchanged($value): bool
166
+	{
167
+		if (is_array($value) && is_array($this->value)) {
168
+			$diff = EEH_Array::array_diff_recursive($value, $this->value);
169
+			// $diff = array_diff($value, $this->value);
170
+			return empty($diff);
171
+		}
172
+		// emulate WP's method for checking equality
173
+		return $value === $this->value && maybe_serialize($value) === maybe_serialize($this->value);
174
+	}
175
+
176
+
177
+	/**
178
+	 * @return string
179
+	 */
180
+	private function autoload(): string
181
+	{
182
+		return $this->autoload ? 'yes' : 'no';
183
+	}
184
+
185
+
186
+	/**
187
+	 * Deletes the option from the database
188
+	 * for the rest of the request
189
+	 *
190
+	 * @return bool
191
+	 * @since  $VID:$
192
+	 */
193
+	public function deleteOption(): bool
194
+	{
195
+		return $this->option_engine->deleteOption($this->option_name);
196
+	}
197 197
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Debug_Tools.helper.php 2 patches
Indentation   +714 added lines, -714 removed lines patch added patch discarded remove patch
@@ -14,709 +14,709 @@  discard block
 block discarded – undo
14 14
  */
15 15
 class EEH_Debug_Tools
16 16
 {
17
-    /**
18
-     *    instance of the EEH_Autoloader object
19
-     *
20
-     * @var    $_instance
21
-     * @access    private
22
-     */
23
-    private static $_instance;
24
-
25
-    /**
26
-     * @var array
27
-     */
28
-    protected $_memory_usage_points = array();
29
-
30
-
31
-
32
-    /**
33
-     * @singleton method used to instantiate class object
34
-     * @access    public
35
-     * @return EEH_Debug_Tools
36
-     */
37
-    public static function instance()
38
-    {
39
-        // check if class object is instantiated, and instantiated properly
40
-        if (! self::$_instance instanceof EEH_Debug_Tools) {
41
-            self::$_instance = new self();
42
-        }
43
-        return self::$_instance;
44
-    }
45
-
46
-
47
-
48
-    /**
49
-     * private class constructor
50
-     */
51
-    private function __construct()
52
-    {
53
-        // load Kint PHP debugging library
54
-        if (
55
-            defined('EE_LOAD_KINT')
56
-            && ! class_exists('Kint')
57
-            && file_exists(EE_PLUGIN_DIR_PATH . 'tests/kint/Kint.class.php')
58
-        ) {
59
-            // despite EE4 having a check for an existing copy of the Kint debugging class,
60
-            // if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
61
-            // then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
62
-            // so we've moved it to our test folder so that it is not included with production releases
63
-            // plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
64
-            require_once(EE_PLUGIN_DIR_PATH . 'tests/kint/Kint.class.php');
65
-        }
66
-        $plugin = basename(EE_PLUGIN_DIR_PATH);
67
-        add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
68
-        add_action('activated_plugin', array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
69
-        add_action('shutdown', array('EEH_Debug_Tools', 'show_db_name'));
70
-    }
71
-
72
-
73
-
74
-    /**
75
-     *    show_db_name
76
-     *
77
-     * @return void
78
-     */
79
-    public static function show_db_name()
80
-    {
81
-        if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
82
-            echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
83
-                 . DB_NAME
84
-                 . '</p>';
85
-        }
86
-        if (EE_DEBUG) {
87
-            Benchmark::displayResults();
88
-        }
89
-    }
90
-
91
-
92
-
93
-    /**
94
-     *    dump EE_Session object at bottom of page after everything else has happened
95
-     *
96
-     * @return void
97
-     */
98
-    public function espresso_session_footer_dump()
99
-    {
100
-        if (
101
-            (defined('WP_DEBUG') && WP_DEBUG)
102
-            && ! defined('DOING_AJAX')
103
-            && class_exists('Kint')
104
-            && function_exists('wp_get_current_user')
105
-            && current_user_can('update_core')
106
-            && class_exists('EE_Registry')
107
-        ) {
108
-            Kint::dump(EE_Registry::instance()->SSN->id());
109
-            Kint::dump(EE_Registry::instance()->SSN);
110
-            //          Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
111
-            $this->espresso_list_hooked_functions();
112
-            Benchmark::displayResults();
113
-        }
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     *    List All Hooked Functions
120
-     *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
121
-     *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
122
-     *
123
-     * @param string $tag
124
-     * @return void
125
-     */
126
-    public function espresso_list_hooked_functions($tag = '')
127
-    {
128
-        global $wp_filter;
129
-        echo '<br/><br/><br/><h3>Hooked Functions</h3>';
130
-        if ($tag) {
131
-            $hook[ $tag ] = $wp_filter[ $tag ];
132
-            if (! is_array($hook[ $tag ])) {
133
-                trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
134
-                return;
135
-            }
136
-            echo '<h5>For Tag: ' . esc_html($tag) . '</h5>';
137
-        } else {
138
-            $hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
139
-            ksort($hook);
140
-        }
141
-        foreach ($hook as $tag_name => $priorities) {
142
-            echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>esc_html($tag_name)</strong><br />";
143
-            ksort($priorities);
144
-            foreach ($priorities as $priority => $function) {
145
-                echo esc_html($priority);
146
-                foreach ($function as $name => $properties) {
147
-                    $name = esc_html($name);
148
-                    echo "\t$name<br />";
149
-                }
150
-            }
151
-        }
152
-    }
153
-
154
-
155
-
156
-    /**
157
-     *    registered_filter_callbacks
158
-     *
159
-     * @param string $hook_name
160
-     * @return array
161
-     */
162
-    public static function registered_filter_callbacks($hook_name = '')
163
-    {
164
-        $filters = array();
165
-        global $wp_filter;
166
-        if (isset($wp_filter[ $hook_name ])) {
167
-            $filters[ $hook_name ] = array();
168
-            foreach ($wp_filter[ $hook_name ] as $priority => $callbacks) {
169
-                $filters[ $hook_name ][ $priority ] = array();
170
-                foreach ($callbacks as $callback) {
171
-                    $filters[ $hook_name ][ $priority ][] = $callback['function'];
172
-                }
173
-            }
174
-        }
175
-        return $filters;
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     *    captures plugin activation errors for debugging
182
-     *
183
-     * @return void
184
-     * @throws EE_Error
185
-     */
186
-    public static function ee_plugin_activation_errors()
187
-    {
188
-        if (WP_DEBUG) {
189
-            $activation_errors = ob_get_contents();
190
-            if (empty($activation_errors)) {
191
-                return;
192
-            }
193
-            $activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
194
-            espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
195
-            if (class_exists('EEH_File')) {
196
-                try {
197
-                    EEH_File::ensure_file_exists_and_is_writable(
198
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html'
199
-                    );
200
-                    EEH_File::write_to_file(
201
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html',
202
-                        $activation_errors
203
-                    );
204
-                } catch (EE_Error $e) {
205
-                    EE_Error::add_error(
206
-                        sprintf(
207
-                            esc_html__(
208
-                                'The Event Espresso activation errors file could not be setup because: %s',
209
-                                'event_espresso'
210
-                            ),
211
-                            $e->getMessage()
212
-                        ),
213
-                        __FILE__,
214
-                        __FUNCTION__,
215
-                        __LINE__
216
-                    );
217
-                }
218
-            } else {
219
-                // old school attempt
220
-                file_put_contents(
221
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html',
222
-                    $activation_errors
223
-                );
224
-            }
225
-            $activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
226
-            update_option('ee_plugin_activation_errors', $activation_errors);
227
-        }
228
-    }
229
-
230
-
231
-
232
-    /**
233
-     * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.
234
-     * Very useful for providing helpful messages to developers when the method of doing something has been deprecated,
235
-     * or we want to make sure they use something the right way.
236
-     *
237
-     * @access public
238
-     * @param string $function      The function that was called
239
-     * @param string $message       A message explaining what has been done incorrectly
240
-     * @param string $version       The version of Event Espresso where the error was added
241
-     * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
242
-     *                              for a deprecated function. This allows deprecation to occur during one version,
243
-     *                              but not have any notices appear until a later version. This allows developers
244
-     *                              extra time to update their code before notices appear.
245
-     * @param int    $error_type
246
-     * @uses   trigger_error()
247
-     */
248
-    public function doing_it_wrong(
249
-        $function,
250
-        $message,
251
-        $version,
252
-        $applies_when = '',
253
-        $error_type = null
254
-    ) {
255
-        $applies_when = ! empty($applies_when) ? $applies_when : espresso_version();
256
-        $error_type = $error_type !== null ? $error_type : E_USER_NOTICE;
257
-        // because we swapped the parameter order around for the last two params,
258
-        // let's verify that some third party isn't still passing an error type value for the third param
259
-        if (is_int($applies_when)) {
260
-            $error_type = $applies_when;
261
-            $applies_when = espresso_version();
262
-        }
263
-        // if not displaying notices yet, then just leave
264
-        if (version_compare(espresso_version(), $applies_when, '<')) {
265
-            return;
266
-        }
267
-        do_action('AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
268
-        $version = $version === null
269
-            ? ''
270
-            : sprintf(
271
-                esc_html__('(This message was added in version %s of Event Espresso)', 'event_espresso'),
272
-                $version
273
-            );
274
-        $error_message = sprintf(
275
-            esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s', 'event_espresso'),
276
-            $function,
277
-            '<strong>',
278
-            '</strong>',
279
-            $message,
280
-            $version
281
-        );
282
-        // don't trigger error if doing ajax,
283
-        // instead we'll add a transient EE_Error notice that in theory should show on the next request.
284
-        if (defined('DOING_AJAX') && DOING_AJAX) {
285
-            $error_message .= ' ' . esc_html__(
286
-                'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
287
-                'event_espresso'
288
-            );
289
-            $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
290
-            $error_message .= '<ul><li>';
291
-            $error_message .= implode('</li><li>', $request->requestParams());
292
-            $error_message .= '</ul>';
293
-            EE_Error::add_error($error_message, 'debug::doing_it_wrong', $function, '42');
294
-            // now we set this on the transient so it shows up on the next request.
295
-            EE_Error::get_notices(false, true);
296
-        } else {
297
-            trigger_error($error_message, $error_type);
298
-        }
299
-    }
300
-
301
-
302
-
303
-
304
-    /**
305
-     * Logger helpers
306
-     */
307
-    /**
308
-     * debug
309
-     *
310
-     * @param string $class
311
-     * @param string $func
312
-     * @param string $line
313
-     * @param array  $info
314
-     * @param bool   $display_request
315
-     * @param string $debug_index
316
-     * @param string $debug_key
317
-     */
318
-    public static function log(
319
-        $class = '',
320
-        $func = '',
321
-        $line = '',
322
-        $info = array(),
323
-        $display_request = false,
324
-        $debug_index = '',
325
-        $debug_key = 'EE_DEBUG_SPCO'
326
-    ) {
327
-        if (WP_DEBUG) {
328
-            $debug_key = $debug_key . '_' . EE_Session::instance()->id();
329
-            $debug_data = get_option($debug_key, array());
330
-            $default_data = array(
331
-                $class => $func . '() : ' . $line,
332
-            );
333
-            // don't serialize objects
334
-            $info = self::strip_objects($info);
335
-            $index = ! empty($debug_index) ? $debug_index : 0;
336
-            if (! isset($debug_data[ $index ])) {
337
-                $debug_data[ $index ] = array();
338
-            }
339
-            $debug_data[ $index ][ microtime() ] = array_merge($default_data, $info);
340
-            update_option($debug_key, $debug_data);
341
-        }
342
-    }
343
-
344
-
345
-
346
-    /**
347
-     * strip_objects
348
-     *
349
-     * @param array $info
350
-     * @return array
351
-     */
352
-    public static function strip_objects($info = array())
353
-    {
354
-        foreach ($info as $key => $value) {
355
-            if (is_array($value)) {
356
-                $info[ $key ] = self::strip_objects($value);
357
-            } elseif (is_object($value)) {
358
-                $object_class = get_class($value);
359
-                $info[ $object_class ] = array();
360
-                $info[ $object_class ]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361
-                if (method_exists($value, 'ID')) {
362
-                    $info[ $object_class ]['ID'] = $value->ID();
363
-                }
364
-                if (method_exists($value, 'status')) {
365
-                    $info[ $object_class ]['status'] = $value->status();
366
-                } elseif (method_exists($value, 'status_ID')) {
367
-                    $info[ $object_class ]['status'] = $value->status_ID();
368
-                }
369
-                unset($info[ $key ]);
370
-            }
371
-        }
372
-        return (array) $info;
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * @param mixed      $var
379
-     * @param string     $var_name
380
-     * @param string     $file
381
-     * @param int|string $line
382
-     * @param int|string $heading_tag
383
-     * @param bool       $die
384
-     * @param string     $margin
385
-     */
386
-    public static function printv(
387
-        $var,
388
-        $var_name = '',
389
-        $file = '',
390
-        $line = '',
391
-        $heading_tag = 5,
392
-        $die = false,
393
-        $margin = ''
394
-    ) {
395
-        $var_name = ! $var_name ? 'string' : $var_name;
396
-        $var_name = ucwords(str_replace('$', '', $var_name));
397
-        $is_method = method_exists($var_name, $var);
398
-        $var_name = ucwords(str_replace('_', ' ', $var_name));
399
-        $heading_tag = EEH_Debug_Tools::headingTag($heading_tag);
400
-        // $result = EEH_Debug_Tools::headingSpacer($heading_tag);
401
-        $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin, $line);
402
-        $result .= $is_method
403
-            ? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
404
-            : EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
405
-        $result .= EEH_Debug_Tools::file_and_line($file, $line, $heading_tag);
406
-        $result .= EEH_Debug_Tools::headingX($heading_tag);
407
-        if ($die) {
408
-            die($result);
409
-        }
410
-        echo $result;
411
-    }
412
-
413
-
414
-    protected static function headingTag($heading_tag)
415
-    {
416
-        $heading_tag = absint($heading_tag);
417
-        return $heading_tag > 0 && $heading_tag < 7 ? "h{$heading_tag}" : 'h5';
418
-    }
419
-
420
-    protected static function headingSpacer($heading_tag)
421
-    {
422
-        return EEH_Debug_Tools::plainOutput() && ($heading_tag === 'h1' || $heading_tag === 'h2')
423
-            ? self::lineBreak()
424
-            : '';
425
-    }
426
-
427
-
428
-    protected static function plainOutput()
429
-    {
430
-        return defined('EE_TESTS_DIR')
431
-               || (defined('DOING_AJAX') && DOING_AJAX && ! isset($_REQUEST['pretty_output']))
432
-               || (
433
-                   isset($_SERVER['REQUEST_URI'])
434
-                   && strpos(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 'wp-json') !== false
435
-               );
436
-    }
437
-
438
-
439
-    /**
440
-     * @param string $var_name
441
-     * @param string $heading_tag
442
-     * @param string $margin
443
-     * @param int    $line
444
-     * @return string
445
-     */
446
-    protected static function heading($var_name = '', $heading_tag = 'h5', $margin = '', $line = 0)
447
-    {
448
-        if (EEH_Debug_Tools::plainOutput()) {
449
-            switch ($heading_tag) {
450
-                case 'h1':
451
-                    $line_breaks = EEH_Debug_Tools::lineBreak(3);
452
-                    break;
453
-                case 'h2':
454
-                    $line_breaks = EEH_Debug_Tools::lineBreak(2);
455
-                    break;
456
-                default:
457
-                    $line_breaks = EEH_Debug_Tools::lineBreak();
458
-                    break;
459
-            }
460
-            return "{$line_breaks}{$line}) {$var_name}";
461
-        }
462
-        $margin = "25px 0 0 {$margin}";
463
-        return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
464
-    }
465
-
466
-
467
-
468
-    /**
469
-     * @param string $heading_tag
470
-     * @return string
471
-     */
472
-    protected static function headingX($heading_tag = 'h5')
473
-    {
474
-        if (EEH_Debug_Tools::plainOutput()) {
475
-            return '';
476
-        }
477
-        return '</' . $heading_tag . '>';
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * @param string $content
484
-     * @return string
485
-     */
486
-    protected static function grey_span($content = '')
487
-    {
488
-        if (EEH_Debug_Tools::plainOutput()) {
489
-            return $content;
490
-        }
491
-        return '<span style="color:#999">' . $content . '</span>';
492
-    }
493
-
494
-
495
-
496
-    /**
497
-     * @param string $file
498
-     * @param int    $line
499
-     * @return string
500
-     */
501
-    protected static function file_and_line($file, $line, $heading_tag)
502
-    {
503
-        if ($file === '' || $line === '') {
504
-            return '';
505
-        }
506
-        $file = str_replace(EE_PLUGIN_DIR_PATH, '/', $file);
507
-        if (EEH_Debug_Tools::plainOutput()) {
508
-            if ($heading_tag === 'h1' || $heading_tag === 'h2') {
509
-                return " ({$file})" . EEH_Debug_Tools::lineBreak();
510
-            }
511
-            return '';
512
-        }
513
-        return EEH_Debug_Tools::lineBreak()
514
-               . '<span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
515
-               . $file
516
-               . EEH_Debug_Tools::lineBreak()
517
-               . 'line no: '
518
-               . $line
519
-               . '</span>';
520
-    }
521
-
522
-
523
-
524
-    /**
525
-     * @param string $content
526
-     * @return string
527
-     */
528
-    protected static function orange_span($content = '')
529
-    {
530
-        if (EEH_Debug_Tools::plainOutput()) {
531
-            return $content;
532
-        }
533
-        return '<span style="color:#E76700">' . $content . '</span>';
534
-    }
535
-
536
-
537
-
538
-    /**
539
-     * @param mixed $var
540
-     * @return string
541
-     */
542
-    protected static function pre_span($var)
543
-    {
544
-        ob_start();
545
-        var_dump($var);
546
-        $var = ob_get_clean();
547
-        if (EEH_Debug_Tools::plainOutput()) {
548
-            return str_replace("\n", '', $var);
549
-        }
550
-        return '<pre style="color: #9C3; display: inline-block; padding:.4em .6em; background: #334">' . $var . '</pre>';
551
-    }
552
-
553
-
554
-
555
-    /**
556
-     * @param mixed      $var
557
-     * @param string     $var_name
558
-     * @param string     $file
559
-     * @param int|string $line
560
-     * @param int|string $heading_tag
561
-     * @param bool       $die
562
-     */
563
-    public static function printr(
564
-        $var,
565
-        $var_name = '',
566
-        $file = '',
567
-        $line = '',
568
-        $heading_tag = 5,
569
-        $die = false
570
-    ) {
571
-        // return;
572
-        $file = str_replace(rtrim(ABSPATH, '\\/'), '', $file);
573
-        if (empty($var) && empty($var_name)) {
574
-            $var = $file;
575
-            $var_name = "line $line";
576
-            $file = '';
577
-            $line = '';
578
-        }
579
-        $margin = is_admin() ? ' 180px' : '0';
580
-        if (is_string($var)) {
581
-            EEH_Debug_Tools::printv($var, $var_name, $file, $line, $heading_tag, $die, $margin);
582
-            return;
583
-        }
584
-        if (is_object($var)) {
585
-            $var_name = ! $var_name ? 'object' : $var_name;
586
-        } elseif (is_array($var)) {
587
-            $var_name = ! $var_name ? 'array' : $var_name;
588
-        } elseif (is_numeric($var)) {
589
-            $var_name = ! $var_name ? 'numeric' : $var_name;
590
-        } elseif ($var === null) {
591
-            $var_name = ! $var_name ? 'null' : $var_name;
592
-        }
593
-        $var_name = EEH_Debug_Tools::trimVarName($var_name);
594
-        $heading_tag = EEH_Debug_Tools::headingTag($heading_tag);
595
-        // $result = EEH_Debug_Tools::headingSpacer($heading_tag);
596
-        $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin, $line);
597
-        $result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
598
-            EEH_Debug_Tools::pre_span($var)
599
-        );
600
-        $result .= EEH_Debug_Tools::file_and_line($file, $line, $heading_tag);
601
-        $result .= EEH_Debug_Tools::headingX($heading_tag);
602
-        if ($die) {
603
-            die($result);
604
-        }
605
-        echo $result;
606
-    }
607
-
608
-
609
-    private static function trimVarName($var_name): string
610
-    {
611
-        $converted = str_replace(['$', '_', 'this->'], ['', ' ', ''], $var_name);
612
-        $words = explode(' ', $converted);
613
-        $words = array_map(
614
-            function ($word) {
615
-                return $word === 'id' || $word === 'Id' ? 'ID' : $word;
616
-            },
617
-            $words
618
-        );
619
-        return ucwords(implode(' ', $words));
620
-    }
621
-
622
-
623
-    private static function lineBreak($lines = 1): string
624
-    {
625
-        $linebreak = defined('DOING_AJAX') && DOING_AJAX ? '<br />' : PHP_EOL;
626
-        return str_repeat($linebreak, $lines);
627
-    }
628
-
629
-
630
-    public static function shortClassName(string $fqcn): string
631
-    {
632
-        return substr(strrchr($fqcn, '\\'), 1);
633
-    }
634
-
635
-
636
-
637
-    /******************** deprecated ********************/
638
-
639
-
640
-
641
-    /**
642
-     * @deprecated 4.9.39.rc.034
643
-     */
644
-    public function reset_times()
645
-    {
646
-        Benchmark::resetTimes();
647
-    }
648
-
649
-
650
-
651
-    /**
652
-     * @deprecated 4.9.39.rc.034
653
-     * @param null $timer_name
654
-     */
655
-    public function start_timer($timer_name = null)
656
-    {
657
-        Benchmark::startTimer($timer_name);
658
-    }
659
-
660
-
661
-
662
-    /**
663
-     * @deprecated 4.9.39.rc.034
664
-     * @param string $timer_name
665
-     */
666
-    public function stop_timer($timer_name = '')
667
-    {
668
-        Benchmark::stopTimer($timer_name);
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * @deprecated 4.9.39.rc.034
675
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
676
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
677
-     * @return void
678
-     */
679
-    public function measure_memory($label, $output_now = false)
680
-    {
681
-        Benchmark::measureMemory($label, $output_now);
682
-    }
683
-
684
-
685
-
686
-    /**
687
-     * @deprecated 4.9.39.rc.034
688
-     * @param int $size
689
-     * @return string
690
-     */
691
-    public function convert($size)
692
-    {
693
-        return Benchmark::convert($size);
694
-    }
695
-
696
-
17
+	/**
18
+	 *    instance of the EEH_Autoloader object
19
+	 *
20
+	 * @var    $_instance
21
+	 * @access    private
22
+	 */
23
+	private static $_instance;
24
+
25
+	/**
26
+	 * @var array
27
+	 */
28
+	protected $_memory_usage_points = array();
29
+
30
+
31
+
32
+	/**
33
+	 * @singleton method used to instantiate class object
34
+	 * @access    public
35
+	 * @return EEH_Debug_Tools
36
+	 */
37
+	public static function instance()
38
+	{
39
+		// check if class object is instantiated, and instantiated properly
40
+		if (! self::$_instance instanceof EEH_Debug_Tools) {
41
+			self::$_instance = new self();
42
+		}
43
+		return self::$_instance;
44
+	}
45
+
46
+
47
+
48
+	/**
49
+	 * private class constructor
50
+	 */
51
+	private function __construct()
52
+	{
53
+		// load Kint PHP debugging library
54
+		if (
55
+			defined('EE_LOAD_KINT')
56
+			&& ! class_exists('Kint')
57
+			&& file_exists(EE_PLUGIN_DIR_PATH . 'tests/kint/Kint.class.php')
58
+		) {
59
+			// despite EE4 having a check for an existing copy of the Kint debugging class,
60
+			// if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
61
+			// then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
62
+			// so we've moved it to our test folder so that it is not included with production releases
63
+			// plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
64
+			require_once(EE_PLUGIN_DIR_PATH . 'tests/kint/Kint.class.php');
65
+		}
66
+		$plugin = basename(EE_PLUGIN_DIR_PATH);
67
+		add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
68
+		add_action('activated_plugin', array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
69
+		add_action('shutdown', array('EEH_Debug_Tools', 'show_db_name'));
70
+	}
71
+
72
+
73
+
74
+	/**
75
+	 *    show_db_name
76
+	 *
77
+	 * @return void
78
+	 */
79
+	public static function show_db_name()
80
+	{
81
+		if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
82
+			echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
83
+				 . DB_NAME
84
+				 . '</p>';
85
+		}
86
+		if (EE_DEBUG) {
87
+			Benchmark::displayResults();
88
+		}
89
+	}
90
+
91
+
92
+
93
+	/**
94
+	 *    dump EE_Session object at bottom of page after everything else has happened
95
+	 *
96
+	 * @return void
97
+	 */
98
+	public function espresso_session_footer_dump()
99
+	{
100
+		if (
101
+			(defined('WP_DEBUG') && WP_DEBUG)
102
+			&& ! defined('DOING_AJAX')
103
+			&& class_exists('Kint')
104
+			&& function_exists('wp_get_current_user')
105
+			&& current_user_can('update_core')
106
+			&& class_exists('EE_Registry')
107
+		) {
108
+			Kint::dump(EE_Registry::instance()->SSN->id());
109
+			Kint::dump(EE_Registry::instance()->SSN);
110
+			//          Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
111
+			$this->espresso_list_hooked_functions();
112
+			Benchmark::displayResults();
113
+		}
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 *    List All Hooked Functions
120
+	 *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
121
+	 *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
122
+	 *
123
+	 * @param string $tag
124
+	 * @return void
125
+	 */
126
+	public function espresso_list_hooked_functions($tag = '')
127
+	{
128
+		global $wp_filter;
129
+		echo '<br/><br/><br/><h3>Hooked Functions</h3>';
130
+		if ($tag) {
131
+			$hook[ $tag ] = $wp_filter[ $tag ];
132
+			if (! is_array($hook[ $tag ])) {
133
+				trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
134
+				return;
135
+			}
136
+			echo '<h5>For Tag: ' . esc_html($tag) . '</h5>';
137
+		} else {
138
+			$hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
139
+			ksort($hook);
140
+		}
141
+		foreach ($hook as $tag_name => $priorities) {
142
+			echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>esc_html($tag_name)</strong><br />";
143
+			ksort($priorities);
144
+			foreach ($priorities as $priority => $function) {
145
+				echo esc_html($priority);
146
+				foreach ($function as $name => $properties) {
147
+					$name = esc_html($name);
148
+					echo "\t$name<br />";
149
+				}
150
+			}
151
+		}
152
+	}
153
+
154
+
155
+
156
+	/**
157
+	 *    registered_filter_callbacks
158
+	 *
159
+	 * @param string $hook_name
160
+	 * @return array
161
+	 */
162
+	public static function registered_filter_callbacks($hook_name = '')
163
+	{
164
+		$filters = array();
165
+		global $wp_filter;
166
+		if (isset($wp_filter[ $hook_name ])) {
167
+			$filters[ $hook_name ] = array();
168
+			foreach ($wp_filter[ $hook_name ] as $priority => $callbacks) {
169
+				$filters[ $hook_name ][ $priority ] = array();
170
+				foreach ($callbacks as $callback) {
171
+					$filters[ $hook_name ][ $priority ][] = $callback['function'];
172
+				}
173
+			}
174
+		}
175
+		return $filters;
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 *    captures plugin activation errors for debugging
182
+	 *
183
+	 * @return void
184
+	 * @throws EE_Error
185
+	 */
186
+	public static function ee_plugin_activation_errors()
187
+	{
188
+		if (WP_DEBUG) {
189
+			$activation_errors = ob_get_contents();
190
+			if (empty($activation_errors)) {
191
+				return;
192
+			}
193
+			$activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
194
+			espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
195
+			if (class_exists('EEH_File')) {
196
+				try {
197
+					EEH_File::ensure_file_exists_and_is_writable(
198
+						EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html'
199
+					);
200
+					EEH_File::write_to_file(
201
+						EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html',
202
+						$activation_errors
203
+					);
204
+				} catch (EE_Error $e) {
205
+					EE_Error::add_error(
206
+						sprintf(
207
+							esc_html__(
208
+								'The Event Espresso activation errors file could not be setup because: %s',
209
+								'event_espresso'
210
+							),
211
+							$e->getMessage()
212
+						),
213
+						__FILE__,
214
+						__FUNCTION__,
215
+						__LINE__
216
+					);
217
+				}
218
+			} else {
219
+				// old school attempt
220
+				file_put_contents(
221
+					EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html',
222
+					$activation_errors
223
+				);
224
+			}
225
+			$activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
226
+			update_option('ee_plugin_activation_errors', $activation_errors);
227
+		}
228
+	}
229
+
230
+
231
+
232
+	/**
233
+	 * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.
234
+	 * Very useful for providing helpful messages to developers when the method of doing something has been deprecated,
235
+	 * or we want to make sure they use something the right way.
236
+	 *
237
+	 * @access public
238
+	 * @param string $function      The function that was called
239
+	 * @param string $message       A message explaining what has been done incorrectly
240
+	 * @param string $version       The version of Event Espresso where the error was added
241
+	 * @param string $applies_when  a version string for when you want the doing_it_wrong notice to begin appearing
242
+	 *                              for a deprecated function. This allows deprecation to occur during one version,
243
+	 *                              but not have any notices appear until a later version. This allows developers
244
+	 *                              extra time to update their code before notices appear.
245
+	 * @param int    $error_type
246
+	 * @uses   trigger_error()
247
+	 */
248
+	public function doing_it_wrong(
249
+		$function,
250
+		$message,
251
+		$version,
252
+		$applies_when = '',
253
+		$error_type = null
254
+	) {
255
+		$applies_when = ! empty($applies_when) ? $applies_when : espresso_version();
256
+		$error_type = $error_type !== null ? $error_type : E_USER_NOTICE;
257
+		// because we swapped the parameter order around for the last two params,
258
+		// let's verify that some third party isn't still passing an error type value for the third param
259
+		if (is_int($applies_when)) {
260
+			$error_type = $applies_when;
261
+			$applies_when = espresso_version();
262
+		}
263
+		// if not displaying notices yet, then just leave
264
+		if (version_compare(espresso_version(), $applies_when, '<')) {
265
+			return;
266
+		}
267
+		do_action('AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
268
+		$version = $version === null
269
+			? ''
270
+			: sprintf(
271
+				esc_html__('(This message was added in version %s of Event Espresso)', 'event_espresso'),
272
+				$version
273
+			);
274
+		$error_message = sprintf(
275
+			esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s', 'event_espresso'),
276
+			$function,
277
+			'<strong>',
278
+			'</strong>',
279
+			$message,
280
+			$version
281
+		);
282
+		// don't trigger error if doing ajax,
283
+		// instead we'll add a transient EE_Error notice that in theory should show on the next request.
284
+		if (defined('DOING_AJAX') && DOING_AJAX) {
285
+			$error_message .= ' ' . esc_html__(
286
+				'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
287
+				'event_espresso'
288
+			);
289
+			$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
290
+			$error_message .= '<ul><li>';
291
+			$error_message .= implode('</li><li>', $request->requestParams());
292
+			$error_message .= '</ul>';
293
+			EE_Error::add_error($error_message, 'debug::doing_it_wrong', $function, '42');
294
+			// now we set this on the transient so it shows up on the next request.
295
+			EE_Error::get_notices(false, true);
296
+		} else {
297
+			trigger_error($error_message, $error_type);
298
+		}
299
+	}
300
+
301
+
302
+
303
+
304
+	/**
305
+	 * Logger helpers
306
+	 */
307
+	/**
308
+	 * debug
309
+	 *
310
+	 * @param string $class
311
+	 * @param string $func
312
+	 * @param string $line
313
+	 * @param array  $info
314
+	 * @param bool   $display_request
315
+	 * @param string $debug_index
316
+	 * @param string $debug_key
317
+	 */
318
+	public static function log(
319
+		$class = '',
320
+		$func = '',
321
+		$line = '',
322
+		$info = array(),
323
+		$display_request = false,
324
+		$debug_index = '',
325
+		$debug_key = 'EE_DEBUG_SPCO'
326
+	) {
327
+		if (WP_DEBUG) {
328
+			$debug_key = $debug_key . '_' . EE_Session::instance()->id();
329
+			$debug_data = get_option($debug_key, array());
330
+			$default_data = array(
331
+				$class => $func . '() : ' . $line,
332
+			);
333
+			// don't serialize objects
334
+			$info = self::strip_objects($info);
335
+			$index = ! empty($debug_index) ? $debug_index : 0;
336
+			if (! isset($debug_data[ $index ])) {
337
+				$debug_data[ $index ] = array();
338
+			}
339
+			$debug_data[ $index ][ microtime() ] = array_merge($default_data, $info);
340
+			update_option($debug_key, $debug_data);
341
+		}
342
+	}
343
+
344
+
345
+
346
+	/**
347
+	 * strip_objects
348
+	 *
349
+	 * @param array $info
350
+	 * @return array
351
+	 */
352
+	public static function strip_objects($info = array())
353
+	{
354
+		foreach ($info as $key => $value) {
355
+			if (is_array($value)) {
356
+				$info[ $key ] = self::strip_objects($value);
357
+			} elseif (is_object($value)) {
358
+				$object_class = get_class($value);
359
+				$info[ $object_class ] = array();
360
+				$info[ $object_class ]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361
+				if (method_exists($value, 'ID')) {
362
+					$info[ $object_class ]['ID'] = $value->ID();
363
+				}
364
+				if (method_exists($value, 'status')) {
365
+					$info[ $object_class ]['status'] = $value->status();
366
+				} elseif (method_exists($value, 'status_ID')) {
367
+					$info[ $object_class ]['status'] = $value->status_ID();
368
+				}
369
+				unset($info[ $key ]);
370
+			}
371
+		}
372
+		return (array) $info;
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * @param mixed      $var
379
+	 * @param string     $var_name
380
+	 * @param string     $file
381
+	 * @param int|string $line
382
+	 * @param int|string $heading_tag
383
+	 * @param bool       $die
384
+	 * @param string     $margin
385
+	 */
386
+	public static function printv(
387
+		$var,
388
+		$var_name = '',
389
+		$file = '',
390
+		$line = '',
391
+		$heading_tag = 5,
392
+		$die = false,
393
+		$margin = ''
394
+	) {
395
+		$var_name = ! $var_name ? 'string' : $var_name;
396
+		$var_name = ucwords(str_replace('$', '', $var_name));
397
+		$is_method = method_exists($var_name, $var);
398
+		$var_name = ucwords(str_replace('_', ' ', $var_name));
399
+		$heading_tag = EEH_Debug_Tools::headingTag($heading_tag);
400
+		// $result = EEH_Debug_Tools::headingSpacer($heading_tag);
401
+		$result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin, $line);
402
+		$result .= $is_method
403
+			? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
404
+			: EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
405
+		$result .= EEH_Debug_Tools::file_and_line($file, $line, $heading_tag);
406
+		$result .= EEH_Debug_Tools::headingX($heading_tag);
407
+		if ($die) {
408
+			die($result);
409
+		}
410
+		echo $result;
411
+	}
412
+
413
+
414
+	protected static function headingTag($heading_tag)
415
+	{
416
+		$heading_tag = absint($heading_tag);
417
+		return $heading_tag > 0 && $heading_tag < 7 ? "h{$heading_tag}" : 'h5';
418
+	}
419
+
420
+	protected static function headingSpacer($heading_tag)
421
+	{
422
+		return EEH_Debug_Tools::plainOutput() && ($heading_tag === 'h1' || $heading_tag === 'h2')
423
+			? self::lineBreak()
424
+			: '';
425
+	}
426
+
427
+
428
+	protected static function plainOutput()
429
+	{
430
+		return defined('EE_TESTS_DIR')
431
+			   || (defined('DOING_AJAX') && DOING_AJAX && ! isset($_REQUEST['pretty_output']))
432
+			   || (
433
+				   isset($_SERVER['REQUEST_URI'])
434
+				   && strpos(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 'wp-json') !== false
435
+			   );
436
+	}
437
+
438
+
439
+	/**
440
+	 * @param string $var_name
441
+	 * @param string $heading_tag
442
+	 * @param string $margin
443
+	 * @param int    $line
444
+	 * @return string
445
+	 */
446
+	protected static function heading($var_name = '', $heading_tag = 'h5', $margin = '', $line = 0)
447
+	{
448
+		if (EEH_Debug_Tools::plainOutput()) {
449
+			switch ($heading_tag) {
450
+				case 'h1':
451
+					$line_breaks = EEH_Debug_Tools::lineBreak(3);
452
+					break;
453
+				case 'h2':
454
+					$line_breaks = EEH_Debug_Tools::lineBreak(2);
455
+					break;
456
+				default:
457
+					$line_breaks = EEH_Debug_Tools::lineBreak();
458
+					break;
459
+			}
460
+			return "{$line_breaks}{$line}) {$var_name}";
461
+		}
462
+		$margin = "25px 0 0 {$margin}";
463
+		return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
464
+	}
465
+
466
+
467
+
468
+	/**
469
+	 * @param string $heading_tag
470
+	 * @return string
471
+	 */
472
+	protected static function headingX($heading_tag = 'h5')
473
+	{
474
+		if (EEH_Debug_Tools::plainOutput()) {
475
+			return '';
476
+		}
477
+		return '</' . $heading_tag . '>';
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * @param string $content
484
+	 * @return string
485
+	 */
486
+	protected static function grey_span($content = '')
487
+	{
488
+		if (EEH_Debug_Tools::plainOutput()) {
489
+			return $content;
490
+		}
491
+		return '<span style="color:#999">' . $content . '</span>';
492
+	}
493
+
494
+
495
+
496
+	/**
497
+	 * @param string $file
498
+	 * @param int    $line
499
+	 * @return string
500
+	 */
501
+	protected static function file_and_line($file, $line, $heading_tag)
502
+	{
503
+		if ($file === '' || $line === '') {
504
+			return '';
505
+		}
506
+		$file = str_replace(EE_PLUGIN_DIR_PATH, '/', $file);
507
+		if (EEH_Debug_Tools::plainOutput()) {
508
+			if ($heading_tag === 'h1' || $heading_tag === 'h2') {
509
+				return " ({$file})" . EEH_Debug_Tools::lineBreak();
510
+			}
511
+			return '';
512
+		}
513
+		return EEH_Debug_Tools::lineBreak()
514
+			   . '<span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">'
515
+			   . $file
516
+			   . EEH_Debug_Tools::lineBreak()
517
+			   . 'line no: '
518
+			   . $line
519
+			   . '</span>';
520
+	}
521
+
522
+
523
+
524
+	/**
525
+	 * @param string $content
526
+	 * @return string
527
+	 */
528
+	protected static function orange_span($content = '')
529
+	{
530
+		if (EEH_Debug_Tools::plainOutput()) {
531
+			return $content;
532
+		}
533
+		return '<span style="color:#E76700">' . $content . '</span>';
534
+	}
535
+
536
+
537
+
538
+	/**
539
+	 * @param mixed $var
540
+	 * @return string
541
+	 */
542
+	protected static function pre_span($var)
543
+	{
544
+		ob_start();
545
+		var_dump($var);
546
+		$var = ob_get_clean();
547
+		if (EEH_Debug_Tools::plainOutput()) {
548
+			return str_replace("\n", '', $var);
549
+		}
550
+		return '<pre style="color: #9C3; display: inline-block; padding:.4em .6em; background: #334">' . $var . '</pre>';
551
+	}
552
+
553
+
554
+
555
+	/**
556
+	 * @param mixed      $var
557
+	 * @param string     $var_name
558
+	 * @param string     $file
559
+	 * @param int|string $line
560
+	 * @param int|string $heading_tag
561
+	 * @param bool       $die
562
+	 */
563
+	public static function printr(
564
+		$var,
565
+		$var_name = '',
566
+		$file = '',
567
+		$line = '',
568
+		$heading_tag = 5,
569
+		$die = false
570
+	) {
571
+		// return;
572
+		$file = str_replace(rtrim(ABSPATH, '\\/'), '', $file);
573
+		if (empty($var) && empty($var_name)) {
574
+			$var = $file;
575
+			$var_name = "line $line";
576
+			$file = '';
577
+			$line = '';
578
+		}
579
+		$margin = is_admin() ? ' 180px' : '0';
580
+		if (is_string($var)) {
581
+			EEH_Debug_Tools::printv($var, $var_name, $file, $line, $heading_tag, $die, $margin);
582
+			return;
583
+		}
584
+		if (is_object($var)) {
585
+			$var_name = ! $var_name ? 'object' : $var_name;
586
+		} elseif (is_array($var)) {
587
+			$var_name = ! $var_name ? 'array' : $var_name;
588
+		} elseif (is_numeric($var)) {
589
+			$var_name = ! $var_name ? 'numeric' : $var_name;
590
+		} elseif ($var === null) {
591
+			$var_name = ! $var_name ? 'null' : $var_name;
592
+		}
593
+		$var_name = EEH_Debug_Tools::trimVarName($var_name);
594
+		$heading_tag = EEH_Debug_Tools::headingTag($heading_tag);
595
+		// $result = EEH_Debug_Tools::headingSpacer($heading_tag);
596
+		$result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin, $line);
597
+		$result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
598
+			EEH_Debug_Tools::pre_span($var)
599
+		);
600
+		$result .= EEH_Debug_Tools::file_and_line($file, $line, $heading_tag);
601
+		$result .= EEH_Debug_Tools::headingX($heading_tag);
602
+		if ($die) {
603
+			die($result);
604
+		}
605
+		echo $result;
606
+	}
607
+
608
+
609
+	private static function trimVarName($var_name): string
610
+	{
611
+		$converted = str_replace(['$', '_', 'this->'], ['', ' ', ''], $var_name);
612
+		$words = explode(' ', $converted);
613
+		$words = array_map(
614
+			function ($word) {
615
+				return $word === 'id' || $word === 'Id' ? 'ID' : $word;
616
+			},
617
+			$words
618
+		);
619
+		return ucwords(implode(' ', $words));
620
+	}
621
+
622
+
623
+	private static function lineBreak($lines = 1): string
624
+	{
625
+		$linebreak = defined('DOING_AJAX') && DOING_AJAX ? '<br />' : PHP_EOL;
626
+		return str_repeat($linebreak, $lines);
627
+	}
628
+
629
+
630
+	public static function shortClassName(string $fqcn): string
631
+	{
632
+		return substr(strrchr($fqcn, '\\'), 1);
633
+	}
634
+
635
+
636
+
637
+	/******************** deprecated ********************/
638
+
639
+
640
+
641
+	/**
642
+	 * @deprecated 4.9.39.rc.034
643
+	 */
644
+	public function reset_times()
645
+	{
646
+		Benchmark::resetTimes();
647
+	}
648
+
649
+
650
+
651
+	/**
652
+	 * @deprecated 4.9.39.rc.034
653
+	 * @param null $timer_name
654
+	 */
655
+	public function start_timer($timer_name = null)
656
+	{
657
+		Benchmark::startTimer($timer_name);
658
+	}
659
+
660
+
661
+
662
+	/**
663
+	 * @deprecated 4.9.39.rc.034
664
+	 * @param string $timer_name
665
+	 */
666
+	public function stop_timer($timer_name = '')
667
+	{
668
+		Benchmark::stopTimer($timer_name);
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * @deprecated 4.9.39.rc.034
675
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
676
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
677
+	 * @return void
678
+	 */
679
+	public function measure_memory($label, $output_now = false)
680
+	{
681
+		Benchmark::measureMemory($label, $output_now);
682
+	}
683
+
684
+
685
+
686
+	/**
687
+	 * @deprecated 4.9.39.rc.034
688
+	 * @param int $size
689
+	 * @return string
690
+	 */
691
+	public function convert($size)
692
+	{
693
+		return Benchmark::convert($size);
694
+	}
695
+
696
+
697 697
 
698
-    /**
699
-     * @deprecated 4.9.39.rc.034
700
-     * @param bool $output_now
701
-     * @return string
702
-     */
703
-    public function show_times($output_now = true)
704
-    {
705
-        return Benchmark::displayResults($output_now);
706
-    }
698
+	/**
699
+	 * @deprecated 4.9.39.rc.034
700
+	 * @param bool $output_now
701
+	 * @return string
702
+	 */
703
+	public function show_times($output_now = true)
704
+	{
705
+		return Benchmark::displayResults($output_now);
706
+	}
707 707
 
708 708
 
709 709
 
710
-    /**
711
-     * @deprecated 4.9.39.rc.034
712
-     * @param string $timer_name
713
-     * @param float  $total_time
714
-     * @return string
715
-     */
716
-    public function format_time($timer_name, $total_time)
717
-    {
718
-        return Benchmark::formatTime($timer_name, $total_time);
719
-    }
710
+	/**
711
+	 * @deprecated 4.9.39.rc.034
712
+	 * @param string $timer_name
713
+	 * @param float  $total_time
714
+	 * @return string
715
+	 */
716
+	public function format_time($timer_name, $total_time)
717
+	{
718
+		return Benchmark::formatTime($timer_name, $total_time);
719
+	}
720 720
 }
721 721
 
722 722
 
@@ -726,31 +726,31 @@  discard block
 block discarded – undo
726 726
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
727 727
  */
728 728
 if (class_exists('Kint') && ! function_exists('dump_wp_query')) {
729
-    function dump_wp_query()
730
-    {
731
-        global $wp_query;
732
-        d($wp_query);
733
-    }
729
+	function dump_wp_query()
730
+	{
731
+		global $wp_query;
732
+		d($wp_query);
733
+	}
734 734
 }
735 735
 /**
736 736
  * borrowed from Kint Debugger
737 737
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
738 738
  */
739 739
 if (class_exists('Kint') && ! function_exists('dump_wp')) {
740
-    function dump_wp()
741
-    {
742
-        global $wp;
743
-        d($wp);
744
-    }
740
+	function dump_wp()
741
+	{
742
+		global $wp;
743
+		d($wp);
744
+	}
745 745
 }
746 746
 /**
747 747
  * borrowed from Kint Debugger
748 748
  * Plugin URI: http://upthemes.com/plugins/kint-debugger/
749 749
  */
750 750
 if (class_exists('Kint') && ! function_exists('dump_post')) {
751
-    function dump_post()
752
-    {
753
-        global $post;
754
-        d($post);
755
-    }
751
+	function dump_post()
752
+	{
753
+		global $post;
754
+		d($post);
755
+	}
756 756
 }
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     public static function instance()
38 38
     {
39 39
         // check if class object is instantiated, and instantiated properly
40
-        if (! self::$_instance instanceof EEH_Debug_Tools) {
40
+        if ( ! self::$_instance instanceof EEH_Debug_Tools) {
41 41
             self::$_instance = new self();
42 42
         }
43 43
         return self::$_instance;
@@ -54,14 +54,14 @@  discard block
 block discarded – undo
54 54
         if (
55 55
             defined('EE_LOAD_KINT')
56 56
             && ! class_exists('Kint')
57
-            && file_exists(EE_PLUGIN_DIR_PATH . 'tests/kint/Kint.class.php')
57
+            && file_exists(EE_PLUGIN_DIR_PATH.'tests/kint/Kint.class.php')
58 58
         ) {
59 59
             // despite EE4 having a check for an existing copy of the Kint debugging class,
60 60
             // if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
61 61
             // then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
62 62
             // so we've moved it to our test folder so that it is not included with production releases
63 63
             // plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
64
-            require_once(EE_PLUGIN_DIR_PATH . 'tests/kint/Kint.class.php');
64
+            require_once(EE_PLUGIN_DIR_PATH.'tests/kint/Kint.class.php');
65 65
         }
66 66
         $plugin = basename(EE_PLUGIN_DIR_PATH);
67 67
         add_action("activate_{$plugin}", array('EEH_Debug_Tools', 'ee_plugin_activation_errors'));
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
      */
79 79
     public static function show_db_name()
80 80
     {
81
-        if (! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
81
+        if ( ! defined('DOING_AJAX') && (defined('EE_ERROR_EMAILS') && EE_ERROR_EMAILS)) {
82 82
             echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '
83 83
                  . DB_NAME
84 84
                  . '</p>';
@@ -128,12 +128,12 @@  discard block
 block discarded – undo
128 128
         global $wp_filter;
129 129
         echo '<br/><br/><br/><h3>Hooked Functions</h3>';
130 130
         if ($tag) {
131
-            $hook[ $tag ] = $wp_filter[ $tag ];
132
-            if (! is_array($hook[ $tag ])) {
131
+            $hook[$tag] = $wp_filter[$tag];
132
+            if ( ! is_array($hook[$tag])) {
133 133
                 trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
134 134
                 return;
135 135
             }
136
-            echo '<h5>For Tag: ' . esc_html($tag) . '</h5>';
136
+            echo '<h5>For Tag: '.esc_html($tag).'</h5>';
137 137
         } else {
138 138
             $hook = is_array($wp_filter) ? $wp_filter : array($wp_filter);
139 139
             ksort($hook);
@@ -163,12 +163,12 @@  discard block
 block discarded – undo
163 163
     {
164 164
         $filters = array();
165 165
         global $wp_filter;
166
-        if (isset($wp_filter[ $hook_name ])) {
167
-            $filters[ $hook_name ] = array();
168
-            foreach ($wp_filter[ $hook_name ] as $priority => $callbacks) {
169
-                $filters[ $hook_name ][ $priority ] = array();
166
+        if (isset($wp_filter[$hook_name])) {
167
+            $filters[$hook_name] = array();
168
+            foreach ($wp_filter[$hook_name] as $priority => $callbacks) {
169
+                $filters[$hook_name][$priority] = array();
170 170
                 foreach ($callbacks as $callback) {
171
-                    $filters[ $hook_name ][ $priority ][] = $callback['function'];
171
+                    $filters[$hook_name][$priority][] = $callback['function'];
172 172
                 }
173 173
             }
174 174
         }
@@ -190,15 +190,15 @@  discard block
 block discarded – undo
190 190
             if (empty($activation_errors)) {
191 191
                 return;
192 192
             }
193
-            $activation_errors = date('Y-m-d H:i:s') . "\n" . $activation_errors;
194
-            espresso_load_required('EEH_File', EE_HELPERS . 'EEH_File.helper.php');
193
+            $activation_errors = date('Y-m-d H:i:s')."\n".$activation_errors;
194
+            espresso_load_required('EEH_File', EE_HELPERS.'EEH_File.helper.php');
195 195
             if (class_exists('EEH_File')) {
196 196
                 try {
197 197
                     EEH_File::ensure_file_exists_and_is_writable(
198
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html'
198
+                        EVENT_ESPRESSO_UPLOAD_DIR.'logs/espresso_plugin_activation_errors.html'
199 199
                     );
200 200
                     EEH_File::write_to_file(
201
-                        EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html',
201
+                        EVENT_ESPRESSO_UPLOAD_DIR.'logs/espresso_plugin_activation_errors.html',
202 202
                         $activation_errors
203 203
                     );
204 204
                 } catch (EE_Error $e) {
@@ -218,11 +218,11 @@  discard block
 block discarded – undo
218 218
             } else {
219 219
                 // old school attempt
220 220
                 file_put_contents(
221
-                    EVENT_ESPRESSO_UPLOAD_DIR . 'logs/espresso_plugin_activation_errors.html',
221
+                    EVENT_ESPRESSO_UPLOAD_DIR.'logs/espresso_plugin_activation_errors.html',
222 222
                     $activation_errors
223 223
                 );
224 224
             }
225
-            $activation_errors = get_option('ee_plugin_activation_errors', '') . $activation_errors;
225
+            $activation_errors = get_option('ee_plugin_activation_errors', '').$activation_errors;
226 226
             update_option('ee_plugin_activation_errors', $activation_errors);
227 227
         }
228 228
     }
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
         // don't trigger error if doing ajax,
283 283
         // instead we'll add a transient EE_Error notice that in theory should show on the next request.
284 284
         if (defined('DOING_AJAX') && DOING_AJAX) {
285
-            $error_message .= ' ' . esc_html__(
285
+            $error_message .= ' '.esc_html__(
286 286
                 'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ',
287 287
                 'event_espresso'
288 288
             );
@@ -325,18 +325,18 @@  discard block
 block discarded – undo
325 325
         $debug_key = 'EE_DEBUG_SPCO'
326 326
     ) {
327 327
         if (WP_DEBUG) {
328
-            $debug_key = $debug_key . '_' . EE_Session::instance()->id();
328
+            $debug_key = $debug_key.'_'.EE_Session::instance()->id();
329 329
             $debug_data = get_option($debug_key, array());
330 330
             $default_data = array(
331
-                $class => $func . '() : ' . $line,
331
+                $class => $func.'() : '.$line,
332 332
             );
333 333
             // don't serialize objects
334 334
             $info = self::strip_objects($info);
335 335
             $index = ! empty($debug_index) ? $debug_index : 0;
336
-            if (! isset($debug_data[ $index ])) {
337
-                $debug_data[ $index ] = array();
336
+            if ( ! isset($debug_data[$index])) {
337
+                $debug_data[$index] = array();
338 338
             }
339
-            $debug_data[ $index ][ microtime() ] = array_merge($default_data, $info);
339
+            $debug_data[$index][microtime()] = array_merge($default_data, $info);
340 340
             update_option($debug_key, $debug_data);
341 341
         }
342 342
     }
@@ -353,20 +353,20 @@  discard block
 block discarded – undo
353 353
     {
354 354
         foreach ($info as $key => $value) {
355 355
             if (is_array($value)) {
356
-                $info[ $key ] = self::strip_objects($value);
356
+                $info[$key] = self::strip_objects($value);
357 357
             } elseif (is_object($value)) {
358 358
                 $object_class = get_class($value);
359
-                $info[ $object_class ] = array();
360
-                $info[ $object_class ]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
359
+                $info[$object_class] = array();
360
+                $info[$object_class]['ID'] = method_exists($value, 'ID') ? $value->ID() : spl_object_hash($value);
361 361
                 if (method_exists($value, 'ID')) {
362
-                    $info[ $object_class ]['ID'] = $value->ID();
362
+                    $info[$object_class]['ID'] = $value->ID();
363 363
                 }
364 364
                 if (method_exists($value, 'status')) {
365
-                    $info[ $object_class ]['status'] = $value->status();
365
+                    $info[$object_class]['status'] = $value->status();
366 366
                 } elseif (method_exists($value, 'status_ID')) {
367
-                    $info[ $object_class ]['status'] = $value->status_ID();
367
+                    $info[$object_class]['status'] = $value->status_ID();
368 368
                 }
369
-                unset($info[ $key ]);
369
+                unset($info[$key]);
370 370
             }
371 371
         }
372 372
         return (array) $info;
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
         // $result = EEH_Debug_Tools::headingSpacer($heading_tag);
401 401
         $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin, $line);
402 402
         $result .= $is_method
403
-            ? EEH_Debug_Tools::grey_span('::') . EEH_Debug_Tools::orange_span($var . '()')
404
-            : EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span($var);
403
+            ? EEH_Debug_Tools::grey_span('::').EEH_Debug_Tools::orange_span($var.'()')
404
+            : EEH_Debug_Tools::grey_span(' : ').EEH_Debug_Tools::orange_span($var);
405 405
         $result .= EEH_Debug_Tools::file_and_line($file, $line, $heading_tag);
406 406
         $result .= EEH_Debug_Tools::headingX($heading_tag);
407 407
         if ($die) {
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
             return "{$line_breaks}{$line}) {$var_name}";
461 461
         }
462 462
         $margin = "25px 0 0 {$margin}";
463
-        return '<' . $heading_tag . ' style="color:#2EA2CC; margin:' . $margin . ';"><b>' . $var_name . '</b>';
463
+        return '<'.$heading_tag.' style="color:#2EA2CC; margin:'.$margin.';"><b>'.$var_name.'</b>';
464 464
     }
465 465
 
466 466
 
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
         if (EEH_Debug_Tools::plainOutput()) {
475 475
             return '';
476 476
         }
477
-        return '</' . $heading_tag . '>';
477
+        return '</'.$heading_tag.'>';
478 478
     }
479 479
 
480 480
 
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
         if (EEH_Debug_Tools::plainOutput()) {
489 489
             return $content;
490 490
         }
491
-        return '<span style="color:#999">' . $content . '</span>';
491
+        return '<span style="color:#999">'.$content.'</span>';
492 492
     }
493 493
 
494 494
 
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
         $file = str_replace(EE_PLUGIN_DIR_PATH, '/', $file);
507 507
         if (EEH_Debug_Tools::plainOutput()) {
508 508
             if ($heading_tag === 'h1' || $heading_tag === 'h2') {
509
-                return " ({$file})" . EEH_Debug_Tools::lineBreak();
509
+                return " ({$file})".EEH_Debug_Tools::lineBreak();
510 510
             }
511 511
             return '';
512 512
         }
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
         if (EEH_Debug_Tools::plainOutput()) {
531 531
             return $content;
532 532
         }
533
-        return '<span style="color:#E76700">' . $content . '</span>';
533
+        return '<span style="color:#E76700">'.$content.'</span>';
534 534
     }
535 535
 
536 536
 
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
         if (EEH_Debug_Tools::plainOutput()) {
548 548
             return str_replace("\n", '', $var);
549 549
         }
550
-        return '<pre style="color: #9C3; display: inline-block; padding:.4em .6em; background: #334">' . $var . '</pre>';
550
+        return '<pre style="color: #9C3; display: inline-block; padding:.4em .6em; background: #334">'.$var.'</pre>';
551 551
     }
552 552
 
553 553
 
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
         $heading_tag = EEH_Debug_Tools::headingTag($heading_tag);
595 595
         // $result = EEH_Debug_Tools::headingSpacer($heading_tag);
596 596
         $result = EEH_Debug_Tools::heading($var_name, $heading_tag, $margin, $line);
597
-        $result .= EEH_Debug_Tools::grey_span(' : ') . EEH_Debug_Tools::orange_span(
597
+        $result .= EEH_Debug_Tools::grey_span(' : ').EEH_Debug_Tools::orange_span(
598 598
             EEH_Debug_Tools::pre_span($var)
599 599
         );
600 600
         $result .= EEH_Debug_Tools::file_and_line($file, $line, $heading_tag);
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
         $converted = str_replace(['$', '_', 'this->'], ['', ' ', ''], $var_name);
612 612
         $words = explode(' ', $converted);
613 613
         $words = array_map(
614
-            function ($word) {
614
+            function($word) {
615 615
                 return $word === 'id' || $word === 'Id' ? 'ID' : $word;
616 616
             },
617 617
             $words
Please login to merge, or discard this patch.
core/helpers/EEH_Array.helper.php 2 patches
Indentation   +290 added lines, -290 removed lines patch added patch discarded remove patch
@@ -11,313 +11,313 @@
 block discarded – undo
11 11
  */
12 12
 class EEH_Array extends EEH_Base
13 13
 {
14
-    /**
15
-     * This method basically works the same as the PHP core function array_diff except it allows you to compare arrays
16
-     * of EE_Base_Class objects NOTE: This will ONLY work on an array of EE_Base_Class objects
17
-     *
18
-     * @uses array_udiff core php function for setting up our own array comparison
19
-     * @uses self::_compare_objects as the custom method for array_udiff
20
-     * @param  array $array1 an array of objects
21
-     * @param  array $array2 an array of objects
22
-     * @return array         an array of objects found in array 1 that aren't found in array 2.
23
-     */
24
-    public static function object_array_diff($array1, $array2)
25
-    {
26
-        return array_udiff($array1, $array2, array('self', '_compare_objects'));
27
-    }
14
+	/**
15
+	 * This method basically works the same as the PHP core function array_diff except it allows you to compare arrays
16
+	 * of EE_Base_Class objects NOTE: This will ONLY work on an array of EE_Base_Class objects
17
+	 *
18
+	 * @uses array_udiff core php function for setting up our own array comparison
19
+	 * @uses self::_compare_objects as the custom method for array_udiff
20
+	 * @param  array $array1 an array of objects
21
+	 * @param  array $array2 an array of objects
22
+	 * @return array         an array of objects found in array 1 that aren't found in array 2.
23
+	 */
24
+	public static function object_array_diff($array1, $array2)
25
+	{
26
+		return array_udiff($array1, $array2, array('self', '_compare_objects'));
27
+	}
28 28
 
29
-    /**
30
-     * Given that $arr is an array, determines if it's associative or numerically AND sequentially indexed
31
-     *
32
-     * @param array $array
33
-     * @return boolean
34
-     */
35
-    public static function is_associative_array(array $array): bool
36
-    {
37
-        return ! empty($array) && array_keys($array) !== range(0, count($array) - 1);
38
-    }
29
+	/**
30
+	 * Given that $arr is an array, determines if it's associative or numerically AND sequentially indexed
31
+	 *
32
+	 * @param array $array
33
+	 * @return boolean
34
+	 */
35
+	public static function is_associative_array(array $array): bool
36
+	{
37
+		return ! empty($array) && array_keys($array) !== range(0, count($array) - 1);
38
+	}
39 39
 
40
-    /**
41
-     * Gets an item from the array and leave the array intact. Use in place of end()
42
-     * when you don't want to change the array
43
-     *
44
-     * @param array $arr
45
-     * @return mixed what ever is in the array
46
-     */
47
-    public static function get_one_item_from_array($arr)
48
-    {
49
-        $item = end($arr);
50
-        reset($arr);
51
-        return $item;
52
-    }
40
+	/**
41
+	 * Gets an item from the array and leave the array intact. Use in place of end()
42
+	 * when you don't want to change the array
43
+	 *
44
+	 * @param array $arr
45
+	 * @return mixed what ever is in the array
46
+	 */
47
+	public static function get_one_item_from_array($arr)
48
+	{
49
+		$item = end($arr);
50
+		reset($arr);
51
+		return $item;
52
+	}
53 53
 
54
-    /**
55
-     * Detects if this is a multi-dimensional array
56
-     * meaning that at least one top-level value is an array. Eg [ [], ...]
57
-     *
58
-     * @param mixed $arr
59
-     * @return boolean
60
-     */
61
-    public static function is_multi_dimensional_array($arr)
62
-    {
63
-        if (is_array($arr)) {
64
-            foreach ($arr as $item) {
65
-                if (is_array($item)) {
66
-                    return true; // yep, there's at least 2 levels to this array
67
-                }
68
-            }
69
-        }
70
-        return false; // there's only 1 level, or it's not an array at all!
71
-    }
54
+	/**
55
+	 * Detects if this is a multi-dimensional array
56
+	 * meaning that at least one top-level value is an array. Eg [ [], ...]
57
+	 *
58
+	 * @param mixed $arr
59
+	 * @return boolean
60
+	 */
61
+	public static function is_multi_dimensional_array($arr)
62
+	{
63
+		if (is_array($arr)) {
64
+			foreach ($arr as $item) {
65
+				if (is_array($item)) {
66
+					return true; // yep, there's at least 2 levels to this array
67
+				}
68
+			}
69
+		}
70
+		return false; // there's only 1 level, or it's not an array at all!
71
+	}
72 72
 
73
-    /**
74
-     * Shorthand for isset( $arr[ $index ] ) ? $arr[ $index ] : $default
75
-     *
76
-     * @param array $arr
77
-     * @param mixed $index
78
-     * @param mixed $default
79
-     * @return mixed
80
-     */
81
-    public static function is_set($arr, $index, $default)
82
-    {
83
-        return isset($arr[ $index ]) ? $arr[ $index ] : $default;
84
-    }
73
+	/**
74
+	 * Shorthand for isset( $arr[ $index ] ) ? $arr[ $index ] : $default
75
+	 *
76
+	 * @param array $arr
77
+	 * @param mixed $index
78
+	 * @param mixed $default
79
+	 * @return mixed
80
+	 */
81
+	public static function is_set($arr, $index, $default)
82
+	{
83
+		return isset($arr[ $index ]) ? $arr[ $index ] : $default;
84
+	}
85 85
 
86
-    /**
87
-     * Exactly like `maybe_unserialize`, but also accounts for a WP bug: http://core.trac.wordpress.org/ticket/26118
88
-     *
89
-     * @param mixed $value usually a string, but could be an array or object
90
-     * @return mixed the UN-serialized data
91
-     */
92
-    public static function maybe_unserialize($value)
93
-    {
94
-        $data = maybe_unserialize($value);
95
-        // it's possible that this still has serialized data if it's the session.
96
-        //  WP has a bug, http://core.trac.wordpress.org/ticket/26118 that doesn't unserialize this automatically.
97
-        $token = 'C';
98
-        $data = is_string($data) ? trim($data) : $data;
99
-        if (is_string($data) && strlen($data) > 1 && $data[0] == $token && preg_match("/^{$token}:[0-9]+:/s", $data)) {
100
-            return unserialize($data);
101
-        } else {
102
-            return $data;
103
-        }
104
-    }
86
+	/**
87
+	 * Exactly like `maybe_unserialize`, but also accounts for a WP bug: http://core.trac.wordpress.org/ticket/26118
88
+	 *
89
+	 * @param mixed $value usually a string, but could be an array or object
90
+	 * @return mixed the UN-serialized data
91
+	 */
92
+	public static function maybe_unserialize($value)
93
+	{
94
+		$data = maybe_unserialize($value);
95
+		// it's possible that this still has serialized data if it's the session.
96
+		//  WP has a bug, http://core.trac.wordpress.org/ticket/26118 that doesn't unserialize this automatically.
97
+		$token = 'C';
98
+		$data = is_string($data) ? trim($data) : $data;
99
+		if (is_string($data) && strlen($data) > 1 && $data[0] == $token && preg_match("/^{$token}:[0-9]+:/s", $data)) {
100
+			return unserialize($data);
101
+		} else {
102
+			return $data;
103
+		}
104
+	}
105 105
 
106 106
 
107
-    /**
108
-     * insert_into_array
109
-     *
110
-     * @param array        $target_array the array to insert new data into
111
-     * @param array        $array_to_insert the new data to be inserted
112
-     * @param int|string|null $offset a known key within $target_array where new data will be inserted
113
-     * @param bool         $add_before whether to add new data before or after the offset key
114
-     * @param bool         $preserve_keys whether or not to reset numerically indexed arrays
115
-     * @return array
116
-     */
117
-    public static function insert_into_array(
118
-        array $target_array = array(),
119
-        array $array_to_insert = array(),
120
-        $offset = null,
121
-        bool $add_before = true,
122
-        bool $preserve_keys = true
123
-    ) {
124
-        $target_array_keys = array_keys($target_array);
125
-        // if no offset key was supplied
126
-        if (empty($offset)) {
127
-            // use start or end of $target_array based on whether we are adding before or not
128
-            $offset = $add_before ? 0 : count($target_array);
129
-        }
130
-        // if offset key is a string, then find the corresponding numeric location for that element
131
-        $offset = is_int($offset) ? $offset : array_search($offset, $target_array_keys, true);
132
-        // add one to the offset if adding after
133
-        $offset = $add_before ? $offset : $offset + 1;
134
-        // but ensure offset does not exceed the length of the array
135
-        $offset = $offset > count($target_array) ? count($target_array) : $offset;
136
-        // reindex array ???
137
-        if ($preserve_keys) {
138
-            // take a slice of the target array from the beginning till the offset,
139
-            // then add the new data
140
-            // then add another slice that starts at the offset and goes till the end
141
-            return array_slice($target_array, 0, $offset, true) + $array_to_insert + array_slice(
142
-                $target_array,
143
-                $offset,
144
-                null,
145
-                true
146
-            );
147
-        } else {
148
-            // since we don't want to preserve keys, we can use array_splice
149
-            array_splice($target_array, $offset, 0, $array_to_insert);
150
-            return $target_array;
151
-        }
152
-    }
107
+	/**
108
+	 * insert_into_array
109
+	 *
110
+	 * @param array        $target_array the array to insert new data into
111
+	 * @param array        $array_to_insert the new data to be inserted
112
+	 * @param int|string|null $offset a known key within $target_array where new data will be inserted
113
+	 * @param bool         $add_before whether to add new data before or after the offset key
114
+	 * @param bool         $preserve_keys whether or not to reset numerically indexed arrays
115
+	 * @return array
116
+	 */
117
+	public static function insert_into_array(
118
+		array $target_array = array(),
119
+		array $array_to_insert = array(),
120
+		$offset = null,
121
+		bool $add_before = true,
122
+		bool $preserve_keys = true
123
+	) {
124
+		$target_array_keys = array_keys($target_array);
125
+		// if no offset key was supplied
126
+		if (empty($offset)) {
127
+			// use start or end of $target_array based on whether we are adding before or not
128
+			$offset = $add_before ? 0 : count($target_array);
129
+		}
130
+		// if offset key is a string, then find the corresponding numeric location for that element
131
+		$offset = is_int($offset) ? $offset : array_search($offset, $target_array_keys, true);
132
+		// add one to the offset if adding after
133
+		$offset = $add_before ? $offset : $offset + 1;
134
+		// but ensure offset does not exceed the length of the array
135
+		$offset = $offset > count($target_array) ? count($target_array) : $offset;
136
+		// reindex array ???
137
+		if ($preserve_keys) {
138
+			// take a slice of the target array from the beginning till the offset,
139
+			// then add the new data
140
+			// then add another slice that starts at the offset and goes till the end
141
+			return array_slice($target_array, 0, $offset, true) + $array_to_insert + array_slice(
142
+				$target_array,
143
+				$offset,
144
+				null,
145
+				true
146
+			);
147
+		} else {
148
+			// since we don't want to preserve keys, we can use array_splice
149
+			array_splice($target_array, $offset, 0, $array_to_insert);
150
+			return $target_array;
151
+		}
152
+	}
153 153
 
154 154
 
155
-    /**
156
-     * array_merge() is slow and should never be used while looping over data
157
-     * if you don't need to preserve keys from all arrays, then using a foreach loop is much faster
158
-     * so really this acts more like array_replace( $array1, $array2 )
159
-     * or a union with the arrays flipped ( $array2 + $array1 )
160
-     * this saves a few lines of code and improves readability
161
-     *
162
-     * @param array $array1
163
-     * @param array $array2
164
-     * @return array
165
-     */
166
-    public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
167
-    {
168
-        foreach ($array2 as $key => $value) {
169
-            $array1[ $key ] = $value;
170
-        }
171
-        return $array1;
172
-    }
155
+	/**
156
+	 * array_merge() is slow and should never be used while looping over data
157
+	 * if you don't need to preserve keys from all arrays, then using a foreach loop is much faster
158
+	 * so really this acts more like array_replace( $array1, $array2 )
159
+	 * or a union with the arrays flipped ( $array2 + $array1 )
160
+	 * this saves a few lines of code and improves readability
161
+	 *
162
+	 * @param array $array1
163
+	 * @param array $array2
164
+	 * @return array
165
+	 */
166
+	public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
167
+	{
168
+		foreach ($array2 as $key => $value) {
169
+			$array1[ $key ] = $value;
170
+		}
171
+		return $array1;
172
+	}
173 173
 
174 174
 
175
-    /**
176
-     * given a flat array like $array = array('A', 'B', 'C')
177
-     * will convert into a multidimensional array like $array[A][B][C]
178
-     * if $final_value is provided and is anything other than null,
179
-     * then that will be set as the value for the innermost array key
180
-     * like so: $array[A][B][C] = $final_value
181
-     *
182
-     * @param array $flat_array
183
-     * @param mixed $final_value
184
-     * @return array
185
-     */
186
-    public static function convert_array_values_to_keys(array $flat_array, $final_value = null)
187
-    {
188
-        $multidimensional = array();
189
-        $reference = &$multidimensional;
190
-        foreach ($flat_array as $key) {
191
-            $reference[ $key ] = array();
192
-            $reference = &$reference[ $key ];
193
-        }
194
-        if ($final_value !== null) {
195
-            $reference = $final_value;
196
-        }
197
-        return $multidimensional;
198
-    }
175
+	/**
176
+	 * given a flat array like $array = array('A', 'B', 'C')
177
+	 * will convert into a multidimensional array like $array[A][B][C]
178
+	 * if $final_value is provided and is anything other than null,
179
+	 * then that will be set as the value for the innermost array key
180
+	 * like so: $array[A][B][C] = $final_value
181
+	 *
182
+	 * @param array $flat_array
183
+	 * @param mixed $final_value
184
+	 * @return array
185
+	 */
186
+	public static function convert_array_values_to_keys(array $flat_array, $final_value = null)
187
+	{
188
+		$multidimensional = array();
189
+		$reference = &$multidimensional;
190
+		foreach ($flat_array as $key) {
191
+			$reference[ $key ] = array();
192
+			$reference = &$reference[ $key ];
193
+		}
194
+		if ($final_value !== null) {
195
+			$reference = $final_value;
196
+		}
197
+		return $multidimensional;
198
+	}
199 199
 
200 200
 
201
-    /**
202
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
203
-     * @param array $array
204
-     * @return bool
205
-     */
206
-    public static function is_array_numerically_and_sequentially_indexed(array $array)
207
-    {
208
-        return empty($array) || array_keys($array) === range(0, count($array) - 1);
209
-    }
201
+	/**
202
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
203
+	 * @param array $array
204
+	 * @return bool
205
+	 */
206
+	public static function is_array_numerically_and_sequentially_indexed(array $array)
207
+	{
208
+		return empty($array) || array_keys($array) === range(0, count($array) - 1);
209
+	}
210 210
 
211 211
 
212
-    /**
213
-     * recursively walks through an array and adds slashes to all no array elements
214
-     *
215
-     * @param mixed $element
216
-     * @return array|string
217
-     * @since   4.10.29.p
218
-     */
219
-    public static function addSlashesRecursively($element)
220
-    {
221
-        if (is_array($element)) {
222
-            foreach ($element as $key => $value) {
223
-                $element[ $key ] = EEH_Array::addSlashesRecursively($value);
224
-            }
225
-            return $element;
226
-        }
227
-        return is_string($element) ? addslashes($element) : $element;
228
-    }
212
+	/**
213
+	 * recursively walks through an array and adds slashes to all no array elements
214
+	 *
215
+	 * @param mixed $element
216
+	 * @return array|string
217
+	 * @since   4.10.29.p
218
+	 */
219
+	public static function addSlashesRecursively($element)
220
+	{
221
+		if (is_array($element)) {
222
+			foreach ($element as $key => $value) {
223
+				$element[ $key ] = EEH_Array::addSlashesRecursively($value);
224
+			}
225
+			return $element;
226
+		}
227
+		return is_string($element) ? addslashes($element) : $element;
228
+	}
229 229
 
230 230
 
231
-    /**
232
-     * link https://stackoverflow.com/a/3877494
233
-     *
234
-     * @param array $array_1
235
-     * @param array $array_2
236
-     * @return array
237
-     * @since   $VID:$
238
-     */
239
-    public static function array_diff_recursive(array $array_1, array $array_2): array
240
-    {
241
-        $diff = [];
242
-        foreach ($array_1 as $key => $value) {
243
-            if (array_key_exists($key, $array_2)) {
244
-                if (is_array($value)) {
245
-                    $inner_diff = EEH_Array::array_diff_recursive($value, $array_2[ $key ]);
246
-                    if (count($inner_diff)) {
247
-                        $diff[ $key ] = $inner_diff;
248
-                    }
249
-                } else {
250
-                    if ($value != $array_2[ $key ]) {
251
-                        $diff[ $key ] = $value;
252
-                    }
253
-                }
254
-            } else {
255
-                $diff[ $key ] = $value;
256
-            }
257
-        }
258
-        return $diff;
259
-    }
231
+	/**
232
+	 * link https://stackoverflow.com/a/3877494
233
+	 *
234
+	 * @param array $array_1
235
+	 * @param array $array_2
236
+	 * @return array
237
+	 * @since   $VID:$
238
+	 */
239
+	public static function array_diff_recursive(array $array_1, array $array_2): array
240
+	{
241
+		$diff = [];
242
+		foreach ($array_1 as $key => $value) {
243
+			if (array_key_exists($key, $array_2)) {
244
+				if (is_array($value)) {
245
+					$inner_diff = EEH_Array::array_diff_recursive($value, $array_2[ $key ]);
246
+					if (count($inner_diff)) {
247
+						$diff[ $key ] = $inner_diff;
248
+					}
249
+				} else {
250
+					if ($value != $array_2[ $key ]) {
251
+						$diff[ $key ] = $value;
252
+					}
253
+				}
254
+			} else {
255
+				$diff[ $key ] = $value;
256
+			}
257
+		}
258
+		return $diff;
259
+	}
260 260
 
261 261
 
262
-    /**
263
-     * converts multidimensional arrays into a single depth associative array
264
-     * or converts arrays of any depth into a readable string representation
265
-     *
266
-     *  $example = [
267
-     *      'a' => 'A',
268
-     *      'b' => 'B',
269
-     *      'c' => [
270
-     *          'd' => 'D',
271
-     *          'e' => 'E',
272
-     *          'f' => [ 'G', 'H', 'I' ],
273
-     *      ],
274
-     *      [ 'J', 'K' ],
275
-     *      'L',
276
-     *      'M',
277
-     *      'n' => [
278
-     *          'o' => 'P'
279
-     *      ],
280
-     *  ];
281
-     *
282
-     *  print_r( EEH_Array::flattenArray($example) );
283
-     *
284
-     *  Array (
285
-     *      [a] => A
286
-     *      [b] => B
287
-     *      [c] => [ d:D, e:E, f:[ G, H, I ] ]
288
-     *      [0] => [ J, K ]
289
-     *      [1] => L
290
-     *      [2] => M
291
-     *      [n] => [ o:P ]
292
-     *  )
293
-     *
294
-     *  print_r( EEH_Array::flattenArray($example, true) );
295
-     *
296
-     *  "a:A, b:B, c:[ d:D, e:E, f:[ G, H, I ] ], [ J, K ], L, M, n:[ o:P ]"
297
-     *
298
-     * @param array $array      the array to be flattened
299
-     * @param bool  $to_string  [true] will flatten the entire array down into a string
300
-     *                          [false] will only flatten sub-arrays down into strings and return a array
301
-     * @param bool  $top_level  used for formatting purposes only, best to leave this alone as it's set internally
302
-     * @return array|false|string
303
-     * @since $VID:$
304
-     */
305
-    public static function flattenArray(array $array, bool $to_string = false, bool $top_level = true)
306
-    {
307
-        $flat_array = [];
308
-        foreach ($array as $key => $value) {
309
-            $flat_array[ $key ] = is_array($value)
310
-                ? EEH_Array::flattenArray($value, true, false)
311
-                : $value;
312
-        }
313
-        if (! $to_string) {
314
-            return $flat_array;
315
-        }
316
-        $flat = '';
317
-        foreach ($flat_array as $key => $value) {
318
-            $flat .= is_int($key) ? "$value, " : "$key:$value, ";
319
-        }
320
-        $flat = substr($flat, 0, -2);
321
-        return $top_level ? $flat : "[ $flat ]";
322
-    }
262
+	/**
263
+	 * converts multidimensional arrays into a single depth associative array
264
+	 * or converts arrays of any depth into a readable string representation
265
+	 *
266
+	 *  $example = [
267
+	 *      'a' => 'A',
268
+	 *      'b' => 'B',
269
+	 *      'c' => [
270
+	 *          'd' => 'D',
271
+	 *          'e' => 'E',
272
+	 *          'f' => [ 'G', 'H', 'I' ],
273
+	 *      ],
274
+	 *      [ 'J', 'K' ],
275
+	 *      'L',
276
+	 *      'M',
277
+	 *      'n' => [
278
+	 *          'o' => 'P'
279
+	 *      ],
280
+	 *  ];
281
+	 *
282
+	 *  print_r( EEH_Array::flattenArray($example) );
283
+	 *
284
+	 *  Array (
285
+	 *      [a] => A
286
+	 *      [b] => B
287
+	 *      [c] => [ d:D, e:E, f:[ G, H, I ] ]
288
+	 *      [0] => [ J, K ]
289
+	 *      [1] => L
290
+	 *      [2] => M
291
+	 *      [n] => [ o:P ]
292
+	 *  )
293
+	 *
294
+	 *  print_r( EEH_Array::flattenArray($example, true) );
295
+	 *
296
+	 *  "a:A, b:B, c:[ d:D, e:E, f:[ G, H, I ] ], [ J, K ], L, M, n:[ o:P ]"
297
+	 *
298
+	 * @param array $array      the array to be flattened
299
+	 * @param bool  $to_string  [true] will flatten the entire array down into a string
300
+	 *                          [false] will only flatten sub-arrays down into strings and return a array
301
+	 * @param bool  $top_level  used for formatting purposes only, best to leave this alone as it's set internally
302
+	 * @return array|false|string
303
+	 * @since $VID:$
304
+	 */
305
+	public static function flattenArray(array $array, bool $to_string = false, bool $top_level = true)
306
+	{
307
+		$flat_array = [];
308
+		foreach ($array as $key => $value) {
309
+			$flat_array[ $key ] = is_array($value)
310
+				? EEH_Array::flattenArray($value, true, false)
311
+				: $value;
312
+		}
313
+		if (! $to_string) {
314
+			return $flat_array;
315
+		}
316
+		$flat = '';
317
+		foreach ($flat_array as $key => $value) {
318
+			$flat .= is_int($key) ? "$value, " : "$key:$value, ";
319
+		}
320
+		$flat = substr($flat, 0, -2);
321
+		return $top_level ? $flat : "[ $flat ]";
322
+	}
323 323
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
      */
81 81
     public static function is_set($arr, $index, $default)
82 82
     {
83
-        return isset($arr[ $index ]) ? $arr[ $index ] : $default;
83
+        return isset($arr[$index]) ? $arr[$index] : $default;
84 84
     }
85 85
 
86 86
     /**
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
     public static function merge_arrays_and_overwrite_keys(array $array1, array $array2)
167 167
     {
168 168
         foreach ($array2 as $key => $value) {
169
-            $array1[ $key ] = $value;
169
+            $array1[$key] = $value;
170 170
         }
171 171
         return $array1;
172 172
     }
@@ -188,8 +188,8 @@  discard block
 block discarded – undo
188 188
         $multidimensional = array();
189 189
         $reference = &$multidimensional;
190 190
         foreach ($flat_array as $key) {
191
-            $reference[ $key ] = array();
192
-            $reference = &$reference[ $key ];
191
+            $reference[$key] = array();
192
+            $reference = &$reference[$key];
193 193
         }
194 194
         if ($final_value !== null) {
195 195
             $reference = $final_value;
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
     {
221 221
         if (is_array($element)) {
222 222
             foreach ($element as $key => $value) {
223
-                $element[ $key ] = EEH_Array::addSlashesRecursively($value);
223
+                $element[$key] = EEH_Array::addSlashesRecursively($value);
224 224
             }
225 225
             return $element;
226 226
         }
@@ -242,17 +242,17 @@  discard block
 block discarded – undo
242 242
         foreach ($array_1 as $key => $value) {
243 243
             if (array_key_exists($key, $array_2)) {
244 244
                 if (is_array($value)) {
245
-                    $inner_diff = EEH_Array::array_diff_recursive($value, $array_2[ $key ]);
245
+                    $inner_diff = EEH_Array::array_diff_recursive($value, $array_2[$key]);
246 246
                     if (count($inner_diff)) {
247
-                        $diff[ $key ] = $inner_diff;
247
+                        $diff[$key] = $inner_diff;
248 248
                     }
249 249
                 } else {
250
-                    if ($value != $array_2[ $key ]) {
251
-                        $diff[ $key ] = $value;
250
+                    if ($value != $array_2[$key]) {
251
+                        $diff[$key] = $value;
252 252
                     }
253 253
                 }
254 254
             } else {
255
-                $diff[ $key ] = $value;
255
+                $diff[$key] = $value;
256 256
             }
257 257
         }
258 258
         return $diff;
@@ -306,11 +306,11 @@  discard block
 block discarded – undo
306 306
     {
307 307
         $flat_array = [];
308 308
         foreach ($array as $key => $value) {
309
-            $flat_array[ $key ] = is_array($value)
309
+            $flat_array[$key] = is_array($value)
310 310
                 ? EEH_Array::flattenArray($value, true, false)
311 311
                 : $value;
312 312
         }
313
-        if (! $to_string) {
313
+        if ( ! $to_string) {
314 314
             return $flat_array;
315 315
         }
316 316
         $flat = '';
Please login to merge, or discard this patch.
admin_pages/general_settings/General_Settings_Admin_Page.core.php 2 patches
Indentation   +1408 added lines, -1408 removed lines patch added patch discarded remove patch
@@ -19,1425 +19,1425 @@
 block discarded – undo
19 19
  */
20 20
 class General_Settings_Admin_Page extends EE_Admin_Page
21 21
 {
22
-    /**
23
-     * @var EE_Core_Config
24
-     */
25
-    public $core_config;
26
-
27
-
28
-    /**
29
-     * Initialize basic properties.
30
-     */
31
-    protected function _init_page_props()
32
-    {
33
-        $this->page_slug        = GEN_SET_PG_SLUG;
34
-        $this->page_label       = GEN_SET_LABEL;
35
-        $this->_admin_base_url  = GEN_SET_ADMIN_URL;
36
-        $this->_admin_base_path = GEN_SET_ADMIN;
37
-    }
38
-
39
-
40
-    /**
41
-     * Set ajax hooks
42
-     */
43
-    protected function _ajax_hooks()
44
-    {
45
-        add_action('wp_ajax_espresso_display_country_settings', [$this, 'display_country_settings']);
46
-        add_action('wp_ajax_espresso_display_country_states', [$this, 'display_country_states']);
47
-        add_action('wp_ajax_espresso_delete_state', [$this, 'delete_state'], 10, 3);
48
-        add_action('wp_ajax_espresso_add_new_state', [$this, 'add_new_state']);
49
-    }
50
-
51
-
52
-    /**
53
-     * More page properties initialization.
54
-     */
55
-    protected function _define_page_props()
56
-    {
57
-        $this->_admin_page_title = GEN_SET_LABEL;
58
-        $this->_labels           = ['publishbox' => esc_html__('Update Settings', 'event_espresso')];
59
-    }
60
-
61
-
62
-    /**
63
-     * Set page routes property.
64
-     */
65
-    protected function _set_page_routes()
66
-    {
67
-        $this->_page_routes = [
68
-            'critical_pages'                => [
69
-                'func'       => '_espresso_page_settings',
70
-                'capability' => 'manage_options',
71
-            ],
72
-            'update_espresso_page_settings' => [
73
-                'func'       => '_update_espresso_page_settings',
74
-                'capability' => 'manage_options',
75
-                'noheader'   => true,
76
-            ],
77
-            'default'                       => [
78
-                'func'       => '_your_organization_settings',
79
-                'capability' => 'manage_options',
80
-            ],
81
-
82
-            'update_your_organization_settings' => [
83
-                'func'       => '_update_your_organization_settings',
84
-                'capability' => 'manage_options',
85
-                'noheader'   => true,
86
-            ],
87
-
88
-            'admin_option_settings' => [
89
-                'func'       => '_admin_option_settings',
90
-                'capability' => 'manage_options',
91
-            ],
92
-
93
-            'update_admin_option_settings' => [
94
-                'func'       => '_update_admin_option_settings',
95
-                'capability' => 'manage_options',
96
-                'noheader'   => true,
97
-            ],
98
-
99
-            'country_settings' => [
100
-                'func'       => '_country_settings',
101
-                'capability' => 'manage_options',
102
-            ],
103
-
104
-            'update_country_settings' => [
105
-                'func'       => '_update_country_settings',
106
-                'capability' => 'manage_options',
107
-                'noheader'   => true,
108
-            ],
109
-
110
-            'display_country_settings' => [
111
-                'func'       => 'display_country_settings',
112
-                'capability' => 'manage_options',
113
-                'noheader'   => true,
114
-            ],
115
-
116
-            'add_new_state' => [
117
-                'func'       => 'add_new_state',
118
-                'capability' => 'manage_options',
119
-                'noheader'   => true,
120
-            ],
121
-
122
-            'delete_state'            => [
123
-                'func'       => 'delete_state',
124
-                'capability' => 'manage_options',
125
-                'noheader'   => true,
126
-            ],
127
-            'privacy_settings'        => [
128
-                'func'       => 'privacySettings',
129
-                'capability' => 'manage_options',
130
-            ],
131
-            'update_privacy_settings' => [
132
-                'func'               => 'updatePrivacySettings',
133
-                'capability'         => 'manage_options',
134
-                'noheader'           => true,
135
-                'headers_sent_route' => 'privacy_settings',
136
-            ],
137
-        ];
138
-    }
139
-
140
-
141
-    /**
142
-     * Set page configuration property
143
-     */
144
-    protected function _set_page_config()
145
-    {
146
-        $this->_page_config = [
147
-            'critical_pages'        => [
148
-                'nav'           => [
149
-                    'label' => esc_html__('Critical Pages', 'event_espresso'),
150
-                    'order' => 50,
151
-                ],
152
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
153
-                'help_tabs'     => [
154
-                    'general_settings_critical_pages_help_tab' => [
155
-                        'title'    => esc_html__('Critical Pages', 'event_espresso'),
156
-                        'filename' => 'general_settings_critical_pages',
157
-                    ],
158
-                ],
159
-                'require_nonce' => false,
160
-            ],
161
-            'default'               => [
162
-                'nav'           => [
163
-                    'label' => esc_html__('Your Organization', 'event_espresso'),
164
-                    'order' => 20,
165
-                ],
166
-                'help_tabs'     => [
167
-                    'general_settings_your_organization_help_tab' => [
168
-                        'title'    => esc_html__('Your Organization', 'event_espresso'),
169
-                        'filename' => 'general_settings_your_organization',
170
-                    ],
171
-                ],
172
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
173
-                'require_nonce' => false,
174
-            ],
175
-            'admin_option_settings' => [
176
-                'nav'           => [
177
-                    'label' => esc_html__('Admin Options', 'event_espresso'),
178
-                    'order' => 60,
179
-                ],
180
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
181
-                'help_tabs'     => [
182
-                    'general_settings_admin_options_help_tab' => [
183
-                        'title'    => esc_html__('Admin Options', 'event_espresso'),
184
-                        'filename' => 'general_settings_admin_options',
185
-                    ],
186
-                ],
187
-                'require_nonce' => false,
188
-            ],
189
-            'country_settings'      => [
190
-                'nav'           => [
191
-                    'label' => esc_html__('Countries', 'event_espresso'),
192
-                    'order' => 70,
193
-                ],
194
-                'help_tabs'     => [
195
-                    'general_settings_countries_help_tab' => [
196
-                        'title'    => esc_html__('Countries', 'event_espresso'),
197
-                        'filename' => 'general_settings_countries',
198
-                    ],
199
-                ],
200
-                'require_nonce' => false,
201
-            ],
202
-            'privacy_settings'      => [
203
-                'nav'           => [
204
-                    'label' => esc_html__('Privacy', 'event_espresso'),
205
-                    'order' => 80,
206
-                ],
207
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
208
-                'require_nonce' => false,
209
-            ],
210
-        ];
211
-    }
212
-
213
-
214
-    protected function _add_screen_options()
215
-    {
216
-    }
217
-
218
-
219
-    protected function _add_feature_pointers()
220
-    {
221
-    }
222
-
223
-
224
-    /**
225
-     * Enqueue global scripts and styles for all routes in the General Settings Admin Pages.
226
-     */
227
-    public function load_scripts_styles()
228
-    {
229
-        // styles
230
-        wp_enqueue_style('espresso-ui-theme');
231
-        // scripts
232
-        wp_enqueue_script('ee_admin_js');
233
-    }
234
-
235
-
236
-    /**
237
-     * Execute logic running on `admin_init`
238
-     */
239
-    public function admin_init()
240
-    {
241
-        $this->core_config = EE_Registry::instance()->CFG->core;
242
-
243
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = wp_strip_all_tags(
244
-            esc_html__(
245
-                'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
246
-                'event_espresso'
247
-            )
248
-        );
249
-        EE_Registry::$i18n_js_strings['error_occurred']          = wp_strip_all_tags(
250
-            esc_html__(
251
-                'An error occurred! Please refresh the page and try again.',
252
-                'event_espresso'
253
-            )
254
-        );
255
-        EE_Registry::$i18n_js_strings['confirm_delete_state']    = wp_strip_all_tags(
256
-            esc_html__(
257
-                'Are you sure you want to delete this State / Province?',
258
-                'event_espresso'
259
-            )
260
-        );
261
-        EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
262
-            'admin-ajax.php?page=espresso_general_settings',
263
-            is_ssl() ? 'https://' : 'http://'
264
-        );
265
-    }
266
-
267
-
268
-    public function admin_notices()
269
-    {
270
-    }
271
-
272
-
273
-    public function admin_footer_scripts()
274
-    {
275
-    }
276
-
277
-
278
-    /**
279
-     * Enqueue scripts and styles for the default route.
280
-     */
281
-    public function load_scripts_styles_default()
282
-    {
283
-        // styles
284
-        wp_enqueue_style('thickbox');
285
-        // scripts
286
-        wp_enqueue_script('media-upload');
287
-        wp_enqueue_script('thickbox');
288
-        wp_register_script(
289
-            'organization_settings',
290
-            GEN_SET_ASSETS_URL . 'your_organization_settings.js',
291
-            ['jquery', 'media-upload', 'thickbox'],
292
-            EVENT_ESPRESSO_VERSION,
293
-            true
294
-        );
295
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
296
-        wp_enqueue_script('organization_settings');
297
-        wp_enqueue_style('organization-css');
298
-        $confirm_image_delete = [
299
-            'text' => wp_strip_all_tags(
300
-                esc_html__(
301
-                    'Do you really want to delete this image? Please remember to save your settings to complete the removal.',
302
-                    'event_espresso'
303
-                )
304
-            ),
305
-        ];
306
-        wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
307
-    }
308
-
309
-
310
-    /**
311
-     * Enqueue scripts and styles for the country settings route.
312
-     */
313
-    public function load_scripts_styles_country_settings()
314
-    {
315
-        // scripts
316
-        wp_register_script(
317
-            'gen_settings_countries',
318
-            GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
319
-            ['ee_admin_js'],
320
-            EVENT_ESPRESSO_VERSION,
321
-            true
322
-        );
323
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
324
-        wp_enqueue_script('gen_settings_countries');
325
-        wp_enqueue_style('organization-css');
326
-    }
327
-
328
-
329
-    /*************        Espresso Pages        *************/
330
-    /**
331
-     * _espresso_page_settings
332
-     *
333
-     * @throws EE_Error
334
-     * @throws DomainException
335
-     * @throws DomainException
336
-     * @throws InvalidDataTypeException
337
-     * @throws InvalidArgumentException
338
-     */
339
-    protected function _espresso_page_settings()
340
-    {
341
-        // Check to make sure all of the main pages are set up properly,
342
-        // if not create the default pages and display an admin notice
343
-        EEH_Activation::verify_default_pages_exist();
344
-        $this->_transient_garbage_collection();
345
-
346
-        $this->_template_args['values']             = $this->_yes_no_values;
347
-
348
-        $this->_template_args['reg_page_id']        = $this->core_config->reg_page_id ?? null;
349
-        $this->_template_args['reg_page_obj']       = isset($this->core_config->reg_page_id)
350
-            ? get_post($this->core_config->reg_page_id)
351
-            : false;
352
-
353
-        $this->_template_args['txn_page_id']        = $this->core_config->txn_page_id ?? null;
354
-        $this->_template_args['txn_page_obj']       = isset($this->core_config->txn_page_id)
355
-            ? get_post($this->core_config->txn_page_id)
356
-            : false;
357
-
358
-        $this->_template_args['thank_you_page_id']  = $this->core_config->thank_you_page_id ?? null;
359
-        $this->_template_args['thank_you_page_obj'] = isset($this->core_config->thank_you_page_id)
360
-            ? get_post($this->core_config->thank_you_page_id)
361
-            : false;
362
-
363
-        $this->_template_args['cancel_page_id']     = $this->core_config->cancel_page_id ?? null;
364
-        $this->_template_args['cancel_page_obj']    = isset($this->core_config->cancel_page_id)
365
-            ? get_post($this->core_config->cancel_page_id)
366
-            : false;
367
-
368
-        $this->_set_add_edit_form_tags('update_espresso_page_settings');
369
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
370
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
371
-            GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
372
-            $this->_template_args,
373
-            true
374
-        );
375
-        $this->display_admin_page_with_sidebar();
376
-    }
377
-
378
-
379
-    /**
380
-     * Handler for updating espresso page settings.
381
-     *
382
-     * @throws EE_Error
383
-     */
384
-    protected function _update_espresso_page_settings()
385
-    {
386
-        $this->core_config = EE_Registry::instance()->CFG->core;
387
-        // capture incoming request data && set page IDs
388
-        $this->core_config->reg_page_id       = $this->request->getRequestParam(
389
-            'reg_page_id',
390
-            $this->core_config->reg_page_id,
391
-            DataType::INT
392
-        );
393
-        $this->core_config->txn_page_id       = $this->request->getRequestParam(
394
-            'txn_page_id',
395
-            $this->core_config->txn_page_id,
396
-            DataType::INT
397
-        );
398
-        $this->core_config->thank_you_page_id = $this->request->getRequestParam(
399
-            'thank_you_page_id',
400
-            $this->core_config->thank_you_page_id,
401
-            DataType::INT
402
-        );
403
-        $this->core_config->cancel_page_id    = $this->request->getRequestParam(
404
-            'cancel_page_id',
405
-            $this->core_config->cancel_page_id,
406
-            DataType::INT
407
-        );
408
-
409
-        $this->core_config = apply_filters(
410
-            'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core',
411
-            $this->core_config,
412
-            $this->request->requestParams()
413
-        );
414
-
415
-        $what = esc_html__('Critical Pages & Shortcodes', 'event_espresso');
416
-        $this->_redirect_after_action(
417
-            $this->_update_espresso_configuration(
418
-                $what,
419
-                $this->core_config,
420
-                __FILE__,
421
-                __FUNCTION__,
422
-                __LINE__
423
-            ),
424
-            $what,
425
-            '',
426
-            [
427
-                'action' => 'critical_pages',
428
-            ],
429
-            true
430
-        );
431
-    }
432
-
433
-
434
-    /*************        Your Organization        *************/
435
-
436
-
437
-    /**
438
-     * @throws DomainException
439
-     * @throws EE_Error
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidDataTypeException
442
-     * @throws InvalidInterfaceException
443
-     */
444
-    protected function _your_organization_settings()
445
-    {
446
-        $this->_template_args['admin_page_content'] = '';
447
-        try {
448
-            /** @var OrganizationSettings $organization_settings_form */
449
-            $organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
450
-
451
-            $this->_template_args['admin_page_content'] = EEH_HTML::div(
452
-                $organization_settings_form->display(),
453
-                '',
454
-                'padding'
455
-            );
456
-        } catch (Exception $e) {
457
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
458
-        }
459
-        $this->_set_add_edit_form_tags('update_your_organization_settings');
460
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
461
-        $this->display_admin_page_with_sidebar();
462
-    }
463
-
464
-
465
-    /**
466
-     * Handler for updating organization settings.
467
-     *
468
-     * @throws EE_Error
469
-     */
470
-    protected function _update_your_organization_settings()
471
-    {
472
-        try {
473
-            /** @var OrganizationSettings $organization_settings_form */
474
-            $organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
475
-
476
-            $success = $organization_settings_form->process($this->request->requestParams());
477
-
478
-            EE_Registry::instance()->CFG = apply_filters(
479
-                'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG',
480
-                EE_Registry::instance()->CFG
481
-            );
482
-        } catch (Exception $e) {
483
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
484
-            $success = false;
485
-        }
486
-
487
-        if ($success) {
488
-            $success = $this->_update_espresso_configuration(
489
-                esc_html__('Your Organization Settings', 'event_espresso'),
490
-                EE_Registry::instance()->CFG,
491
-                __FILE__,
492
-                __FUNCTION__,
493
-                __LINE__
494
-            );
495
-        }
496
-
497
-        $this->_redirect_after_action($success, '', '', ['action' => 'default'], true);
498
-    }
499
-
500
-
501
-
502
-    /*************        Admin Options        *************/
503
-
504
-
505
-    /**
506
-     * _admin_option_settings
507
-     *
508
-     * @throws EE_Error
509
-     * @throws LogicException
510
-     */
511
-    protected function _admin_option_settings()
512
-    {
513
-        $this->_template_args['admin_page_content'] = '';
514
-        try {
515
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
516
-            // still need this for the old school form in Extend_General_Settings_Admin_Page
517
-            $this->_template_args['values'] = $this->_yes_no_values;
518
-            // also need to account for the do_action that was in the old template
519
-            $admin_options_settings_form->setTemplateArgs($this->_template_args);
520
-            $this->_template_args['admin_page_content'] = EEH_HTML::div(
521
-                $admin_options_settings_form->display(),
522
-                '',
523
-                'padding'
524
-            );
525
-        } catch (Exception $e) {
526
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
527
-        }
528
-        $this->_set_add_edit_form_tags('update_admin_option_settings');
529
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
530
-        $this->display_admin_page_with_sidebar();
531
-    }
532
-
533
-
534
-    /**
535
-     * _update_admin_option_settings
536
-     *
537
-     * @throws EE_Error
538
-     * @throws InvalidDataTypeException
539
-     * @throws InvalidFormSubmissionException
540
-     * @throws InvalidArgumentException
541
-     * @throws LogicException
542
-     */
543
-    protected function _update_admin_option_settings()
544
-    {
545
-        try {
546
-            $admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
547
-            $admin_options_settings_form->process(
548
-                $this->request->getRequestParam(
549
-                    $admin_options_settings_form->slug(),
550
-                    [],
551
-                    DataType::STRING,
552
-                    true
553
-                )
554
-            );
555
-            EE_Registry::instance()->CFG->admin = apply_filters(
556
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
557
-                EE_Registry::instance()->CFG->admin
558
-            );
559
-        } catch (Exception $e) {
560
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
561
-        }
562
-        $this->_redirect_after_action(
563
-            apply_filters(
564
-                'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
565
-                $this->_update_espresso_configuration(
566
-                    esc_html__('Admin Options', 'event_espresso'),
567
-                    EE_Registry::instance()->CFG->admin,
568
-                    __FILE__,
569
-                    __FUNCTION__,
570
-                    __LINE__
571
-                )
572
-            ),
573
-            esc_html__('Admin Options', 'event_espresso'),
574
-            'updated',
575
-            ['action' => 'admin_option_settings']
576
-        );
577
-    }
578
-
579
-
580
-    /*************        Countries        *************/
581
-
582
-
583
-    /**
584
-     * @param string|null $default
585
-     * @return string
586
-     */
587
-    protected function getCountryISO(?string $default = null): string
588
-    {
589
-        $default = $default ?? $this->getCountryIsoForSite();
590
-        $CNT_ISO = $this->request->getRequestParam('country', $default);
591
-        return strtoupper($CNT_ISO);
592
-    }
593
-
594
-
595
-    /**
596
-     * @return string
597
-     */
598
-    protected function getCountryIsoForSite(): string
599
-    {
600
-        return ! empty(EE_Registry::instance()->CFG->organization->CNT_ISO)
601
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
602
-            : 'US';
603
-    }
604
-
605
-
606
-    /**
607
-     * @param string          $CNT_ISO
608
-     * @param EE_Country|null $country
609
-     * @return EE_Base_Class|EE_Country
610
-     * @throws EE_Error
611
-     * @throws InvalidArgumentException
612
-     * @throws InvalidDataTypeException
613
-     * @throws InvalidInterfaceException
614
-     * @throws ReflectionException
615
-     */
616
-    protected function verifyOrGetCountryFromIso(string $CNT_ISO, ?EE_Country $country = null)
617
-    {
618
-        /** @var EE_Country $country */
619
-        return $country instanceof EE_Country && $country->ID() === $CNT_ISO
620
-            ? $country
621
-            : EEM_Country::instance()->get_one_by_ID($CNT_ISO);
622
-    }
623
-
624
-
625
-    /**
626
-     * Output Country Settings view.
627
-     *
628
-     * @throws DomainException
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    protected function _country_settings()
636
-    {
637
-        $CNT_ISO = $this->getCountryISO();
638
-
639
-        $this->_template_args['values']    = $this->_yes_no_values;
640
-        $this->_template_args['countries'] = new EE_Question_Form_Input(
641
-            EE_Question::new_instance(
642
-                [
643
-                  'QST_ID'           => 0,
644
-                  'QST_display_text' => esc_html__('Select Country', 'event_espresso'),
645
-                  'QST_system'       => 'admin-country',
646
-                ]
647
-            ),
648
-            EE_Answer::new_instance(
649
-                [
650
-                    'ANS_ID'    => 0,
651
-                    'ANS_value' => $CNT_ISO,
652
-                ]
653
-            ),
654
-            [
655
-                'input_id'       => 'country',
656
-                'input_name'     => 'country',
657
-                'input_prefix'   => '',
658
-                'append_qstn_id' => false,
659
-            ]
660
-        );
661
-
662
-        $country = $this->verifyOrGetCountryFromIso($CNT_ISO);
663
-        add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10);
664
-        add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10);
665
-        $this->_template_args['country_details_settings'] = $this->display_country_settings(
666
-            $country->ID(),
667
-            $country
668
-        );
669
-        $this->_template_args['country_states_settings']  = $this->display_country_states(
670
-            $country->ID(),
671
-            $country
672
-        );
673
-        $this->_template_args['CNT_name_for_site']        = $country->name();
674
-
675
-        $this->_set_add_edit_form_tags('update_country_settings');
676
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
677
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
678
-            GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
679
-            $this->_template_args,
680
-            true
681
-        );
682
-        $this->display_admin_page_with_no_sidebar();
683
-    }
684
-
685
-
686
-    /**
687
-     * @param string          $CNT_ISO
688
-     * @param EE_Country|null $country
689
-     * @return string
690
-     * @throws DomainException
691
-     * @throws EE_Error
692
-     * @throws InvalidArgumentException
693
-     * @throws InvalidDataTypeException
694
-     * @throws InvalidInterfaceException
695
-     * @throws ReflectionException
696
-     */
697
-    public function display_country_settings(string $CNT_ISO = '', ?EE_Country $country = null): string
698
-    {
699
-        $CNT_ISO          = $this->getCountryISO($CNT_ISO);
700
-        $CNT_ISO_for_site = $this->getCountryIsoForSite();
701
-
702
-        if (! $CNT_ISO) {
703
-            return '';
704
-        }
705
-
706
-        // for ajax
707
-        remove_all_filters('FHEE__EEH_Form_Fields__label_html');
708
-        remove_all_filters('FHEE__EEH_Form_Fields__input_html');
709
-        add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10, 2);
710
-        add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10, 2);
711
-        $country                                  = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
712
-        $CNT_cur_disabled                         = $CNT_ISO !== $CNT_ISO_for_site;
713
-        $this->_template_args['CNT_cur_disabled'] = $CNT_cur_disabled;
714
-
715
-        $country_input_types            = [
716
-            'CNT_active'      => [
717
-                'type'             => 'RADIO_BTN',
718
-                'input_name'       => "cntry[$CNT_ISO]",
719
-                'class'            => '',
720
-                'options'          => $this->_yes_no_values,
721
-                'use_desc_4_label' => true,
722
-            ],
723
-            'CNT_ISO'         => [
724
-                'type'       => 'TEXT',
725
-                'input_name' => "cntry[$CNT_ISO]",
726
-                'class'      => 'ee-input-width--small',
727
-            ],
728
-            'CNT_ISO3'        => [
729
-                'type'       => 'TEXT',
730
-                'input_name' => "cntry[$CNT_ISO]",
731
-                'class'      => 'ee-input-width--small',
732
-            ],
733
-            // 'RGN_ID'          => [
734
-            //     'type'       => 'TEXT',
735
-            //     'input_name' => "cntry[$CNT_ISO]",
736
-            //     'class'      => 'ee-input-width--small',
737
-            // ],
738
-            'CNT_name'        => [
739
-                'type'       => 'TEXT',
740
-                'input_name' => "cntry[$CNT_ISO]",
741
-                'class'      => 'ee-input-width--big',
742
-            ],
743
-            'CNT_cur_code'    => [
744
-                'type'       => 'TEXT',
745
-                'input_name' => "cntry[$CNT_ISO]",
746
-                'class'      => 'ee-input-width--small',
747
-                'disabled'   => $CNT_cur_disabled,
748
-            ],
749
-            'CNT_cur_single'  => [
750
-                'type'       => 'TEXT',
751
-                'input_name' => "cntry[$CNT_ISO]",
752
-                'class'      => 'ee-input-width--reg',
753
-                'disabled'   => $CNT_cur_disabled,
754
-            ],
755
-            'CNT_cur_plural'  => [
756
-                'type'       => 'TEXT',
757
-                'input_name' => "cntry[$CNT_ISO]",
758
-                'class'      => 'ee-input-width--reg',
759
-                'disabled'   => $CNT_cur_disabled,
760
-            ],
761
-            'CNT_cur_sign'    => [
762
-                'type'         => 'TEXT',
763
-                'input_name'   => "cntry[$CNT_ISO]",
764
-                'class'        => 'ee-input-width--small',
765
-                'htmlentities' => false,
766
-                'disabled'     => $CNT_cur_disabled,
767
-            ],
768
-            'CNT_cur_sign_b4' => [
769
-                'type'             => 'RADIO_BTN',
770
-                'input_name'       => "cntry[$CNT_ISO]",
771
-                'class'            => '',
772
-                'options'          => $this->_yes_no_values,
773
-                'use_desc_4_label' => true,
774
-                'disabled'         => $CNT_cur_disabled,
775
-            ],
776
-            'CNT_cur_dec_plc' => [
777
-                'type'       => 'RADIO_BTN',
778
-                'input_name' => "cntry[$CNT_ISO]",
779
-                'class'      => '',
780
-                'options'    => [
781
-                    ['id' => 0, 'text' => ''],
782
-                    ['id' => 1, 'text' => ''],
783
-                    ['id' => 2, 'text' => ''],
784
-                    ['id' => 3, 'text' => ''],
785
-                ],
786
-                'disabled'   => $CNT_cur_disabled,
787
-            ],
788
-            'CNT_cur_dec_mrk' => [
789
-                'type'             => 'RADIO_BTN',
790
-                'input_name'       => "cntry[$CNT_ISO]",
791
-                'class'            => '',
792
-                'options'          => [
793
-                    [
794
-                        'id'   => ',',
795
-                        'text' => esc_html__(', (comma)', 'event_espresso'),
796
-                    ],
797
-                    ['id' => '.', 'text' => esc_html__('. (decimal)', 'event_espresso')],
798
-                ],
799
-                'use_desc_4_label' => true,
800
-                'disabled'         => $CNT_cur_disabled,
801
-            ],
802
-            'CNT_cur_thsnds'  => [
803
-                'type'             => 'RADIO_BTN',
804
-                'input_name'       => "cntry[$CNT_ISO]",
805
-                'class'            => '',
806
-                'options'          => [
807
-                    [
808
-                        'id'   => ',',
809
-                        'text' => esc_html__(', (comma)', 'event_espresso'),
810
-                    ],
811
-                    [
812
-                        'id'   => '.',
813
-                        'text' => esc_html__('. (decimal)', 'event_espresso'),
814
-                    ],
815
-                    [
816
-                        'id'   => '&nbsp;',
817
-                        'text' => esc_html__('(space)', 'event_espresso'),
818
-                    ],
819
-                ],
820
-                'use_desc_4_label' => true,
821
-                'disabled'         => $CNT_cur_disabled,
822
-            ],
823
-            'CNT_tel_code'    => [
824
-                'type'       => 'TEXT',
825
-                'input_name' => "cntry[$CNT_ISO]",
826
-                'class'      => 'ee-input-width--small',
827
-            ],
828
-            'CNT_is_EU'       => [
829
-                'type'             => 'RADIO_BTN',
830
-                'input_name'       => "cntry[$CNT_ISO]",
831
-                'class'            => '',
832
-                'options'          => $this->_yes_no_values,
833
-                'use_desc_4_label' => true,
834
-            ],
835
-        ];
836
-        $this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object(
837
-            $country,
838
-            $country_input_types
839
-        );
840
-        $country_details_settings       = EEH_Template::display_template(
841
-            GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
842
-            $this->_template_args,
843
-            true
844
-        );
845
-
846
-        if (defined('DOING_AJAX')) {
847
-            $notices = EE_Error::get_notices(false, false, false);
848
-            echo wp_json_encode(
849
-                [
850
-                    'return_data' => $country_details_settings,
851
-                    'success'     => $notices['success'],
852
-                    'errors'      => $notices['errors'],
853
-                ]
854
-            );
855
-            die();
856
-        }
857
-        return $country_details_settings;
858
-    }
859
-
860
-
861
-    /**
862
-     * @param string          $CNT_ISO
863
-     * @param EE_Country|null $country
864
-     * @return string
865
-     * @throws DomainException
866
-     * @throws EE_Error
867
-     * @throws InvalidArgumentException
868
-     * @throws InvalidDataTypeException
869
-     * @throws InvalidInterfaceException
870
-     * @throws ReflectionException
871
-     */
872
-    public function display_country_states(string $CNT_ISO = '', ?EE_Country $country = null): string
873
-    {
874
-        $CNT_ISO = $this->getCountryISO($CNT_ISO);
875
-        if (! $CNT_ISO) {
876
-            return '';
877
-        }
878
-        // for ajax
879
-        remove_all_filters('FHEE__EEH_Form_Fields__label_html');
880
-        remove_all_filters('FHEE__EEH_Form_Fields__input_html');
881
-        add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'state_form_field_label_wrap'], 10, 2);
882
-        add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'state_form_field_input__wrap'], 10);
883
-        $states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
884
-        if (empty($states)) {
885
-            /** @var EventEspresso\core\services\address\CountrySubRegionDao $countrySubRegionDao */
886
-            $countrySubRegionDao = $this->loader->getShared(
887
-                'EventEspresso\core\services\address\CountrySubRegionDao'
888
-            );
889
-            if ($countrySubRegionDao instanceof EventEspresso\core\services\address\CountrySubRegionDao) {
890
-                $country = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
891
-                if ($countrySubRegionDao->saveCountrySubRegions($country)) {
892
-                    $states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
893
-                }
894
-            }
895
-        }
896
-        if (is_array($states)) {
897
-            foreach ($states as $STA_ID => $state) {
898
-                if ($state instanceof EE_State) {
899
-                    $inputs = EE_Question_Form_Input::generate_question_form_inputs_for_object(
900
-                        $state,
901
-                        [
902
-                            'STA_abbrev' => [
903
-                                'type'             => 'TEXT',
904
-                                'label'            => esc_html__('Code', 'event_espresso'),
905
-                                'input_name'       => "states[$STA_ID]",
906
-                                'class'            => 'ee-input-width--tiny',
907
-                                'add_mobile_label' => true,
908
-                            ],
909
-                            'STA_name'   => [
910
-                                'type'             => 'TEXT',
911
-                                'label'            => esc_html__('Name', 'event_espresso'),
912
-                                'input_name'       => "states[$STA_ID]",
913
-                                'class'            => 'ee-input-width--big',
914
-                                'add_mobile_label' => true,
915
-                            ],
916
-                            'STA_active' => [
917
-                                'type'             => 'RADIO_BTN',
918
-                                'label'            => esc_html__('State Appears in Dropdown Select Lists', 'event_espresso'),
919
-                                'input_name'       => "states[$STA_ID]",
920
-                                'options'          => $this->_yes_no_values,
921
-                                'use_desc_4_label' => true,
922
-                                'add_mobile_label' => true,
923
-                            ],
924
-                        ]
925
-                    );
926
-
927
-                    $delete_state_url = EE_Admin_Page::add_query_args_and_nonce(
928
-                        [
929
-                            'action'     => 'delete_state',
930
-                            'STA_ID'     => $STA_ID,
931
-                            'CNT_ISO'    => $CNT_ISO,
932
-                            'STA_abbrev' => $state->abbrev(),
933
-                        ],
934
-                        GEN_SET_ADMIN_URL
935
-                    );
936
-
937
-                    $this->_template_args['states'][ $STA_ID ]['inputs']           = $inputs;
938
-                    $this->_template_args['states'][ $STA_ID ]['delete_state_url'] = $delete_state_url;
939
-                }
940
-            }
941
-        } else {
942
-            $this->_template_args['states'] = false;
943
-        }
944
-
945
-        $this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(
946
-            ['action' => 'add_new_state'],
947
-            GEN_SET_ADMIN_URL
948
-        );
949
-
950
-        $state_details_settings = EEH_Template::display_template(
951
-            GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
952
-            $this->_template_args,
953
-            true
954
-        );
955
-
956
-        if (defined('DOING_AJAX')) {
957
-            $notices = EE_Error::get_notices(false, false, false);
958
-            echo wp_json_encode(
959
-                [
960
-                    'return_data' => $state_details_settings,
961
-                    'success'     => $notices['success'],
962
-                    'errors'      => $notices['errors'],
963
-                ]
964
-            );
965
-            die();
966
-        }
967
-        return $state_details_settings;
968
-    }
969
-
970
-
971
-    /**
972
-     * @return void
973
-     * @throws EE_Error
974
-     * @throws InvalidArgumentException
975
-     * @throws InvalidDataTypeException
976
-     * @throws InvalidInterfaceException
977
-     * @throws ReflectionException
978
-     */
979
-    public function add_new_state()
980
-    {
981
-        $success = true;
982
-        $CNT_ISO = $this->getCountryISO('');
983
-        if (! $CNT_ISO) {
984
-            EE_Error::add_error(
985
-                esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
986
-                __FILE__,
987
-                __FUNCTION__,
988
-                __LINE__
989
-            );
990
-            $success = false;
991
-        }
992
-        $STA_abbrev = $this->request->getRequestParam('STA_abbrev');
993
-        if (! $STA_abbrev) {
994
-            EE_Error::add_error(
995
-                esc_html__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
996
-                __FILE__,
997
-                __FUNCTION__,
998
-                __LINE__
999
-            );
1000
-            $success = false;
1001
-        }
1002
-        $STA_name = $this->request->getRequestParam('STA_name');
1003
-        if (! $STA_name) {
1004
-            EE_Error::add_error(
1005
-                esc_html__('No State name or an invalid State name was received.', 'event_espresso'),
1006
-                __FILE__,
1007
-                __FUNCTION__,
1008
-                __LINE__
1009
-            );
1010
-            $success = false;
1011
-        }
1012
-
1013
-        if ($success) {
1014
-            $cols_n_values = [
1015
-                'CNT_ISO'    => $CNT_ISO,
1016
-                'STA_abbrev' => $STA_abbrev,
1017
-                'STA_name'   => $STA_name,
1018
-                'STA_active' => true,
1019
-            ];
1020
-            $success       = EEM_State::instance()->insert($cols_n_values);
1021
-            EE_Error::add_success(esc_html__('The State was added successfully.', 'event_espresso'));
1022
-        }
1023
-
1024
-        if (defined('DOING_AJAX')) {
1025
-            $notices = EE_Error::get_notices(false, false, false);
1026
-            echo wp_json_encode(array_merge($notices, ['return_data' => $CNT_ISO]));
1027
-            die();
1028
-        }
1029
-        $this->_redirect_after_action(
1030
-            $success,
1031
-            esc_html__('State', 'event_espresso'),
1032
-            'added',
1033
-            ['action' => 'country_settings']
1034
-        );
1035
-    }
1036
-
1037
-
1038
-    /**
1039
-     * @return void
1040
-     * @throws EE_Error
1041
-     * @throws InvalidArgumentException
1042
-     * @throws InvalidDataTypeException
1043
-     * @throws InvalidInterfaceException
1044
-     * @throws ReflectionException
1045
-     */
1046
-    public function delete_state()
1047
-    {
1048
-        $CNT_ISO    = $this->getCountryISO();
1049
-        $STA_ID     = $this->request->getRequestParam('STA_ID');
1050
-        $STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1051
-
1052
-        if (! $STA_ID) {
1053
-            EE_Error::add_error(
1054
-                esc_html__('No State ID or an invalid State ID was received.', 'event_espresso'),
1055
-                __FILE__,
1056
-                __FUNCTION__,
1057
-                __LINE__
1058
-            );
1059
-            return;
1060
-        }
1061
-
1062
-        $success = EEM_State::instance()->delete_by_ID($STA_ID);
1063
-        if ($success !== false) {
1064
-            do_action(
1065
-                'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
1066
-                $CNT_ISO,
1067
-                $STA_ID,
1068
-                ['STA_abbrev' => $STA_abbrev]
1069
-            );
1070
-            EE_Error::add_success(esc_html__('The State was deleted successfully.', 'event_espresso'));
1071
-        }
1072
-        if (defined('DOING_AJAX')) {
1073
-            $notices                = EE_Error::get_notices(false);
1074
-            $notices['return_data'] = true;
1075
-            echo wp_json_encode($notices);
1076
-            die();
1077
-        }
1078
-        $this->_redirect_after_action(
1079
-            $success,
1080
-            esc_html__('State', 'event_espresso'),
1081
-            'deleted',
1082
-            ['action' => 'country_settings']
1083
-        );
1084
-    }
1085
-
1086
-
1087
-    /**
1088
-     * @return void
1089
-     * @throws EE_Error
1090
-     * @throws InvalidArgumentException
1091
-     * @throws InvalidDataTypeException
1092
-     * @throws InvalidInterfaceException
1093
-     * @throws ReflectionException
1094
-     */
1095
-    protected function _update_country_settings()
1096
-    {
1097
-        $CNT_ISO = $this->getCountryISO();
1098
-        if (! $CNT_ISO) {
1099
-            EE_Error::add_error(
1100
-                esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1101
-                __FILE__,
1102
-                __FUNCTION__,
1103
-                __LINE__
1104
-            );
1105
-            return;
1106
-        }
1107
-
1108
-        $country = $this->verifyOrGetCountryFromIso($CNT_ISO);
1109
-
1110
-        $cols_n_values                    = [];
1111
-        $cols_n_values['CNT_ISO3']        = strtoupper(
1112
-            $this->request->getRequestParam('cntry', '', $country->ISO3())
1113
-        );
1114
-        $cols_n_values['CNT_name']        =
1115
-            $this->request->getRequestParam("cntry[$CNT_ISO][CNT_name]", $country->name());
1116
-        $cols_n_values['CNT_cur_code']    = strtoupper(
1117
-            $this->request->getRequestParam(
1118
-                "cntry[$CNT_ISO][CNT_cur_code]",
1119
-                $country->currency_code()
1120
-            )
1121
-        );
1122
-        $cols_n_values['CNT_cur_single']  = $this->request->getRequestParam(
1123
-            "cntry[$CNT_ISO][CNT_cur_single]",
1124
-            $country->currency_name_single()
1125
-        );
1126
-        $cols_n_values['CNT_cur_plural']  = $this->request->getRequestParam(
1127
-            "cntry[$CNT_ISO][CNT_cur_plural]",
1128
-            $country->currency_name_plural()
1129
-        );
1130
-        $cols_n_values['CNT_cur_sign']    = $this->request->getRequestParam(
1131
-            "cntry[$CNT_ISO][CNT_cur_sign]",
1132
-            $country->currency_sign()
1133
-        );
1134
-        $cols_n_values['CNT_cur_sign_b4'] = $this->request->getRequestParam(
1135
-            "cntry[$CNT_ISO][CNT_cur_sign_b4]",
1136
-            $country->currency_sign_before(),
1137
-            DataType::BOOL
1138
-        );
1139
-        $cols_n_values['CNT_cur_dec_plc'] = $this->request->getRequestParam(
1140
-            "cntry[$CNT_ISO][CNT_cur_dec_plc]",
1141
-            $country->currency_decimal_places()
1142
-        );
1143
-        $cols_n_values['CNT_cur_dec_mrk'] = $this->request->getRequestParam(
1144
-            "cntry[$CNT_ISO][CNT_cur_dec_mrk]",
1145
-            $country->currency_decimal_mark()
1146
-        );
1147
-        $cols_n_values['CNT_cur_thsnds']  = $this->request->getRequestParam(
1148
-            "cntry[$CNT_ISO][CNT_cur_thsnds]",
1149
-            $country->currency_thousands_separator()
1150
-        );
1151
-        $cols_n_values['CNT_tel_code']    = $this->request->getRequestParam(
1152
-            "cntry[$CNT_ISO][CNT_tel_code]",
1153
-            $country->telephoneCode()
1154
-        );
1155
-        $cols_n_values['CNT_active']      = $this->request->getRequestParam(
1156
-            "cntry[$CNT_ISO][CNT_active]",
1157
-            $country->isActive(),
1158
-            DataType::BOOL
1159
-        );
1160
-
1161
-        // allow filtering of country data
1162
-        $cols_n_values = apply_filters(
1163
-            'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values',
1164
-            $cols_n_values
1165
-        );
1166
-
1167
-        // where values
1168
-        $where_cols_n_values = [['CNT_ISO' => $CNT_ISO]];
1169
-        // run the update
1170
-        $success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
1171
-
1172
-        // allow filtering of states data
1173
-        $states = apply_filters(
1174
-            'FHEE__General_Settings_Admin_Page___update_country_settings__states',
1175
-            $this->request->getRequestParam('states', [], DataType::STRING, true)
1176
-        );
1177
-
1178
-        if (! empty($states) && $success !== false) {
1179
-            // loop thru state data ( looks like : states[75][STA_name] )
1180
-            foreach ($states as $STA_ID => $state) {
1181
-                $cols_n_values = [
1182
-                    'CNT_ISO'    => $CNT_ISO,
1183
-                    'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
1184
-                    'STA_name'   => sanitize_text_field($state['STA_name']),
1185
-                    'STA_active' => filter_var($state['STA_active'], FILTER_VALIDATE_BOOLEAN),
1186
-                ];
1187
-                // where values
1188
-                $where_cols_n_values = [['STA_ID' => $STA_ID]];
1189
-                // run the update
1190
-                $success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
1191
-                if ($success !== false) {
1192
-                    do_action(
1193
-                        'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
1194
-                        $CNT_ISO,
1195
-                        $STA_ID,
1196
-                        $cols_n_values
1197
-                    );
1198
-                }
1199
-            }
1200
-        }
1201
-        // check if country being edited matches org option country, and if so, then  update EE_Config with new settings
1202
-        if (
1203
-            isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
1204
-            && $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO
1205
-        ) {
1206
-            EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
1207
-            EE_Registry::instance()->CFG->update_espresso_config();
1208
-        }
1209
-
1210
-        if ($success !== false) {
1211
-            EE_Error::add_success(
1212
-                esc_html__('Country Settings updated successfully.', 'event_espresso')
1213
-            );
1214
-        }
1215
-        $this->_redirect_after_action(
1216
-            $success,
1217
-            '',
1218
-            '',
1219
-            ['action' => 'country_settings', 'country' => $CNT_ISO],
1220
-            true
1221
-        );
1222
-    }
1223
-
1224
-
1225
-    /**
1226
-     * form_form_field_label_wrap
1227
-     *
1228
-     * @param string $label
1229
-     * @return string
1230
-     */
1231
-    public function country_form_field_label_wrap(string $label): string
1232
-    {
1233
-        return '
22
+	/**
23
+	 * @var EE_Core_Config
24
+	 */
25
+	public $core_config;
26
+
27
+
28
+	/**
29
+	 * Initialize basic properties.
30
+	 */
31
+	protected function _init_page_props()
32
+	{
33
+		$this->page_slug        = GEN_SET_PG_SLUG;
34
+		$this->page_label       = GEN_SET_LABEL;
35
+		$this->_admin_base_url  = GEN_SET_ADMIN_URL;
36
+		$this->_admin_base_path = GEN_SET_ADMIN;
37
+	}
38
+
39
+
40
+	/**
41
+	 * Set ajax hooks
42
+	 */
43
+	protected function _ajax_hooks()
44
+	{
45
+		add_action('wp_ajax_espresso_display_country_settings', [$this, 'display_country_settings']);
46
+		add_action('wp_ajax_espresso_display_country_states', [$this, 'display_country_states']);
47
+		add_action('wp_ajax_espresso_delete_state', [$this, 'delete_state'], 10, 3);
48
+		add_action('wp_ajax_espresso_add_new_state', [$this, 'add_new_state']);
49
+	}
50
+
51
+
52
+	/**
53
+	 * More page properties initialization.
54
+	 */
55
+	protected function _define_page_props()
56
+	{
57
+		$this->_admin_page_title = GEN_SET_LABEL;
58
+		$this->_labels           = ['publishbox' => esc_html__('Update Settings', 'event_espresso')];
59
+	}
60
+
61
+
62
+	/**
63
+	 * Set page routes property.
64
+	 */
65
+	protected function _set_page_routes()
66
+	{
67
+		$this->_page_routes = [
68
+			'critical_pages'                => [
69
+				'func'       => '_espresso_page_settings',
70
+				'capability' => 'manage_options',
71
+			],
72
+			'update_espresso_page_settings' => [
73
+				'func'       => '_update_espresso_page_settings',
74
+				'capability' => 'manage_options',
75
+				'noheader'   => true,
76
+			],
77
+			'default'                       => [
78
+				'func'       => '_your_organization_settings',
79
+				'capability' => 'manage_options',
80
+			],
81
+
82
+			'update_your_organization_settings' => [
83
+				'func'       => '_update_your_organization_settings',
84
+				'capability' => 'manage_options',
85
+				'noheader'   => true,
86
+			],
87
+
88
+			'admin_option_settings' => [
89
+				'func'       => '_admin_option_settings',
90
+				'capability' => 'manage_options',
91
+			],
92
+
93
+			'update_admin_option_settings' => [
94
+				'func'       => '_update_admin_option_settings',
95
+				'capability' => 'manage_options',
96
+				'noheader'   => true,
97
+			],
98
+
99
+			'country_settings' => [
100
+				'func'       => '_country_settings',
101
+				'capability' => 'manage_options',
102
+			],
103
+
104
+			'update_country_settings' => [
105
+				'func'       => '_update_country_settings',
106
+				'capability' => 'manage_options',
107
+				'noheader'   => true,
108
+			],
109
+
110
+			'display_country_settings' => [
111
+				'func'       => 'display_country_settings',
112
+				'capability' => 'manage_options',
113
+				'noheader'   => true,
114
+			],
115
+
116
+			'add_new_state' => [
117
+				'func'       => 'add_new_state',
118
+				'capability' => 'manage_options',
119
+				'noheader'   => true,
120
+			],
121
+
122
+			'delete_state'            => [
123
+				'func'       => 'delete_state',
124
+				'capability' => 'manage_options',
125
+				'noheader'   => true,
126
+			],
127
+			'privacy_settings'        => [
128
+				'func'       => 'privacySettings',
129
+				'capability' => 'manage_options',
130
+			],
131
+			'update_privacy_settings' => [
132
+				'func'               => 'updatePrivacySettings',
133
+				'capability'         => 'manage_options',
134
+				'noheader'           => true,
135
+				'headers_sent_route' => 'privacy_settings',
136
+			],
137
+		];
138
+	}
139
+
140
+
141
+	/**
142
+	 * Set page configuration property
143
+	 */
144
+	protected function _set_page_config()
145
+	{
146
+		$this->_page_config = [
147
+			'critical_pages'        => [
148
+				'nav'           => [
149
+					'label' => esc_html__('Critical Pages', 'event_espresso'),
150
+					'order' => 50,
151
+				],
152
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
153
+				'help_tabs'     => [
154
+					'general_settings_critical_pages_help_tab' => [
155
+						'title'    => esc_html__('Critical Pages', 'event_espresso'),
156
+						'filename' => 'general_settings_critical_pages',
157
+					],
158
+				],
159
+				'require_nonce' => false,
160
+			],
161
+			'default'               => [
162
+				'nav'           => [
163
+					'label' => esc_html__('Your Organization', 'event_espresso'),
164
+					'order' => 20,
165
+				],
166
+				'help_tabs'     => [
167
+					'general_settings_your_organization_help_tab' => [
168
+						'title'    => esc_html__('Your Organization', 'event_espresso'),
169
+						'filename' => 'general_settings_your_organization',
170
+					],
171
+				],
172
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
173
+				'require_nonce' => false,
174
+			],
175
+			'admin_option_settings' => [
176
+				'nav'           => [
177
+					'label' => esc_html__('Admin Options', 'event_espresso'),
178
+					'order' => 60,
179
+				],
180
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
181
+				'help_tabs'     => [
182
+					'general_settings_admin_options_help_tab' => [
183
+						'title'    => esc_html__('Admin Options', 'event_espresso'),
184
+						'filename' => 'general_settings_admin_options',
185
+					],
186
+				],
187
+				'require_nonce' => false,
188
+			],
189
+			'country_settings'      => [
190
+				'nav'           => [
191
+					'label' => esc_html__('Countries', 'event_espresso'),
192
+					'order' => 70,
193
+				],
194
+				'help_tabs'     => [
195
+					'general_settings_countries_help_tab' => [
196
+						'title'    => esc_html__('Countries', 'event_espresso'),
197
+						'filename' => 'general_settings_countries',
198
+					],
199
+				],
200
+				'require_nonce' => false,
201
+			],
202
+			'privacy_settings'      => [
203
+				'nav'           => [
204
+					'label' => esc_html__('Privacy', 'event_espresso'),
205
+					'order' => 80,
206
+				],
207
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, ['_publish_post_box']),
208
+				'require_nonce' => false,
209
+			],
210
+		];
211
+	}
212
+
213
+
214
+	protected function _add_screen_options()
215
+	{
216
+	}
217
+
218
+
219
+	protected function _add_feature_pointers()
220
+	{
221
+	}
222
+
223
+
224
+	/**
225
+	 * Enqueue global scripts and styles for all routes in the General Settings Admin Pages.
226
+	 */
227
+	public function load_scripts_styles()
228
+	{
229
+		// styles
230
+		wp_enqueue_style('espresso-ui-theme');
231
+		// scripts
232
+		wp_enqueue_script('ee_admin_js');
233
+	}
234
+
235
+
236
+	/**
237
+	 * Execute logic running on `admin_init`
238
+	 */
239
+	public function admin_init()
240
+	{
241
+		$this->core_config = EE_Registry::instance()->CFG->core;
242
+
243
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = wp_strip_all_tags(
244
+			esc_html__(
245
+				'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
246
+				'event_espresso'
247
+			)
248
+		);
249
+		EE_Registry::$i18n_js_strings['error_occurred']          = wp_strip_all_tags(
250
+			esc_html__(
251
+				'An error occurred! Please refresh the page and try again.',
252
+				'event_espresso'
253
+			)
254
+		);
255
+		EE_Registry::$i18n_js_strings['confirm_delete_state']    = wp_strip_all_tags(
256
+			esc_html__(
257
+				'Are you sure you want to delete this State / Province?',
258
+				'event_espresso'
259
+			)
260
+		);
261
+		EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
262
+			'admin-ajax.php?page=espresso_general_settings',
263
+			is_ssl() ? 'https://' : 'http://'
264
+		);
265
+	}
266
+
267
+
268
+	public function admin_notices()
269
+	{
270
+	}
271
+
272
+
273
+	public function admin_footer_scripts()
274
+	{
275
+	}
276
+
277
+
278
+	/**
279
+	 * Enqueue scripts and styles for the default route.
280
+	 */
281
+	public function load_scripts_styles_default()
282
+	{
283
+		// styles
284
+		wp_enqueue_style('thickbox');
285
+		// scripts
286
+		wp_enqueue_script('media-upload');
287
+		wp_enqueue_script('thickbox');
288
+		wp_register_script(
289
+			'organization_settings',
290
+			GEN_SET_ASSETS_URL . 'your_organization_settings.js',
291
+			['jquery', 'media-upload', 'thickbox'],
292
+			EVENT_ESPRESSO_VERSION,
293
+			true
294
+		);
295
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
296
+		wp_enqueue_script('organization_settings');
297
+		wp_enqueue_style('organization-css');
298
+		$confirm_image_delete = [
299
+			'text' => wp_strip_all_tags(
300
+				esc_html__(
301
+					'Do you really want to delete this image? Please remember to save your settings to complete the removal.',
302
+					'event_espresso'
303
+				)
304
+			),
305
+		];
306
+		wp_localize_script('organization_settings', 'confirm_image_delete', $confirm_image_delete);
307
+	}
308
+
309
+
310
+	/**
311
+	 * Enqueue scripts and styles for the country settings route.
312
+	 */
313
+	public function load_scripts_styles_country_settings()
314
+	{
315
+		// scripts
316
+		wp_register_script(
317
+			'gen_settings_countries',
318
+			GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
319
+			['ee_admin_js'],
320
+			EVENT_ESPRESSO_VERSION,
321
+			true
322
+		);
323
+		wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
324
+		wp_enqueue_script('gen_settings_countries');
325
+		wp_enqueue_style('organization-css');
326
+	}
327
+
328
+
329
+	/*************        Espresso Pages        *************/
330
+	/**
331
+	 * _espresso_page_settings
332
+	 *
333
+	 * @throws EE_Error
334
+	 * @throws DomainException
335
+	 * @throws DomainException
336
+	 * @throws InvalidDataTypeException
337
+	 * @throws InvalidArgumentException
338
+	 */
339
+	protected function _espresso_page_settings()
340
+	{
341
+		// Check to make sure all of the main pages are set up properly,
342
+		// if not create the default pages and display an admin notice
343
+		EEH_Activation::verify_default_pages_exist();
344
+		$this->_transient_garbage_collection();
345
+
346
+		$this->_template_args['values']             = $this->_yes_no_values;
347
+
348
+		$this->_template_args['reg_page_id']        = $this->core_config->reg_page_id ?? null;
349
+		$this->_template_args['reg_page_obj']       = isset($this->core_config->reg_page_id)
350
+			? get_post($this->core_config->reg_page_id)
351
+			: false;
352
+
353
+		$this->_template_args['txn_page_id']        = $this->core_config->txn_page_id ?? null;
354
+		$this->_template_args['txn_page_obj']       = isset($this->core_config->txn_page_id)
355
+			? get_post($this->core_config->txn_page_id)
356
+			: false;
357
+
358
+		$this->_template_args['thank_you_page_id']  = $this->core_config->thank_you_page_id ?? null;
359
+		$this->_template_args['thank_you_page_obj'] = isset($this->core_config->thank_you_page_id)
360
+			? get_post($this->core_config->thank_you_page_id)
361
+			: false;
362
+
363
+		$this->_template_args['cancel_page_id']     = $this->core_config->cancel_page_id ?? null;
364
+		$this->_template_args['cancel_page_obj']    = isset($this->core_config->cancel_page_id)
365
+			? get_post($this->core_config->cancel_page_id)
366
+			: false;
367
+
368
+		$this->_set_add_edit_form_tags('update_espresso_page_settings');
369
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
370
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
371
+			GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
372
+			$this->_template_args,
373
+			true
374
+		);
375
+		$this->display_admin_page_with_sidebar();
376
+	}
377
+
378
+
379
+	/**
380
+	 * Handler for updating espresso page settings.
381
+	 *
382
+	 * @throws EE_Error
383
+	 */
384
+	protected function _update_espresso_page_settings()
385
+	{
386
+		$this->core_config = EE_Registry::instance()->CFG->core;
387
+		// capture incoming request data && set page IDs
388
+		$this->core_config->reg_page_id       = $this->request->getRequestParam(
389
+			'reg_page_id',
390
+			$this->core_config->reg_page_id,
391
+			DataType::INT
392
+		);
393
+		$this->core_config->txn_page_id       = $this->request->getRequestParam(
394
+			'txn_page_id',
395
+			$this->core_config->txn_page_id,
396
+			DataType::INT
397
+		);
398
+		$this->core_config->thank_you_page_id = $this->request->getRequestParam(
399
+			'thank_you_page_id',
400
+			$this->core_config->thank_you_page_id,
401
+			DataType::INT
402
+		);
403
+		$this->core_config->cancel_page_id    = $this->request->getRequestParam(
404
+			'cancel_page_id',
405
+			$this->core_config->cancel_page_id,
406
+			DataType::INT
407
+		);
408
+
409
+		$this->core_config = apply_filters(
410
+			'FHEE__General_Settings_Admin_Page___update_espresso_page_settings__CFG_core',
411
+			$this->core_config,
412
+			$this->request->requestParams()
413
+		);
414
+
415
+		$what = esc_html__('Critical Pages & Shortcodes', 'event_espresso');
416
+		$this->_redirect_after_action(
417
+			$this->_update_espresso_configuration(
418
+				$what,
419
+				$this->core_config,
420
+				__FILE__,
421
+				__FUNCTION__,
422
+				__LINE__
423
+			),
424
+			$what,
425
+			'',
426
+			[
427
+				'action' => 'critical_pages',
428
+			],
429
+			true
430
+		);
431
+	}
432
+
433
+
434
+	/*************        Your Organization        *************/
435
+
436
+
437
+	/**
438
+	 * @throws DomainException
439
+	 * @throws EE_Error
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidDataTypeException
442
+	 * @throws InvalidInterfaceException
443
+	 */
444
+	protected function _your_organization_settings()
445
+	{
446
+		$this->_template_args['admin_page_content'] = '';
447
+		try {
448
+			/** @var OrganizationSettings $organization_settings_form */
449
+			$organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
450
+
451
+			$this->_template_args['admin_page_content'] = EEH_HTML::div(
452
+				$organization_settings_form->display(),
453
+				'',
454
+				'padding'
455
+			);
456
+		} catch (Exception $e) {
457
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
458
+		}
459
+		$this->_set_add_edit_form_tags('update_your_organization_settings');
460
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
461
+		$this->display_admin_page_with_sidebar();
462
+	}
463
+
464
+
465
+	/**
466
+	 * Handler for updating organization settings.
467
+	 *
468
+	 * @throws EE_Error
469
+	 */
470
+	protected function _update_your_organization_settings()
471
+	{
472
+		try {
473
+			/** @var OrganizationSettings $organization_settings_form */
474
+			$organization_settings_form = $this->loader->getShared(OrganizationSettings::class);
475
+
476
+			$success = $organization_settings_form->process($this->request->requestParams());
477
+
478
+			EE_Registry::instance()->CFG = apply_filters(
479
+				'FHEE__General_Settings_Admin_Page___update_your_organization_settings__CFG',
480
+				EE_Registry::instance()->CFG
481
+			);
482
+		} catch (Exception $e) {
483
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
484
+			$success = false;
485
+		}
486
+
487
+		if ($success) {
488
+			$success = $this->_update_espresso_configuration(
489
+				esc_html__('Your Organization Settings', 'event_espresso'),
490
+				EE_Registry::instance()->CFG,
491
+				__FILE__,
492
+				__FUNCTION__,
493
+				__LINE__
494
+			);
495
+		}
496
+
497
+		$this->_redirect_after_action($success, '', '', ['action' => 'default'], true);
498
+	}
499
+
500
+
501
+
502
+	/*************        Admin Options        *************/
503
+
504
+
505
+	/**
506
+	 * _admin_option_settings
507
+	 *
508
+	 * @throws EE_Error
509
+	 * @throws LogicException
510
+	 */
511
+	protected function _admin_option_settings()
512
+	{
513
+		$this->_template_args['admin_page_content'] = '';
514
+		try {
515
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
516
+			// still need this for the old school form in Extend_General_Settings_Admin_Page
517
+			$this->_template_args['values'] = $this->_yes_no_values;
518
+			// also need to account for the do_action that was in the old template
519
+			$admin_options_settings_form->setTemplateArgs($this->_template_args);
520
+			$this->_template_args['admin_page_content'] = EEH_HTML::div(
521
+				$admin_options_settings_form->display(),
522
+				'',
523
+				'padding'
524
+			);
525
+		} catch (Exception $e) {
526
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
527
+		}
528
+		$this->_set_add_edit_form_tags('update_admin_option_settings');
529
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
530
+		$this->display_admin_page_with_sidebar();
531
+	}
532
+
533
+
534
+	/**
535
+	 * _update_admin_option_settings
536
+	 *
537
+	 * @throws EE_Error
538
+	 * @throws InvalidDataTypeException
539
+	 * @throws InvalidFormSubmissionException
540
+	 * @throws InvalidArgumentException
541
+	 * @throws LogicException
542
+	 */
543
+	protected function _update_admin_option_settings()
544
+	{
545
+		try {
546
+			$admin_options_settings_form = new AdminOptionsSettings(EE_Registry::instance());
547
+			$admin_options_settings_form->process(
548
+				$this->request->getRequestParam(
549
+					$admin_options_settings_form->slug(),
550
+					[],
551
+					DataType::STRING,
552
+					true
553
+				)
554
+			);
555
+			EE_Registry::instance()->CFG->admin = apply_filters(
556
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__CFG_admin',
557
+				EE_Registry::instance()->CFG->admin
558
+			);
559
+		} catch (Exception $e) {
560
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
561
+		}
562
+		$this->_redirect_after_action(
563
+			apply_filters(
564
+				'FHEE__General_Settings_Admin_Page___update_admin_option_settings__success',
565
+				$this->_update_espresso_configuration(
566
+					esc_html__('Admin Options', 'event_espresso'),
567
+					EE_Registry::instance()->CFG->admin,
568
+					__FILE__,
569
+					__FUNCTION__,
570
+					__LINE__
571
+				)
572
+			),
573
+			esc_html__('Admin Options', 'event_espresso'),
574
+			'updated',
575
+			['action' => 'admin_option_settings']
576
+		);
577
+	}
578
+
579
+
580
+	/*************        Countries        *************/
581
+
582
+
583
+	/**
584
+	 * @param string|null $default
585
+	 * @return string
586
+	 */
587
+	protected function getCountryISO(?string $default = null): string
588
+	{
589
+		$default = $default ?? $this->getCountryIsoForSite();
590
+		$CNT_ISO = $this->request->getRequestParam('country', $default);
591
+		return strtoupper($CNT_ISO);
592
+	}
593
+
594
+
595
+	/**
596
+	 * @return string
597
+	 */
598
+	protected function getCountryIsoForSite(): string
599
+	{
600
+		return ! empty(EE_Registry::instance()->CFG->organization->CNT_ISO)
601
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
602
+			: 'US';
603
+	}
604
+
605
+
606
+	/**
607
+	 * @param string          $CNT_ISO
608
+	 * @param EE_Country|null $country
609
+	 * @return EE_Base_Class|EE_Country
610
+	 * @throws EE_Error
611
+	 * @throws InvalidArgumentException
612
+	 * @throws InvalidDataTypeException
613
+	 * @throws InvalidInterfaceException
614
+	 * @throws ReflectionException
615
+	 */
616
+	protected function verifyOrGetCountryFromIso(string $CNT_ISO, ?EE_Country $country = null)
617
+	{
618
+		/** @var EE_Country $country */
619
+		return $country instanceof EE_Country && $country->ID() === $CNT_ISO
620
+			? $country
621
+			: EEM_Country::instance()->get_one_by_ID($CNT_ISO);
622
+	}
623
+
624
+
625
+	/**
626
+	 * Output Country Settings view.
627
+	 *
628
+	 * @throws DomainException
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	protected function _country_settings()
636
+	{
637
+		$CNT_ISO = $this->getCountryISO();
638
+
639
+		$this->_template_args['values']    = $this->_yes_no_values;
640
+		$this->_template_args['countries'] = new EE_Question_Form_Input(
641
+			EE_Question::new_instance(
642
+				[
643
+				  'QST_ID'           => 0,
644
+				  'QST_display_text' => esc_html__('Select Country', 'event_espresso'),
645
+				  'QST_system'       => 'admin-country',
646
+				]
647
+			),
648
+			EE_Answer::new_instance(
649
+				[
650
+					'ANS_ID'    => 0,
651
+					'ANS_value' => $CNT_ISO,
652
+				]
653
+			),
654
+			[
655
+				'input_id'       => 'country',
656
+				'input_name'     => 'country',
657
+				'input_prefix'   => '',
658
+				'append_qstn_id' => false,
659
+			]
660
+		);
661
+
662
+		$country = $this->verifyOrGetCountryFromIso($CNT_ISO);
663
+		add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10);
664
+		add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10);
665
+		$this->_template_args['country_details_settings'] = $this->display_country_settings(
666
+			$country->ID(),
667
+			$country
668
+		);
669
+		$this->_template_args['country_states_settings']  = $this->display_country_states(
670
+			$country->ID(),
671
+			$country
672
+		);
673
+		$this->_template_args['CNT_name_for_site']        = $country->name();
674
+
675
+		$this->_set_add_edit_form_tags('update_country_settings');
676
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
677
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
678
+			GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
679
+			$this->_template_args,
680
+			true
681
+		);
682
+		$this->display_admin_page_with_no_sidebar();
683
+	}
684
+
685
+
686
+	/**
687
+	 * @param string          $CNT_ISO
688
+	 * @param EE_Country|null $country
689
+	 * @return string
690
+	 * @throws DomainException
691
+	 * @throws EE_Error
692
+	 * @throws InvalidArgumentException
693
+	 * @throws InvalidDataTypeException
694
+	 * @throws InvalidInterfaceException
695
+	 * @throws ReflectionException
696
+	 */
697
+	public function display_country_settings(string $CNT_ISO = '', ?EE_Country $country = null): string
698
+	{
699
+		$CNT_ISO          = $this->getCountryISO($CNT_ISO);
700
+		$CNT_ISO_for_site = $this->getCountryIsoForSite();
701
+
702
+		if (! $CNT_ISO) {
703
+			return '';
704
+		}
705
+
706
+		// for ajax
707
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
708
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
709
+		add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'country_form_field_label_wrap'], 10, 2);
710
+		add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'country_form_field_input__wrap'], 10, 2);
711
+		$country                                  = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
712
+		$CNT_cur_disabled                         = $CNT_ISO !== $CNT_ISO_for_site;
713
+		$this->_template_args['CNT_cur_disabled'] = $CNT_cur_disabled;
714
+
715
+		$country_input_types            = [
716
+			'CNT_active'      => [
717
+				'type'             => 'RADIO_BTN',
718
+				'input_name'       => "cntry[$CNT_ISO]",
719
+				'class'            => '',
720
+				'options'          => $this->_yes_no_values,
721
+				'use_desc_4_label' => true,
722
+			],
723
+			'CNT_ISO'         => [
724
+				'type'       => 'TEXT',
725
+				'input_name' => "cntry[$CNT_ISO]",
726
+				'class'      => 'ee-input-width--small',
727
+			],
728
+			'CNT_ISO3'        => [
729
+				'type'       => 'TEXT',
730
+				'input_name' => "cntry[$CNT_ISO]",
731
+				'class'      => 'ee-input-width--small',
732
+			],
733
+			// 'RGN_ID'          => [
734
+			//     'type'       => 'TEXT',
735
+			//     'input_name' => "cntry[$CNT_ISO]",
736
+			//     'class'      => 'ee-input-width--small',
737
+			// ],
738
+			'CNT_name'        => [
739
+				'type'       => 'TEXT',
740
+				'input_name' => "cntry[$CNT_ISO]",
741
+				'class'      => 'ee-input-width--big',
742
+			],
743
+			'CNT_cur_code'    => [
744
+				'type'       => 'TEXT',
745
+				'input_name' => "cntry[$CNT_ISO]",
746
+				'class'      => 'ee-input-width--small',
747
+				'disabled'   => $CNT_cur_disabled,
748
+			],
749
+			'CNT_cur_single'  => [
750
+				'type'       => 'TEXT',
751
+				'input_name' => "cntry[$CNT_ISO]",
752
+				'class'      => 'ee-input-width--reg',
753
+				'disabled'   => $CNT_cur_disabled,
754
+			],
755
+			'CNT_cur_plural'  => [
756
+				'type'       => 'TEXT',
757
+				'input_name' => "cntry[$CNT_ISO]",
758
+				'class'      => 'ee-input-width--reg',
759
+				'disabled'   => $CNT_cur_disabled,
760
+			],
761
+			'CNT_cur_sign'    => [
762
+				'type'         => 'TEXT',
763
+				'input_name'   => "cntry[$CNT_ISO]",
764
+				'class'        => 'ee-input-width--small',
765
+				'htmlentities' => false,
766
+				'disabled'     => $CNT_cur_disabled,
767
+			],
768
+			'CNT_cur_sign_b4' => [
769
+				'type'             => 'RADIO_BTN',
770
+				'input_name'       => "cntry[$CNT_ISO]",
771
+				'class'            => '',
772
+				'options'          => $this->_yes_no_values,
773
+				'use_desc_4_label' => true,
774
+				'disabled'         => $CNT_cur_disabled,
775
+			],
776
+			'CNT_cur_dec_plc' => [
777
+				'type'       => 'RADIO_BTN',
778
+				'input_name' => "cntry[$CNT_ISO]",
779
+				'class'      => '',
780
+				'options'    => [
781
+					['id' => 0, 'text' => ''],
782
+					['id' => 1, 'text' => ''],
783
+					['id' => 2, 'text' => ''],
784
+					['id' => 3, 'text' => ''],
785
+				],
786
+				'disabled'   => $CNT_cur_disabled,
787
+			],
788
+			'CNT_cur_dec_mrk' => [
789
+				'type'             => 'RADIO_BTN',
790
+				'input_name'       => "cntry[$CNT_ISO]",
791
+				'class'            => '',
792
+				'options'          => [
793
+					[
794
+						'id'   => ',',
795
+						'text' => esc_html__(', (comma)', 'event_espresso'),
796
+					],
797
+					['id' => '.', 'text' => esc_html__('. (decimal)', 'event_espresso')],
798
+				],
799
+				'use_desc_4_label' => true,
800
+				'disabled'         => $CNT_cur_disabled,
801
+			],
802
+			'CNT_cur_thsnds'  => [
803
+				'type'             => 'RADIO_BTN',
804
+				'input_name'       => "cntry[$CNT_ISO]",
805
+				'class'            => '',
806
+				'options'          => [
807
+					[
808
+						'id'   => ',',
809
+						'text' => esc_html__(', (comma)', 'event_espresso'),
810
+					],
811
+					[
812
+						'id'   => '.',
813
+						'text' => esc_html__('. (decimal)', 'event_espresso'),
814
+					],
815
+					[
816
+						'id'   => '&nbsp;',
817
+						'text' => esc_html__('(space)', 'event_espresso'),
818
+					],
819
+				],
820
+				'use_desc_4_label' => true,
821
+				'disabled'         => $CNT_cur_disabled,
822
+			],
823
+			'CNT_tel_code'    => [
824
+				'type'       => 'TEXT',
825
+				'input_name' => "cntry[$CNT_ISO]",
826
+				'class'      => 'ee-input-width--small',
827
+			],
828
+			'CNT_is_EU'       => [
829
+				'type'             => 'RADIO_BTN',
830
+				'input_name'       => "cntry[$CNT_ISO]",
831
+				'class'            => '',
832
+				'options'          => $this->_yes_no_values,
833
+				'use_desc_4_label' => true,
834
+			],
835
+		];
836
+		$this->_template_args['inputs'] = EE_Question_Form_Input::generate_question_form_inputs_for_object(
837
+			$country,
838
+			$country_input_types
839
+		);
840
+		$country_details_settings       = EEH_Template::display_template(
841
+			GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
842
+			$this->_template_args,
843
+			true
844
+		);
845
+
846
+		if (defined('DOING_AJAX')) {
847
+			$notices = EE_Error::get_notices(false, false, false);
848
+			echo wp_json_encode(
849
+				[
850
+					'return_data' => $country_details_settings,
851
+					'success'     => $notices['success'],
852
+					'errors'      => $notices['errors'],
853
+				]
854
+			);
855
+			die();
856
+		}
857
+		return $country_details_settings;
858
+	}
859
+
860
+
861
+	/**
862
+	 * @param string          $CNT_ISO
863
+	 * @param EE_Country|null $country
864
+	 * @return string
865
+	 * @throws DomainException
866
+	 * @throws EE_Error
867
+	 * @throws InvalidArgumentException
868
+	 * @throws InvalidDataTypeException
869
+	 * @throws InvalidInterfaceException
870
+	 * @throws ReflectionException
871
+	 */
872
+	public function display_country_states(string $CNT_ISO = '', ?EE_Country $country = null): string
873
+	{
874
+		$CNT_ISO = $this->getCountryISO($CNT_ISO);
875
+		if (! $CNT_ISO) {
876
+			return '';
877
+		}
878
+		// for ajax
879
+		remove_all_filters('FHEE__EEH_Form_Fields__label_html');
880
+		remove_all_filters('FHEE__EEH_Form_Fields__input_html');
881
+		add_filter('FHEE__EEH_Form_Fields__label_html', [$this, 'state_form_field_label_wrap'], 10, 2);
882
+		add_filter('FHEE__EEH_Form_Fields__input_html', [$this, 'state_form_field_input__wrap'], 10);
883
+		$states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
884
+		if (empty($states)) {
885
+			/** @var EventEspresso\core\services\address\CountrySubRegionDao $countrySubRegionDao */
886
+			$countrySubRegionDao = $this->loader->getShared(
887
+				'EventEspresso\core\services\address\CountrySubRegionDao'
888
+			);
889
+			if ($countrySubRegionDao instanceof EventEspresso\core\services\address\CountrySubRegionDao) {
890
+				$country = $this->verifyOrGetCountryFromIso($CNT_ISO, $country);
891
+				if ($countrySubRegionDao->saveCountrySubRegions($country)) {
892
+					$states = EEM_State::instance()->get_all_states_for_these_countries([$CNT_ISO => $CNT_ISO]);
893
+				}
894
+			}
895
+		}
896
+		if (is_array($states)) {
897
+			foreach ($states as $STA_ID => $state) {
898
+				if ($state instanceof EE_State) {
899
+					$inputs = EE_Question_Form_Input::generate_question_form_inputs_for_object(
900
+						$state,
901
+						[
902
+							'STA_abbrev' => [
903
+								'type'             => 'TEXT',
904
+								'label'            => esc_html__('Code', 'event_espresso'),
905
+								'input_name'       => "states[$STA_ID]",
906
+								'class'            => 'ee-input-width--tiny',
907
+								'add_mobile_label' => true,
908
+							],
909
+							'STA_name'   => [
910
+								'type'             => 'TEXT',
911
+								'label'            => esc_html__('Name', 'event_espresso'),
912
+								'input_name'       => "states[$STA_ID]",
913
+								'class'            => 'ee-input-width--big',
914
+								'add_mobile_label' => true,
915
+							],
916
+							'STA_active' => [
917
+								'type'             => 'RADIO_BTN',
918
+								'label'            => esc_html__('State Appears in Dropdown Select Lists', 'event_espresso'),
919
+								'input_name'       => "states[$STA_ID]",
920
+								'options'          => $this->_yes_no_values,
921
+								'use_desc_4_label' => true,
922
+								'add_mobile_label' => true,
923
+							],
924
+						]
925
+					);
926
+
927
+					$delete_state_url = EE_Admin_Page::add_query_args_and_nonce(
928
+						[
929
+							'action'     => 'delete_state',
930
+							'STA_ID'     => $STA_ID,
931
+							'CNT_ISO'    => $CNT_ISO,
932
+							'STA_abbrev' => $state->abbrev(),
933
+						],
934
+						GEN_SET_ADMIN_URL
935
+					);
936
+
937
+					$this->_template_args['states'][ $STA_ID ]['inputs']           = $inputs;
938
+					$this->_template_args['states'][ $STA_ID ]['delete_state_url'] = $delete_state_url;
939
+				}
940
+			}
941
+		} else {
942
+			$this->_template_args['states'] = false;
943
+		}
944
+
945
+		$this->_template_args['add_new_state_url'] = EE_Admin_Page::add_query_args_and_nonce(
946
+			['action' => 'add_new_state'],
947
+			GEN_SET_ADMIN_URL
948
+		);
949
+
950
+		$state_details_settings = EEH_Template::display_template(
951
+			GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
952
+			$this->_template_args,
953
+			true
954
+		);
955
+
956
+		if (defined('DOING_AJAX')) {
957
+			$notices = EE_Error::get_notices(false, false, false);
958
+			echo wp_json_encode(
959
+				[
960
+					'return_data' => $state_details_settings,
961
+					'success'     => $notices['success'],
962
+					'errors'      => $notices['errors'],
963
+				]
964
+			);
965
+			die();
966
+		}
967
+		return $state_details_settings;
968
+	}
969
+
970
+
971
+	/**
972
+	 * @return void
973
+	 * @throws EE_Error
974
+	 * @throws InvalidArgumentException
975
+	 * @throws InvalidDataTypeException
976
+	 * @throws InvalidInterfaceException
977
+	 * @throws ReflectionException
978
+	 */
979
+	public function add_new_state()
980
+	{
981
+		$success = true;
982
+		$CNT_ISO = $this->getCountryISO('');
983
+		if (! $CNT_ISO) {
984
+			EE_Error::add_error(
985
+				esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
986
+				__FILE__,
987
+				__FUNCTION__,
988
+				__LINE__
989
+			);
990
+			$success = false;
991
+		}
992
+		$STA_abbrev = $this->request->getRequestParam('STA_abbrev');
993
+		if (! $STA_abbrev) {
994
+			EE_Error::add_error(
995
+				esc_html__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
996
+				__FILE__,
997
+				__FUNCTION__,
998
+				__LINE__
999
+			);
1000
+			$success = false;
1001
+		}
1002
+		$STA_name = $this->request->getRequestParam('STA_name');
1003
+		if (! $STA_name) {
1004
+			EE_Error::add_error(
1005
+				esc_html__('No State name or an invalid State name was received.', 'event_espresso'),
1006
+				__FILE__,
1007
+				__FUNCTION__,
1008
+				__LINE__
1009
+			);
1010
+			$success = false;
1011
+		}
1012
+
1013
+		if ($success) {
1014
+			$cols_n_values = [
1015
+				'CNT_ISO'    => $CNT_ISO,
1016
+				'STA_abbrev' => $STA_abbrev,
1017
+				'STA_name'   => $STA_name,
1018
+				'STA_active' => true,
1019
+			];
1020
+			$success       = EEM_State::instance()->insert($cols_n_values);
1021
+			EE_Error::add_success(esc_html__('The State was added successfully.', 'event_espresso'));
1022
+		}
1023
+
1024
+		if (defined('DOING_AJAX')) {
1025
+			$notices = EE_Error::get_notices(false, false, false);
1026
+			echo wp_json_encode(array_merge($notices, ['return_data' => $CNT_ISO]));
1027
+			die();
1028
+		}
1029
+		$this->_redirect_after_action(
1030
+			$success,
1031
+			esc_html__('State', 'event_espresso'),
1032
+			'added',
1033
+			['action' => 'country_settings']
1034
+		);
1035
+	}
1036
+
1037
+
1038
+	/**
1039
+	 * @return void
1040
+	 * @throws EE_Error
1041
+	 * @throws InvalidArgumentException
1042
+	 * @throws InvalidDataTypeException
1043
+	 * @throws InvalidInterfaceException
1044
+	 * @throws ReflectionException
1045
+	 */
1046
+	public function delete_state()
1047
+	{
1048
+		$CNT_ISO    = $this->getCountryISO();
1049
+		$STA_ID     = $this->request->getRequestParam('STA_ID');
1050
+		$STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1051
+
1052
+		if (! $STA_ID) {
1053
+			EE_Error::add_error(
1054
+				esc_html__('No State ID or an invalid State ID was received.', 'event_espresso'),
1055
+				__FILE__,
1056
+				__FUNCTION__,
1057
+				__LINE__
1058
+			);
1059
+			return;
1060
+		}
1061
+
1062
+		$success = EEM_State::instance()->delete_by_ID($STA_ID);
1063
+		if ($success !== false) {
1064
+			do_action(
1065
+				'AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
1066
+				$CNT_ISO,
1067
+				$STA_ID,
1068
+				['STA_abbrev' => $STA_abbrev]
1069
+			);
1070
+			EE_Error::add_success(esc_html__('The State was deleted successfully.', 'event_espresso'));
1071
+		}
1072
+		if (defined('DOING_AJAX')) {
1073
+			$notices                = EE_Error::get_notices(false);
1074
+			$notices['return_data'] = true;
1075
+			echo wp_json_encode($notices);
1076
+			die();
1077
+		}
1078
+		$this->_redirect_after_action(
1079
+			$success,
1080
+			esc_html__('State', 'event_espresso'),
1081
+			'deleted',
1082
+			['action' => 'country_settings']
1083
+		);
1084
+	}
1085
+
1086
+
1087
+	/**
1088
+	 * @return void
1089
+	 * @throws EE_Error
1090
+	 * @throws InvalidArgumentException
1091
+	 * @throws InvalidDataTypeException
1092
+	 * @throws InvalidInterfaceException
1093
+	 * @throws ReflectionException
1094
+	 */
1095
+	protected function _update_country_settings()
1096
+	{
1097
+		$CNT_ISO = $this->getCountryISO();
1098
+		if (! $CNT_ISO) {
1099
+			EE_Error::add_error(
1100
+				esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1101
+				__FILE__,
1102
+				__FUNCTION__,
1103
+				__LINE__
1104
+			);
1105
+			return;
1106
+		}
1107
+
1108
+		$country = $this->verifyOrGetCountryFromIso($CNT_ISO);
1109
+
1110
+		$cols_n_values                    = [];
1111
+		$cols_n_values['CNT_ISO3']        = strtoupper(
1112
+			$this->request->getRequestParam('cntry', '', $country->ISO3())
1113
+		);
1114
+		$cols_n_values['CNT_name']        =
1115
+			$this->request->getRequestParam("cntry[$CNT_ISO][CNT_name]", $country->name());
1116
+		$cols_n_values['CNT_cur_code']    = strtoupper(
1117
+			$this->request->getRequestParam(
1118
+				"cntry[$CNT_ISO][CNT_cur_code]",
1119
+				$country->currency_code()
1120
+			)
1121
+		);
1122
+		$cols_n_values['CNT_cur_single']  = $this->request->getRequestParam(
1123
+			"cntry[$CNT_ISO][CNT_cur_single]",
1124
+			$country->currency_name_single()
1125
+		);
1126
+		$cols_n_values['CNT_cur_plural']  = $this->request->getRequestParam(
1127
+			"cntry[$CNT_ISO][CNT_cur_plural]",
1128
+			$country->currency_name_plural()
1129
+		);
1130
+		$cols_n_values['CNT_cur_sign']    = $this->request->getRequestParam(
1131
+			"cntry[$CNT_ISO][CNT_cur_sign]",
1132
+			$country->currency_sign()
1133
+		);
1134
+		$cols_n_values['CNT_cur_sign_b4'] = $this->request->getRequestParam(
1135
+			"cntry[$CNT_ISO][CNT_cur_sign_b4]",
1136
+			$country->currency_sign_before(),
1137
+			DataType::BOOL
1138
+		);
1139
+		$cols_n_values['CNT_cur_dec_plc'] = $this->request->getRequestParam(
1140
+			"cntry[$CNT_ISO][CNT_cur_dec_plc]",
1141
+			$country->currency_decimal_places()
1142
+		);
1143
+		$cols_n_values['CNT_cur_dec_mrk'] = $this->request->getRequestParam(
1144
+			"cntry[$CNT_ISO][CNT_cur_dec_mrk]",
1145
+			$country->currency_decimal_mark()
1146
+		);
1147
+		$cols_n_values['CNT_cur_thsnds']  = $this->request->getRequestParam(
1148
+			"cntry[$CNT_ISO][CNT_cur_thsnds]",
1149
+			$country->currency_thousands_separator()
1150
+		);
1151
+		$cols_n_values['CNT_tel_code']    = $this->request->getRequestParam(
1152
+			"cntry[$CNT_ISO][CNT_tel_code]",
1153
+			$country->telephoneCode()
1154
+		);
1155
+		$cols_n_values['CNT_active']      = $this->request->getRequestParam(
1156
+			"cntry[$CNT_ISO][CNT_active]",
1157
+			$country->isActive(),
1158
+			DataType::BOOL
1159
+		);
1160
+
1161
+		// allow filtering of country data
1162
+		$cols_n_values = apply_filters(
1163
+			'FHEE__General_Settings_Admin_Page___update_country_settings__cols_n_values',
1164
+			$cols_n_values
1165
+		);
1166
+
1167
+		// where values
1168
+		$where_cols_n_values = [['CNT_ISO' => $CNT_ISO]];
1169
+		// run the update
1170
+		$success = EEM_Country::instance()->update($cols_n_values, $where_cols_n_values);
1171
+
1172
+		// allow filtering of states data
1173
+		$states = apply_filters(
1174
+			'FHEE__General_Settings_Admin_Page___update_country_settings__states',
1175
+			$this->request->getRequestParam('states', [], DataType::STRING, true)
1176
+		);
1177
+
1178
+		if (! empty($states) && $success !== false) {
1179
+			// loop thru state data ( looks like : states[75][STA_name] )
1180
+			foreach ($states as $STA_ID => $state) {
1181
+				$cols_n_values = [
1182
+					'CNT_ISO'    => $CNT_ISO,
1183
+					'STA_abbrev' => sanitize_text_field($state['STA_abbrev']),
1184
+					'STA_name'   => sanitize_text_field($state['STA_name']),
1185
+					'STA_active' => filter_var($state['STA_active'], FILTER_VALIDATE_BOOLEAN),
1186
+				];
1187
+				// where values
1188
+				$where_cols_n_values = [['STA_ID' => $STA_ID]];
1189
+				// run the update
1190
+				$success = EEM_State::instance()->update($cols_n_values, $where_cols_n_values);
1191
+				if ($success !== false) {
1192
+					do_action(
1193
+						'AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
1194
+						$CNT_ISO,
1195
+						$STA_ID,
1196
+						$cols_n_values
1197
+					);
1198
+				}
1199
+			}
1200
+		}
1201
+		// check if country being edited matches org option country, and if so, then  update EE_Config with new settings
1202
+		if (
1203
+			isset(EE_Registry::instance()->CFG->organization->CNT_ISO)
1204
+			&& $CNT_ISO == EE_Registry::instance()->CFG->organization->CNT_ISO
1205
+		) {
1206
+			EE_Registry::instance()->CFG->currency = new EE_Currency_Config($CNT_ISO);
1207
+			EE_Registry::instance()->CFG->update_espresso_config();
1208
+		}
1209
+
1210
+		if ($success !== false) {
1211
+			EE_Error::add_success(
1212
+				esc_html__('Country Settings updated successfully.', 'event_espresso')
1213
+			);
1214
+		}
1215
+		$this->_redirect_after_action(
1216
+			$success,
1217
+			'',
1218
+			'',
1219
+			['action' => 'country_settings', 'country' => $CNT_ISO],
1220
+			true
1221
+		);
1222
+	}
1223
+
1224
+
1225
+	/**
1226
+	 * form_form_field_label_wrap
1227
+	 *
1228
+	 * @param string $label
1229
+	 * @return string
1230
+	 */
1231
+	public function country_form_field_label_wrap(string $label): string
1232
+	{
1233
+		return '
1234 1234
 			<tr>
1235 1235
 				<th>
1236 1236
 					' . $label . '
1237 1237
 				</th>';
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     * form_form_field_input__wrap
1243
-     *
1244
-     * @param string $input
1245
-     * @return string
1246
-     */
1247
-    public function country_form_field_input__wrap(string $input): string
1248
-    {
1249
-        return '
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 * form_form_field_input__wrap
1243
+	 *
1244
+	 * @param string $input
1245
+	 * @return string
1246
+	 */
1247
+	public function country_form_field_input__wrap(string $input): string
1248
+	{
1249
+		return '
1250 1250
 				<td class="general-settings-country-input-td">
1251 1251
 					' . $input . '
1252 1252
 				</td>
1253 1253
 			</tr>';
1254
-    }
1255
-
1256
-
1257
-    /**
1258
-     * form_form_field_label_wrap
1259
-     *
1260
-     * @param string $label
1261
-     * @param string $required_text
1262
-     * @return string
1263
-     */
1264
-    public function state_form_field_label_wrap(string $label, string $required_text): string
1265
-    {
1266
-        return $required_text;
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * form_form_field_input__wrap
1272
-     *
1273
-     * @param string $input
1274
-     * @return string
1275
-     */
1276
-    public function state_form_field_input__wrap(string $input): string
1277
-    {
1278
-        return '
1254
+	}
1255
+
1256
+
1257
+	/**
1258
+	 * form_form_field_label_wrap
1259
+	 *
1260
+	 * @param string $label
1261
+	 * @param string $required_text
1262
+	 * @return string
1263
+	 */
1264
+	public function state_form_field_label_wrap(string $label, string $required_text): string
1265
+	{
1266
+		return $required_text;
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * form_form_field_input__wrap
1272
+	 *
1273
+	 * @param string $input
1274
+	 * @return string
1275
+	 */
1276
+	public function state_form_field_input__wrap(string $input): string
1277
+	{
1278
+		return '
1279 1279
 				<td class="general-settings-country-state-input-td">
1280 1280
 					' . $input . '
1281 1281
 				</td>';
1282
-    }
1283
-
1284
-
1285
-    /***********/
1286
-
1287
-
1288
-    /**
1289
-     * displays edit and view links for critical EE pages
1290
-     *
1291
-     * @param int $ee_page_id
1292
-     * @return string
1293
-     */
1294
-    public static function edit_view_links(int $ee_page_id): string
1295
-    {
1296
-        $edit_url = add_query_arg(
1297
-            ['post' => $ee_page_id, 'action' => 'edit'],
1298
-            admin_url('post.php')
1299
-        );
1300
-        $links    = '<a href="' . esc_url_raw($edit_url) . '" >' . esc_html__('Edit', 'event_espresso') . '</a>';
1301
-        $links    .= ' &nbsp;|&nbsp; ';
1302
-        $links    .= '<a href="' . get_permalink($ee_page_id) . '" >' . esc_html__('View', 'event_espresso') . '</a>';
1303
-
1304
-        return $links;
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * displays page and shortcode status for critical EE pages
1310
-     *
1311
-     * @param WP_Post $ee_page
1312
-     * @param string  $shortcode
1313
-     * @return string
1314
-     */
1315
-    public static function page_and_shortcode_status(WP_Post $ee_page, string $shortcode): string
1316
-    {
1317
-        // page status
1318
-        if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
1319
-            $pg_class  = 'ee-status-bg--success';
1320
-            $pg_status = sprintf(esc_html__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
1321
-        } else {
1322
-            $pg_class  = 'ee-status-bg--error';
1323
-            $pg_status = sprintf(esc_html__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
1324
-        }
1325
-
1326
-        // shortcode status
1327
-        if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== false) {
1328
-            $sc_class  = 'ee-status-bg--success';
1329
-            $sc_status = sprintf(esc_html__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
1330
-        } else {
1331
-            $sc_class  = 'ee-status-bg--error';
1332
-            $sc_status = sprintf(esc_html__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
1333
-        }
1334
-
1335
-        return '
1282
+	}
1283
+
1284
+
1285
+	/***********/
1286
+
1287
+
1288
+	/**
1289
+	 * displays edit and view links for critical EE pages
1290
+	 *
1291
+	 * @param int $ee_page_id
1292
+	 * @return string
1293
+	 */
1294
+	public static function edit_view_links(int $ee_page_id): string
1295
+	{
1296
+		$edit_url = add_query_arg(
1297
+			['post' => $ee_page_id, 'action' => 'edit'],
1298
+			admin_url('post.php')
1299
+		);
1300
+		$links    = '<a href="' . esc_url_raw($edit_url) . '" >' . esc_html__('Edit', 'event_espresso') . '</a>';
1301
+		$links    .= ' &nbsp;|&nbsp; ';
1302
+		$links    .= '<a href="' . get_permalink($ee_page_id) . '" >' . esc_html__('View', 'event_espresso') . '</a>';
1303
+
1304
+		return $links;
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * displays page and shortcode status for critical EE pages
1310
+	 *
1311
+	 * @param WP_Post $ee_page
1312
+	 * @param string  $shortcode
1313
+	 * @return string
1314
+	 */
1315
+	public static function page_and_shortcode_status(WP_Post $ee_page, string $shortcode): string
1316
+	{
1317
+		// page status
1318
+		if (isset($ee_page->post_status) && $ee_page->post_status == 'publish') {
1319
+			$pg_class  = 'ee-status-bg--success';
1320
+			$pg_status = sprintf(esc_html__('Page%sStatus%sOK', 'event_espresso'), '&nbsp;', '&nbsp;');
1321
+		} else {
1322
+			$pg_class  = 'ee-status-bg--error';
1323
+			$pg_status = sprintf(esc_html__('Page%sVisibility%sProblem', 'event_espresso'), '&nbsp;', '&nbsp;');
1324
+		}
1325
+
1326
+		// shortcode status
1327
+		if (isset($ee_page->post_content) && strpos($ee_page->post_content, $shortcode) !== false) {
1328
+			$sc_class  = 'ee-status-bg--success';
1329
+			$sc_status = sprintf(esc_html__('Shortcode%sOK', 'event_espresso'), '&nbsp;');
1330
+		} else {
1331
+			$sc_class  = 'ee-status-bg--error';
1332
+			$sc_status = sprintf(esc_html__('Shortcode%sProblem', 'event_espresso'), '&nbsp;');
1333
+		}
1334
+
1335
+		return '
1336 1336
         <span class="ee-page-status ' . $pg_class . '"><strong>' . $pg_status . '</strong></span>
1337 1337
         <span class="ee-page-status ' . $sc_class . '"><strong>' . $sc_status . '</strong></span>';
1338
-    }
1339
-
1340
-
1341
-    /**
1342
-     * generates a dropdown of all parent pages - copied from WP core
1343
-     *
1344
-     * @param int  $default
1345
-     * @param int  $parent
1346
-     * @param int  $level
1347
-     * @param bool $echo
1348
-     * @return string;
1349
-     */
1350
-    public static function page_settings_dropdown(
1351
-        int $default = 0,
1352
-        int $parent = 0,
1353
-        int $level = 0,
1354
-        bool $echo = true
1355
-    ): string {
1356
-        global $wpdb;
1357
-        $items  = $wpdb->get_results(
1358
-            $wpdb->prepare(
1359
-                "SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1360
-                $parent
1361
-            )
1362
-        );
1363
-        $output = '';
1364
-
1365
-        if ($items) {
1366
-            $level = absint($level);
1367
-            foreach ($items as $item) {
1368
-                $ID         = absint($item->ID);
1369
-                $post_title = wp_strip_all_tags($item->post_title);
1370
-                $pad    = str_repeat('&nbsp;', $level * 3);
1371
-                $option = "\n\t";
1372
-                $option .= '<option class="level-' . $level . '" ';
1373
-                $option .= 'value="' . $ID . '" ';
1374
-                $option .= $ID === absint($default) ? ' selected' : '';
1375
-                $option .= '>';
1376
-                $option .= "$pad {$post_title}";
1377
-                $option .= '</option>';
1378
-                $output .= $option;
1379
-                ob_start();
1380
-                parent_dropdown($default, $item->ID, $level + 1);
1381
-                $output .= ob_get_clean();
1382
-            }
1383
-        }
1384
-        if ($echo) {
1385
-            echo wp_kses($output, AllowedTags::getWithFormTags());
1386
-            return '';
1387
-        }
1388
-        return $output;
1389
-    }
1390
-
1391
-
1392
-    /**
1393
-     * Loads the scripts for the privacy settings form
1394
-     */
1395
-    public function load_scripts_styles_privacy_settings()
1396
-    {
1397
-        $form_handler = $this->loader->getShared(
1398
-            'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1399
-        );
1400
-        $form_handler->enqueueStylesAndScripts();
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * display the privacy settings form
1406
-     *
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function privacySettings()
1410
-    {
1411
-        $this->_set_add_edit_form_tags('update_privacy_settings');
1412
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
1413
-        $form_handler                               = $this->loader->getShared(
1414
-            'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1415
-        );
1416
-        $this->_template_args['admin_page_content'] = EEH_HTML::div(
1417
-            $form_handler->display(),
1418
-            '',
1419
-            'padding'
1420
-        );
1421
-        $this->display_admin_page_with_sidebar();
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * Update the privacy settings from form data
1427
-     *
1428
-     * @throws EE_Error
1429
-     */
1430
-    public function updatePrivacySettings()
1431
-    {
1432
-        $form_handler = $this->loader->getShared(
1433
-            'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1434
-        );
1435
-        $success      = $form_handler->process($this->get_request_data());
1436
-        $this->_redirect_after_action(
1437
-            $success,
1438
-            esc_html__('Registration Form Options', 'event_espresso'),
1439
-            'updated',
1440
-            ['action' => 'privacy_settings']
1441
-        );
1442
-    }
1338
+	}
1339
+
1340
+
1341
+	/**
1342
+	 * generates a dropdown of all parent pages - copied from WP core
1343
+	 *
1344
+	 * @param int  $default
1345
+	 * @param int  $parent
1346
+	 * @param int  $level
1347
+	 * @param bool $echo
1348
+	 * @return string;
1349
+	 */
1350
+	public static function page_settings_dropdown(
1351
+		int $default = 0,
1352
+		int $parent = 0,
1353
+		int $level = 0,
1354
+		bool $echo = true
1355
+	): string {
1356
+		global $wpdb;
1357
+		$items  = $wpdb->get_results(
1358
+			$wpdb->prepare(
1359
+				"SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1360
+				$parent
1361
+			)
1362
+		);
1363
+		$output = '';
1364
+
1365
+		if ($items) {
1366
+			$level = absint($level);
1367
+			foreach ($items as $item) {
1368
+				$ID         = absint($item->ID);
1369
+				$post_title = wp_strip_all_tags($item->post_title);
1370
+				$pad    = str_repeat('&nbsp;', $level * 3);
1371
+				$option = "\n\t";
1372
+				$option .= '<option class="level-' . $level . '" ';
1373
+				$option .= 'value="' . $ID . '" ';
1374
+				$option .= $ID === absint($default) ? ' selected' : '';
1375
+				$option .= '>';
1376
+				$option .= "$pad {$post_title}";
1377
+				$option .= '</option>';
1378
+				$output .= $option;
1379
+				ob_start();
1380
+				parent_dropdown($default, $item->ID, $level + 1);
1381
+				$output .= ob_get_clean();
1382
+			}
1383
+		}
1384
+		if ($echo) {
1385
+			echo wp_kses($output, AllowedTags::getWithFormTags());
1386
+			return '';
1387
+		}
1388
+		return $output;
1389
+	}
1390
+
1391
+
1392
+	/**
1393
+	 * Loads the scripts for the privacy settings form
1394
+	 */
1395
+	public function load_scripts_styles_privacy_settings()
1396
+	{
1397
+		$form_handler = $this->loader->getShared(
1398
+			'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1399
+		);
1400
+		$form_handler->enqueueStylesAndScripts();
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * display the privacy settings form
1406
+	 *
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function privacySettings()
1410
+	{
1411
+		$this->_set_add_edit_form_tags('update_privacy_settings');
1412
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
1413
+		$form_handler                               = $this->loader->getShared(
1414
+			'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1415
+		);
1416
+		$this->_template_args['admin_page_content'] = EEH_HTML::div(
1417
+			$form_handler->display(),
1418
+			'',
1419
+			'padding'
1420
+		);
1421
+		$this->display_admin_page_with_sidebar();
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * Update the privacy settings from form data
1427
+	 *
1428
+	 * @throws EE_Error
1429
+	 */
1430
+	public function updatePrivacySettings()
1431
+	{
1432
+		$form_handler = $this->loader->getShared(
1433
+			'EventEspresso\core\domain\services\admin\privacy\forms\PrivacySettingsFormHandler'
1434
+		);
1435
+		$success      = $form_handler->process($this->get_request_data());
1436
+		$this->_redirect_after_action(
1437
+			$success,
1438
+			esc_html__('Registration Form Options', 'event_espresso'),
1439
+			'updated',
1440
+			['action' => 'privacy_settings']
1441
+		);
1442
+	}
1443 1443
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -246,19 +246,19 @@  discard block
 block discarded – undo
246 246
                 'event_espresso'
247 247
             )
248 248
         );
249
-        EE_Registry::$i18n_js_strings['error_occurred']          = wp_strip_all_tags(
249
+        EE_Registry::$i18n_js_strings['error_occurred'] = wp_strip_all_tags(
250 250
             esc_html__(
251 251
                 'An error occurred! Please refresh the page and try again.',
252 252
                 'event_espresso'
253 253
             )
254 254
         );
255
-        EE_Registry::$i18n_js_strings['confirm_delete_state']    = wp_strip_all_tags(
255
+        EE_Registry::$i18n_js_strings['confirm_delete_state'] = wp_strip_all_tags(
256 256
             esc_html__(
257 257
                 'Are you sure you want to delete this State / Province?',
258 258
                 'event_espresso'
259 259
             )
260 260
         );
261
-        EE_Registry::$i18n_js_strings['ajax_url']                = admin_url(
261
+        EE_Registry::$i18n_js_strings['ajax_url'] = admin_url(
262 262
             'admin-ajax.php?page=espresso_general_settings',
263 263
             is_ssl() ? 'https://' : 'http://'
264 264
         );
@@ -287,12 +287,12 @@  discard block
 block discarded – undo
287 287
         wp_enqueue_script('thickbox');
288 288
         wp_register_script(
289 289
             'organization_settings',
290
-            GEN_SET_ASSETS_URL . 'your_organization_settings.js',
290
+            GEN_SET_ASSETS_URL.'your_organization_settings.js',
291 291
             ['jquery', 'media-upload', 'thickbox'],
292 292
             EVENT_ESPRESSO_VERSION,
293 293
             true
294 294
         );
295
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
295
+        wp_register_style('organization-css', GEN_SET_ASSETS_URL.'organization.css', [], EVENT_ESPRESSO_VERSION);
296 296
         wp_enqueue_script('organization_settings');
297 297
         wp_enqueue_style('organization-css');
298 298
         $confirm_image_delete = [
@@ -315,12 +315,12 @@  discard block
 block discarded – undo
315 315
         // scripts
316 316
         wp_register_script(
317 317
             'gen_settings_countries',
318
-            GEN_SET_ASSETS_URL . 'gen_settings_countries.js',
318
+            GEN_SET_ASSETS_URL.'gen_settings_countries.js',
319 319
             ['ee_admin_js'],
320 320
             EVENT_ESPRESSO_VERSION,
321 321
             true
322 322
         );
323
-        wp_register_style('organization-css', GEN_SET_ASSETS_URL . 'organization.css', [], EVENT_ESPRESSO_VERSION);
323
+        wp_register_style('organization-css', GEN_SET_ASSETS_URL.'organization.css', [], EVENT_ESPRESSO_VERSION);
324 324
         wp_enqueue_script('gen_settings_countries');
325 325
         wp_enqueue_style('organization-css');
326 326
     }
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
         $this->_set_add_edit_form_tags('update_espresso_page_settings');
369 369
         $this->_set_publish_post_box_vars(null, false, false, null, false);
370 370
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
371
-            GEN_SET_TEMPLATE_PATH . 'espresso_page_settings.template.php',
371
+            GEN_SET_TEMPLATE_PATH.'espresso_page_settings.template.php',
372 372
             $this->_template_args,
373 373
             true
374 374
         );
@@ -385,12 +385,12 @@  discard block
 block discarded – undo
385 385
     {
386 386
         $this->core_config = EE_Registry::instance()->CFG->core;
387 387
         // capture incoming request data && set page IDs
388
-        $this->core_config->reg_page_id       = $this->request->getRequestParam(
388
+        $this->core_config->reg_page_id = $this->request->getRequestParam(
389 389
             'reg_page_id',
390 390
             $this->core_config->reg_page_id,
391 391
             DataType::INT
392 392
         );
393
-        $this->core_config->txn_page_id       = $this->request->getRequestParam(
393
+        $this->core_config->txn_page_id = $this->request->getRequestParam(
394 394
             'txn_page_id',
395 395
             $this->core_config->txn_page_id,
396 396
             DataType::INT
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
             $this->core_config->thank_you_page_id,
401 401
             DataType::INT
402 402
         );
403
-        $this->core_config->cancel_page_id    = $this->request->getRequestParam(
403
+        $this->core_config->cancel_page_id = $this->request->getRequestParam(
404 404
             'cancel_page_id',
405 405
             $this->core_config->cancel_page_id,
406 406
             DataType::INT
@@ -666,16 +666,16 @@  discard block
 block discarded – undo
666 666
             $country->ID(),
667 667
             $country
668 668
         );
669
-        $this->_template_args['country_states_settings']  = $this->display_country_states(
669
+        $this->_template_args['country_states_settings'] = $this->display_country_states(
670 670
             $country->ID(),
671 671
             $country
672 672
         );
673
-        $this->_template_args['CNT_name_for_site']        = $country->name();
673
+        $this->_template_args['CNT_name_for_site'] = $country->name();
674 674
 
675 675
         $this->_set_add_edit_form_tags('update_country_settings');
676 676
         $this->_set_publish_post_box_vars(null, false, false, null, false);
677 677
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
678
-            GEN_SET_TEMPLATE_PATH . 'countries_settings.template.php',
678
+            GEN_SET_TEMPLATE_PATH.'countries_settings.template.php',
679 679
             $this->_template_args,
680 680
             true
681 681
         );
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
         $CNT_ISO          = $this->getCountryISO($CNT_ISO);
700 700
         $CNT_ISO_for_site = $this->getCountryIsoForSite();
701 701
 
702
-        if (! $CNT_ISO) {
702
+        if ( ! $CNT_ISO) {
703 703
             return '';
704 704
         }
705 705
 
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
         $CNT_cur_disabled                         = $CNT_ISO !== $CNT_ISO_for_site;
713 713
         $this->_template_args['CNT_cur_disabled'] = $CNT_cur_disabled;
714 714
 
715
-        $country_input_types            = [
715
+        $country_input_types = [
716 716
             'CNT_active'      => [
717 717
                 'type'             => 'RADIO_BTN',
718 718
                 'input_name'       => "cntry[$CNT_ISO]",
@@ -837,8 +837,8 @@  discard block
 block discarded – undo
837 837
             $country,
838 838
             $country_input_types
839 839
         );
840
-        $country_details_settings       = EEH_Template::display_template(
841
-            GEN_SET_TEMPLATE_PATH . 'country_details_settings.template.php',
840
+        $country_details_settings = EEH_Template::display_template(
841
+            GEN_SET_TEMPLATE_PATH.'country_details_settings.template.php',
842 842
             $this->_template_args,
843 843
             true
844 844
         );
@@ -872,7 +872,7 @@  discard block
 block discarded – undo
872 872
     public function display_country_states(string $CNT_ISO = '', ?EE_Country $country = null): string
873 873
     {
874 874
         $CNT_ISO = $this->getCountryISO($CNT_ISO);
875
-        if (! $CNT_ISO) {
875
+        if ( ! $CNT_ISO) {
876 876
             return '';
877 877
         }
878 878
         // for ajax
@@ -934,8 +934,8 @@  discard block
 block discarded – undo
934 934
                         GEN_SET_ADMIN_URL
935 935
                     );
936 936
 
937
-                    $this->_template_args['states'][ $STA_ID ]['inputs']           = $inputs;
938
-                    $this->_template_args['states'][ $STA_ID ]['delete_state_url'] = $delete_state_url;
937
+                    $this->_template_args['states'][$STA_ID]['inputs']           = $inputs;
938
+                    $this->_template_args['states'][$STA_ID]['delete_state_url'] = $delete_state_url;
939 939
                 }
940 940
             }
941 941
         } else {
@@ -948,7 +948,7 @@  discard block
 block discarded – undo
948 948
         );
949 949
 
950 950
         $state_details_settings = EEH_Template::display_template(
951
-            GEN_SET_TEMPLATE_PATH . 'state_details_settings.template.php',
951
+            GEN_SET_TEMPLATE_PATH.'state_details_settings.template.php',
952 952
             $this->_template_args,
953 953
             true
954 954
         );
@@ -980,7 +980,7 @@  discard block
 block discarded – undo
980 980
     {
981 981
         $success = true;
982 982
         $CNT_ISO = $this->getCountryISO('');
983
-        if (! $CNT_ISO) {
983
+        if ( ! $CNT_ISO) {
984 984
             EE_Error::add_error(
985 985
                 esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
986 986
                 __FILE__,
@@ -990,7 +990,7 @@  discard block
 block discarded – undo
990 990
             $success = false;
991 991
         }
992 992
         $STA_abbrev = $this->request->getRequestParam('STA_abbrev');
993
-        if (! $STA_abbrev) {
993
+        if ( ! $STA_abbrev) {
994 994
             EE_Error::add_error(
995 995
                 esc_html__('No State ISO code or an invalid State ISO code was received.', 'event_espresso'),
996 996
                 __FILE__,
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
             $success = false;
1001 1001
         }
1002 1002
         $STA_name = $this->request->getRequestParam('STA_name');
1003
-        if (! $STA_name) {
1003
+        if ( ! $STA_name) {
1004 1004
             EE_Error::add_error(
1005 1005
                 esc_html__('No State name or an invalid State name was received.', 'event_espresso'),
1006 1006
                 __FILE__,
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
                 'STA_name'   => $STA_name,
1018 1018
                 'STA_active' => true,
1019 1019
             ];
1020
-            $success       = EEM_State::instance()->insert($cols_n_values);
1020
+            $success = EEM_State::instance()->insert($cols_n_values);
1021 1021
             EE_Error::add_success(esc_html__('The State was added successfully.', 'event_espresso'));
1022 1022
         }
1023 1023
 
@@ -1049,7 +1049,7 @@  discard block
 block discarded – undo
1049 1049
         $STA_ID     = $this->request->getRequestParam('STA_ID');
1050 1050
         $STA_abbrev = $this->request->getRequestParam('STA_abbrev');
1051 1051
 
1052
-        if (! $STA_ID) {
1052
+        if ( ! $STA_ID) {
1053 1053
             EE_Error::add_error(
1054 1054
                 esc_html__('No State ID or an invalid State ID was received.', 'event_espresso'),
1055 1055
                 __FILE__,
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
     protected function _update_country_settings()
1096 1096
     {
1097 1097
         $CNT_ISO = $this->getCountryISO();
1098
-        if (! $CNT_ISO) {
1098
+        if ( ! $CNT_ISO) {
1099 1099
             EE_Error::add_error(
1100 1100
                 esc_html__('No Country ISO code or an invalid Country ISO code was received.', 'event_espresso'),
1101 1101
                 __FILE__,
@@ -1119,15 +1119,15 @@  discard block
 block discarded – undo
1119 1119
                 $country->currency_code()
1120 1120
             )
1121 1121
         );
1122
-        $cols_n_values['CNT_cur_single']  = $this->request->getRequestParam(
1122
+        $cols_n_values['CNT_cur_single'] = $this->request->getRequestParam(
1123 1123
             "cntry[$CNT_ISO][CNT_cur_single]",
1124 1124
             $country->currency_name_single()
1125 1125
         );
1126
-        $cols_n_values['CNT_cur_plural']  = $this->request->getRequestParam(
1126
+        $cols_n_values['CNT_cur_plural'] = $this->request->getRequestParam(
1127 1127
             "cntry[$CNT_ISO][CNT_cur_plural]",
1128 1128
             $country->currency_name_plural()
1129 1129
         );
1130
-        $cols_n_values['CNT_cur_sign']    = $this->request->getRequestParam(
1130
+        $cols_n_values['CNT_cur_sign'] = $this->request->getRequestParam(
1131 1131
             "cntry[$CNT_ISO][CNT_cur_sign]",
1132 1132
             $country->currency_sign()
1133 1133
         );
@@ -1144,15 +1144,15 @@  discard block
 block discarded – undo
1144 1144
             "cntry[$CNT_ISO][CNT_cur_dec_mrk]",
1145 1145
             $country->currency_decimal_mark()
1146 1146
         );
1147
-        $cols_n_values['CNT_cur_thsnds']  = $this->request->getRequestParam(
1147
+        $cols_n_values['CNT_cur_thsnds'] = $this->request->getRequestParam(
1148 1148
             "cntry[$CNT_ISO][CNT_cur_thsnds]",
1149 1149
             $country->currency_thousands_separator()
1150 1150
         );
1151
-        $cols_n_values['CNT_tel_code']    = $this->request->getRequestParam(
1151
+        $cols_n_values['CNT_tel_code'] = $this->request->getRequestParam(
1152 1152
             "cntry[$CNT_ISO][CNT_tel_code]",
1153 1153
             $country->telephoneCode()
1154 1154
         );
1155
-        $cols_n_values['CNT_active']      = $this->request->getRequestParam(
1155
+        $cols_n_values['CNT_active'] = $this->request->getRequestParam(
1156 1156
             "cntry[$CNT_ISO][CNT_active]",
1157 1157
             $country->isActive(),
1158 1158
             DataType::BOOL
@@ -1175,7 +1175,7 @@  discard block
 block discarded – undo
1175 1175
             $this->request->getRequestParam('states', [], DataType::STRING, true)
1176 1176
         );
1177 1177
 
1178
-        if (! empty($states) && $success !== false) {
1178
+        if ( ! empty($states) && $success !== false) {
1179 1179
             // loop thru state data ( looks like : states[75][STA_name] )
1180 1180
             foreach ($states as $STA_ID => $state) {
1181 1181
                 $cols_n_values = [
@@ -1233,7 +1233,7 @@  discard block
 block discarded – undo
1233 1233
         return '
1234 1234
 			<tr>
1235 1235
 				<th>
1236
-					' . $label . '
1236
+					' . $label.'
1237 1237
 				</th>';
1238 1238
     }
1239 1239
 
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
     {
1249 1249
         return '
1250 1250
 				<td class="general-settings-country-input-td">
1251
-					' . $input . '
1251
+					' . $input.'
1252 1252
 				</td>
1253 1253
 			</tr>';
1254 1254
     }
@@ -1277,7 +1277,7 @@  discard block
 block discarded – undo
1277 1277
     {
1278 1278
         return '
1279 1279
 				<td class="general-settings-country-state-input-td">
1280
-					' . $input . '
1280
+					' . $input.'
1281 1281
 				</td>';
1282 1282
     }
1283 1283
 
@@ -1297,9 +1297,9 @@  discard block
 block discarded – undo
1297 1297
             ['post' => $ee_page_id, 'action' => 'edit'],
1298 1298
             admin_url('post.php')
1299 1299
         );
1300
-        $links    = '<a href="' . esc_url_raw($edit_url) . '" >' . esc_html__('Edit', 'event_espresso') . '</a>';
1300
+        $links = '<a href="'.esc_url_raw($edit_url).'" >'.esc_html__('Edit', 'event_espresso').'</a>';
1301 1301
         $links    .= ' &nbsp;|&nbsp; ';
1302
-        $links    .= '<a href="' . get_permalink($ee_page_id) . '" >' . esc_html__('View', 'event_espresso') . '</a>';
1302
+        $links    .= '<a href="'.get_permalink($ee_page_id).'" >'.esc_html__('View', 'event_espresso').'</a>';
1303 1303
 
1304 1304
         return $links;
1305 1305
     }
@@ -1333,8 +1333,8 @@  discard block
 block discarded – undo
1333 1333
         }
1334 1334
 
1335 1335
         return '
1336
-        <span class="ee-page-status ' . $pg_class . '"><strong>' . $pg_status . '</strong></span>
1337
-        <span class="ee-page-status ' . $sc_class . '"><strong>' . $sc_status . '</strong></span>';
1336
+        <span class="ee-page-status ' . $pg_class.'"><strong>'.$pg_status.'</strong></span>
1337
+        <span class="ee-page-status ' . $sc_class.'"><strong>'.$sc_status.'</strong></span>';
1338 1338
     }
1339 1339
 
1340 1340
 
@@ -1354,7 +1354,7 @@  discard block
 block discarded – undo
1354 1354
         bool $echo = true
1355 1355
     ): string {
1356 1356
         global $wpdb;
1357
-        $items  = $wpdb->get_results(
1357
+        $items = $wpdb->get_results(
1358 1358
             $wpdb->prepare(
1359 1359
                 "SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status != 'trash' ORDER BY menu_order",
1360 1360
                 $parent
@@ -1369,8 +1369,8 @@  discard block
 block discarded – undo
1369 1369
                 $post_title = wp_strip_all_tags($item->post_title);
1370 1370
                 $pad    = str_repeat('&nbsp;', $level * 3);
1371 1371
                 $option = "\n\t";
1372
-                $option .= '<option class="level-' . $level . '" ';
1373
-                $option .= 'value="' . $ID . '" ';
1372
+                $option .= '<option class="level-'.$level.'" ';
1373
+                $option .= 'value="'.$ID.'" ';
1374 1374
                 $option .= $ID === absint($default) ? ' selected' : '';
1375 1375
                 $option .= '>';
1376 1376
                 $option .= "$pad {$post_title}";
Please login to merge, or discard this patch.
core/domain/services/graphql/mutators/EntityReorder.php 2 patches
Indentation   +153 added lines, -153 removed lines patch added patch discarded remove patch
@@ -20,157 +20,157 @@
 block discarded – undo
20 20
 
21 21
 class EntityReorder
22 22
 {
23
-    /**
24
-     * Defines the mutation data modification closure.
25
-     *
26
-     * @return callable
27
-     */
28
-    public static function mutateAndGetPayload()
29
-    {
30
-        /**
31
-         * Updates an entity.
32
-         *
33
-         * @param array       $input   The input for the mutation
34
-         * @param AppContext  $context The AppContext passed down to all resolvers
35
-         * @param ResolveInfo $info    The ResolveInfo passed down to all resolvers
36
-         * @return array
37
-         * @throws UserError
38
-         * @throws InvalidArgumentException
39
-         * @throws InvalidInterfaceException
40
-         * @throws InvalidDataTypeException
41
-         * @throws Exception
42
-         */
43
-        return static function (array $input, AppContext $context, ResolveInfo $info): array {
44
-            /**
45
-             * Stop now if a user isn't allowed to reorder.
46
-             */
47
-            if (! current_user_can('ee_edit_events')) {
48
-                throw new UserError(
49
-                    esc_html__('Sorry, you do not have the required permissions to reorder entities', 'event_espresso')
50
-                );
51
-            }
52
-            $ok = true;
53
-            // 'entities', 'entityGuids', 'entity_db_ids', 'entityType', 'keyPrefix'
54
-            $details = EntityReorder::prepareEntityDetailsFromInput($input);
55
-            $orderKey  = $details['keyPrefix'] . '_order'; // e.g. "TKT_order"
56
-
57
-            // We do not want to continue reorder if one fails.
58
-            // Thus wrap whole loop in try-catch
59
-            try {
60
-                foreach ($details['entity_db_ids'] as $order => $entityDbid) {
61
-                    $args = [ $orderKey => $order + 1 ];
62
-                    $ok = $details['entities'][ $entityDbid ]->save($args) ? $ok : false;
63
-                }
64
-            } catch (Exception $exception) {
65
-                new ExceptionStackTraceDisplay(
66
-                    new RuntimeException(
67
-                        sprintf(
68
-                            esc_html__(
69
-                                'Failed to update order because of the following error(s): %1$s',
70
-                                'event_espresso'
71
-                            ),
72
-                            $exception->getMessage()
73
-                        )
74
-                    )
75
-                );
76
-            }
77
-
78
-            return compact('ok');
79
-        };
80
-    }
81
-
82
-
83
-    /**
84
-     * Prepares entity details to use for mutations
85
-     * input might look something like:
86
-     *  {
87
-     *      'clientMutationId' => 'REORDER_ENTITIES',
88
-     *      'entityIds' => {
89
-     *          'RGF0ZXRpbWU6Mg==',
90
-     *          'RGF0ZXRpbWU6MQ==',
91
-     *      },
92
-     *      'entityType' => 'Datetime',
93
-     *  }
94
-     *
95
-     * @param array $input The input for the mutation
96
-     * @return array
97
-     * @throws EE_Error
98
-     * @throws ReflectionException
99
-     */
100
-    public static function prepareEntityDetailsFromInput(array $input): array
101
-    {
102
-        $entityGuids = ! empty($input['entityIds']) ? array_map('sanitize_text_field', (array) $input['entityIds']) : [];
103
-        $entityType  = ! empty($input['entityType']) ? sanitize_text_field($input['entityType']) : null;
104
-
105
-        /**
106
-         * Make sure we have the IDs and entity type
107
-         */
108
-        if (empty($entityGuids) || empty($entityType)) {
109
-            throw new UserError(
110
-                // translators: the placeholders are the names of the fields
111
-                sprintf(esc_html__('%1$s and %2$s are required.', 'event_espresso'), 'entityIds', 'entityType')
112
-            );
113
-        }
114
-
115
-        $model = EE_Registry::instance()->load_model($entityType);
116
-
117
-        if (!($model instanceof EEM_Base)) {
118
-            throw new UserError(
119
-                esc_html__(
120
-                    'A valid data model could not be obtained. Did you supply a valid entity type?',
121
-                    'event_espresso'
122
-                )
123
-            );
124
-        }
125
-
126
-        // convert GUIDs to DB IDs
127
-        $entity_db_ids = array_map(
128
-            function ($entityGuid) {
129
-                $id_parts = Relay::fromGlobalId($entityGuid);
130
-                return ! empty($id_parts['id']) ? absint($id_parts['id']) : 0;
131
-            },
132
-            $entityGuids
133
-        );
134
-        // remove 0 values
135
-        $entity_db_ids = array_filter($entity_db_ids);
136
-
137
-        /**
138
-         * If we could not get DB IDs for some GUIDs
139
-         */
140
-        if (count($entity_db_ids) !== count($entityGuids)) {
141
-            throw new UserError(
142
-                esc_html__('Sorry, operation cancelled due to missing or invalid entity IDs.', 'event_espresso')
143
-            );
144
-        }
145
-
146
-        // e.g. DTT_ID, TKT_ID
147
-        $primaryKey = $model->get_primary_key_field()->get_name();
148
-        // e.g. "DTT_ID" will give us "DTT"
149
-        $keyPrefix = explode('_', $primaryKey)[0];
150
-        $deletedKey  = $keyPrefix . '_deleted'; // e.g. "TKT_deleted"
151
-
152
-        $entities = $model::instance()->get_all([
153
-            [
154
-                $primaryKey => ['IN', $entity_db_ids],
155
-                $deletedKey => ['IN', [true, false]],
156
-            ],
157
-        ]);
158
-
159
-        /**
160
-         * If we could not get exactly same number of entities for the given DB IDs
161
-         */
162
-        if (count($entity_db_ids) !== count($entities)) {
163
-            throw new UserError(esc_html__('Sorry, operation cancelled due to missing entities.', 'event_espresso'));
164
-        }
165
-
166
-        // Make sure we have an instance for every ID.
167
-        foreach ($entity_db_ids as $entity_db_id) {
168
-            if (isset($entities[ $entity_db_id ]) && $entities[ $entity_db_id ] instanceof EE_Base_Class) {
169
-                continue;
170
-            }
171
-            throw new UserError(esc_html__('Sorry, operation cancelled due to invalid entities.', 'event_espresso'));
172
-        }
173
-
174
-        return compact('entities', 'entityGuids', 'entity_db_ids', 'entityType', 'keyPrefix');
175
-    }
23
+	/**
24
+	 * Defines the mutation data modification closure.
25
+	 *
26
+	 * @return callable
27
+	 */
28
+	public static function mutateAndGetPayload()
29
+	{
30
+		/**
31
+		 * Updates an entity.
32
+		 *
33
+		 * @param array       $input   The input for the mutation
34
+		 * @param AppContext  $context The AppContext passed down to all resolvers
35
+		 * @param ResolveInfo $info    The ResolveInfo passed down to all resolvers
36
+		 * @return array
37
+		 * @throws UserError
38
+		 * @throws InvalidArgumentException
39
+		 * @throws InvalidInterfaceException
40
+		 * @throws InvalidDataTypeException
41
+		 * @throws Exception
42
+		 */
43
+		return static function (array $input, AppContext $context, ResolveInfo $info): array {
44
+			/**
45
+			 * Stop now if a user isn't allowed to reorder.
46
+			 */
47
+			if (! current_user_can('ee_edit_events')) {
48
+				throw new UserError(
49
+					esc_html__('Sorry, you do not have the required permissions to reorder entities', 'event_espresso')
50
+				);
51
+			}
52
+			$ok = true;
53
+			// 'entities', 'entityGuids', 'entity_db_ids', 'entityType', 'keyPrefix'
54
+			$details = EntityReorder::prepareEntityDetailsFromInput($input);
55
+			$orderKey  = $details['keyPrefix'] . '_order'; // e.g. "TKT_order"
56
+
57
+			// We do not want to continue reorder if one fails.
58
+			// Thus wrap whole loop in try-catch
59
+			try {
60
+				foreach ($details['entity_db_ids'] as $order => $entityDbid) {
61
+					$args = [ $orderKey => $order + 1 ];
62
+					$ok = $details['entities'][ $entityDbid ]->save($args) ? $ok : false;
63
+				}
64
+			} catch (Exception $exception) {
65
+				new ExceptionStackTraceDisplay(
66
+					new RuntimeException(
67
+						sprintf(
68
+							esc_html__(
69
+								'Failed to update order because of the following error(s): %1$s',
70
+								'event_espresso'
71
+							),
72
+							$exception->getMessage()
73
+						)
74
+					)
75
+				);
76
+			}
77
+
78
+			return compact('ok');
79
+		};
80
+	}
81
+
82
+
83
+	/**
84
+	 * Prepares entity details to use for mutations
85
+	 * input might look something like:
86
+	 *  {
87
+	 *      'clientMutationId' => 'REORDER_ENTITIES',
88
+	 *      'entityIds' => {
89
+	 *          'RGF0ZXRpbWU6Mg==',
90
+	 *          'RGF0ZXRpbWU6MQ==',
91
+	 *      },
92
+	 *      'entityType' => 'Datetime',
93
+	 *  }
94
+	 *
95
+	 * @param array $input The input for the mutation
96
+	 * @return array
97
+	 * @throws EE_Error
98
+	 * @throws ReflectionException
99
+	 */
100
+	public static function prepareEntityDetailsFromInput(array $input): array
101
+	{
102
+		$entityGuids = ! empty($input['entityIds']) ? array_map('sanitize_text_field', (array) $input['entityIds']) : [];
103
+		$entityType  = ! empty($input['entityType']) ? sanitize_text_field($input['entityType']) : null;
104
+
105
+		/**
106
+		 * Make sure we have the IDs and entity type
107
+		 */
108
+		if (empty($entityGuids) || empty($entityType)) {
109
+			throw new UserError(
110
+				// translators: the placeholders are the names of the fields
111
+				sprintf(esc_html__('%1$s and %2$s are required.', 'event_espresso'), 'entityIds', 'entityType')
112
+			);
113
+		}
114
+
115
+		$model = EE_Registry::instance()->load_model($entityType);
116
+
117
+		if (!($model instanceof EEM_Base)) {
118
+			throw new UserError(
119
+				esc_html__(
120
+					'A valid data model could not be obtained. Did you supply a valid entity type?',
121
+					'event_espresso'
122
+				)
123
+			);
124
+		}
125
+
126
+		// convert GUIDs to DB IDs
127
+		$entity_db_ids = array_map(
128
+			function ($entityGuid) {
129
+				$id_parts = Relay::fromGlobalId($entityGuid);
130
+				return ! empty($id_parts['id']) ? absint($id_parts['id']) : 0;
131
+			},
132
+			$entityGuids
133
+		);
134
+		// remove 0 values
135
+		$entity_db_ids = array_filter($entity_db_ids);
136
+
137
+		/**
138
+		 * If we could not get DB IDs for some GUIDs
139
+		 */
140
+		if (count($entity_db_ids) !== count($entityGuids)) {
141
+			throw new UserError(
142
+				esc_html__('Sorry, operation cancelled due to missing or invalid entity IDs.', 'event_espresso')
143
+			);
144
+		}
145
+
146
+		// e.g. DTT_ID, TKT_ID
147
+		$primaryKey = $model->get_primary_key_field()->get_name();
148
+		// e.g. "DTT_ID" will give us "DTT"
149
+		$keyPrefix = explode('_', $primaryKey)[0];
150
+		$deletedKey  = $keyPrefix . '_deleted'; // e.g. "TKT_deleted"
151
+
152
+		$entities = $model::instance()->get_all([
153
+			[
154
+				$primaryKey => ['IN', $entity_db_ids],
155
+				$deletedKey => ['IN', [true, false]],
156
+			],
157
+		]);
158
+
159
+		/**
160
+		 * If we could not get exactly same number of entities for the given DB IDs
161
+		 */
162
+		if (count($entity_db_ids) !== count($entities)) {
163
+			throw new UserError(esc_html__('Sorry, operation cancelled due to missing entities.', 'event_espresso'));
164
+		}
165
+
166
+		// Make sure we have an instance for every ID.
167
+		foreach ($entity_db_ids as $entity_db_id) {
168
+			if (isset($entities[ $entity_db_id ]) && $entities[ $entity_db_id ] instanceof EE_Base_Class) {
169
+				continue;
170
+			}
171
+			throw new UserError(esc_html__('Sorry, operation cancelled due to invalid entities.', 'event_espresso'));
172
+		}
173
+
174
+		return compact('entities', 'entityGuids', 'entity_db_ids', 'entityType', 'keyPrefix');
175
+	}
176 176
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -40,11 +40,11 @@  discard block
 block discarded – undo
40 40
          * @throws InvalidDataTypeException
41 41
          * @throws Exception
42 42
          */
43
-        return static function (array $input, AppContext $context, ResolveInfo $info): array {
43
+        return static function(array $input, AppContext $context, ResolveInfo $info): array {
44 44
             /**
45 45
              * Stop now if a user isn't allowed to reorder.
46 46
              */
47
-            if (! current_user_can('ee_edit_events')) {
47
+            if ( ! current_user_can('ee_edit_events')) {
48 48
                 throw new UserError(
49 49
                     esc_html__('Sorry, you do not have the required permissions to reorder entities', 'event_espresso')
50 50
                 );
@@ -52,14 +52,14 @@  discard block
 block discarded – undo
52 52
             $ok = true;
53 53
             // 'entities', 'entityGuids', 'entity_db_ids', 'entityType', 'keyPrefix'
54 54
             $details = EntityReorder::prepareEntityDetailsFromInput($input);
55
-            $orderKey  = $details['keyPrefix'] . '_order'; // e.g. "TKT_order"
55
+            $orderKey = $details['keyPrefix'].'_order'; // e.g. "TKT_order"
56 56
 
57 57
             // We do not want to continue reorder if one fails.
58 58
             // Thus wrap whole loop in try-catch
59 59
             try {
60 60
                 foreach ($details['entity_db_ids'] as $order => $entityDbid) {
61
-                    $args = [ $orderKey => $order + 1 ];
62
-                    $ok = $details['entities'][ $entityDbid ]->save($args) ? $ok : false;
61
+                    $args = [$orderKey => $order + 1];
62
+                    $ok = $details['entities'][$entityDbid]->save($args) ? $ok : false;
63 63
                 }
64 64
             } catch (Exception $exception) {
65 65
                 new ExceptionStackTraceDisplay(
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 
115 115
         $model = EE_Registry::instance()->load_model($entityType);
116 116
 
117
-        if (!($model instanceof EEM_Base)) {
117
+        if ( ! ($model instanceof EEM_Base)) {
118 118
             throw new UserError(
119 119
                 esc_html__(
120 120
                     'A valid data model could not be obtained. Did you supply a valid entity type?',
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 
126 126
         // convert GUIDs to DB IDs
127 127
         $entity_db_ids = array_map(
128
-            function ($entityGuid) {
128
+            function($entityGuid) {
129 129
                 $id_parts = Relay::fromGlobalId($entityGuid);
130 130
                 return ! empty($id_parts['id']) ? absint($id_parts['id']) : 0;
131 131
             },
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         $primaryKey = $model->get_primary_key_field()->get_name();
148 148
         // e.g. "DTT_ID" will give us "DTT"
149 149
         $keyPrefix = explode('_', $primaryKey)[0];
150
-        $deletedKey  = $keyPrefix . '_deleted'; // e.g. "TKT_deleted"
150
+        $deletedKey = $keyPrefix.'_deleted'; // e.g. "TKT_deleted"
151 151
 
152 152
         $entities = $model::instance()->get_all([
153 153
             [
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 
166 166
         // Make sure we have an instance for every ID.
167 167
         foreach ($entity_db_ids as $entity_db_id) {
168
-            if (isset($entities[ $entity_db_id ]) && $entities[ $entity_db_id ] instanceof EE_Base_Class) {
168
+            if (isset($entities[$entity_db_id]) && $entities[$entity_db_id] instanceof EE_Base_Class) {
169 169
                 continue;
170 170
             }
171 171
             throw new UserError(esc_html__('Sorry, operation cancelled due to invalid entities.', 'event_espresso'));
Please login to merge, or discard this patch.
templates/txn_admin_details_main_meta_box_txn_details.template.php 2 patches
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -83,21 +83,21 @@  discard block
 block discarded – undo
83 83
     </div>
84 84
     <br class="clear" />
85 85
     <?php
86
-    $no_payments = $grand_raw_total > 0
87
-                   || $TXN_status !== EEM_Transaction::complete_status_code
88
-                   || ! empty($payments);
89
-    ?>
86
+	$no_payments = $grand_raw_total > 0
87
+				   || $TXN_status !== EEM_Transaction::complete_status_code
88
+				   || ! empty($payments);
89
+	?>
90 90
     <?php if ($attendee instanceof EE_Attendee && $no_payments) : ?>
91 91
         <?php $no_payment_text = $can_edit_payments
92
-            ? esc_html__(
93
-                'No payments have been applied to this transaction yet. Click "Apply Payment" below to make a payment.',
94
-                'event_espresso'
95
-            )
96
-            : esc_html__(
97
-                'No payments have been applied to this transaction yet.',
98
-                'event_espresso'
99
-            );
100
-        ?>
92
+			? esc_html__(
93
+				'No payments have been applied to this transaction yet. Click "Apply Payment" below to make a payment.',
94
+				'event_espresso'
95
+			)
96
+			: esc_html__(
97
+				'No payments have been applied to this transaction yet.',
98
+				'event_espresso'
99
+			);
100
+		?>
101 101
 
102 102
         <h3 class="admin-primary-mbox-h4 hdr-has-icon">
103 103
             <?php esc_html_e('Payment Details', 'event_espresso'); ?>
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
                     <?php if ($payments) : ?>
143 143
                         <?php $payment_total = 0; ?>
144 144
                         <?php foreach ($payments as $PAY_ID => $payment) :
145
-                            if (! $payment instanceof EE_Payment) {
146
-                                continue;
147
-                            }
148
-                            $existing_reg_payment_json = isset($existing_reg_payments[ $PAY_ID ])
149
-                                ? wp_json_encode($existing_reg_payments[ $PAY_ID ])
150
-                                : '{}';
151
-                            ?>
145
+							if (! $payment instanceof EE_Payment) {
146
+								continue;
147
+							}
148
+							$existing_reg_payment_json = isset($existing_reg_payments[ $PAY_ID ])
149
+								? wp_json_encode($existing_reg_payments[ $PAY_ID ])
150
+								: '{}';
151
+							?>
152 152
                             <tr id="txn-admin-payment-tr-<?php echo absint($PAY_ID); ?>" class=' jst-cntr'>
153 153
                                 <td class="jst-cntr no-pad">
154 154
                                     <span id="payment-status-<?php echo absint($PAY_ID); ?>"
@@ -177,31 +177,31 @@  discard block
 block discarded – undo
177 177
                                     <span class="ee-status--ignore">&raquo;</span>
178 178
                                     <span id="payment-gateway-<?php echo absint($PAY_ID); ?>">
179 179
                                         <?php echo($payment->payment_method() instanceof EE_Payment_Method
180
-                                            ? esc_html($payment->payment_method()->admin_name())
181
-                                            : esc_html__('Unknown', 'event_espresso')); ?>
180
+											? esc_html($payment->payment_method()->admin_name())
181
+											: esc_html__('Unknown', 'event_espresso')); ?>
182 182
                                     </span>
183 183
                                     <span id="payment-gateway-id-<?php echo absint($PAY_ID); ?>" class="hidden">
184 184
                                         <?php echo($payment->payment_method() instanceof EE_Payment_Method
185
-                                            ? esc_html($payment->payment_method()->ID())
186
-                                            : 0); ?>
185
+											? esc_html($payment->payment_method()->ID())
186
+											: 0); ?>
187 187
                                     </span>
188 188
                                 </td>
189 189
                                 <td class=' jst-rght'>
190 190
                                     <?php
191
-                                    $payment_class = $payment->amount() > 0
192
-                                        ? 'txn-admin-payment-status-' . $payment->STS_ID()
193
-                                        : 'txn-admin-payment-status-PDC';
194
-                                    ?>
191
+									$payment_class = $payment->amount() > 0
192
+										? 'txn-admin-payment-status-' . $payment->STS_ID()
193
+										: 'txn-admin-payment-status-PDC';
194
+									?>
195 195
                                     <span class="<?php echo esc_attr($payment_class); ?>">
196 196
                                         <span id="payment-amount-<?php echo absint($PAY_ID); ?>"
197 197
                                               style="display:inline;"
198 198
                                         >
199 199
                                         <?php echo EEH_Template::format_currency(
200
-                                            $payment->amount(),
201
-                                            false,
202
-                                            false
203
-                                        ); // already escaped
204
-                                        ?>
200
+											$payment->amount(),
201
+											false,
202
+											false
203
+										); // already escaped
204
+										?>
205 205
                                         </span>
206 206
                                     </span>
207 207
                                 </td>
@@ -253,9 +253,9 @@  discard block
 block discarded – undo
253 253
                             <?php $payment_total += $payment->STS_ID() == 'PAP' ? $payment->amount() : 0; ?>
254 254
                         <?php endforeach; ?>
255 255
                         <?php $pay_totals_class = $payment_total > $grand_raw_total
256
-                            ? ' important-notice'
257
-                            : '';
258
-                        ?>
256
+							? ' important-notice'
257
+							: '';
258
+						?>
259 259
                         <tr id="txn-admin-no-payments-tr" class="admin-primary-mbox-total-tr hidden">
260 260
                             <td class=" jst-rght" colspan="10">
261 261
                                 <span class="important-notice"><?php echo wp_kses($no_payment_text, AllowedTags::getAllowedTags()); ?></span>
@@ -267,27 +267,27 @@  discard block
 block discarded – undo
267 267
                             <th class=" jst-rght" colspan="9">
268 268
                         <span id="payments-total-spn">
269 269
                         <?php
270
-                        $overpaid = $payment_total > $grand_raw_total
271
-                            ? '<span id="overpaid">'
272
-                              . __('This transaction has been overpaid ! ', 'event_espresso')
273
-                              . '</span>'
274
-                            : '';
275
-                        echo $overpaid . esc_html(
276
-                            sprintf(
277
-                                __('Payments Total %s', 'event_espresso'),
278
-                                '(' . EE_Registry::instance()->CFG->currency->code . ')'
279
-                            )
280
-                        ); ?>
270
+						$overpaid = $payment_total > $grand_raw_total
271
+							? '<span id="overpaid">'
272
+							  . __('This transaction has been overpaid ! ', 'event_espresso')
273
+							  . '</span>'
274
+							: '';
275
+						echo $overpaid . esc_html(
276
+							sprintf(
277
+								__('Payments Total %s', 'event_espresso'),
278
+								'(' . EE_Registry::instance()->CFG->currency->code . ')'
279
+							)
280
+						); ?>
281 281
                         </span>
282 282
                             </th>
283 283
                             <th class=" jst-rght">
284 284
                         <span id="txn-admin-payment-total">
285 285
                         <?php
286
-                        echo EEH_Template::format_currency(
287
-                            $payment_total,
288
-                            false,
289
-                            false
290
-                        ); // already escaped ?>
286
+						echo EEH_Template::format_currency(
287
+							$payment_total,
288
+							false,
289
+							false
290
+						); // already escaped ?>
291 291
                         </span>
292 292
                             </th>
293 293
                         </tr>
@@ -388,15 +388,15 @@  discard block
 block discarded – undo
388 388
                 </span>
389 389
             <?php endif; ?>
390 390
             <?php
391
-            // Allows extend the fields at actions area.
392
-            ob_start();
393
-            do_action(
394
-                'AHEE__txn_admin_details_main_meta_box_txn_details__after_actions_buttons',
395
-                $can_edit_payments
396
-            );
397
-            $extra_actions = ob_get_clean();
398
-            echo str_replace(['<li', '</li>'], ['<span', '</span>'], $extra_actions);
399
-            ?>
391
+			// Allows extend the fields at actions area.
392
+			ob_start();
393
+			do_action(
394
+				'AHEE__txn_admin_details_main_meta_box_txn_details__after_actions_buttons',
395
+				$can_edit_payments
396
+			);
397
+			$extra_actions = ob_get_clean();
398
+			echo str_replace(['<li', '</li>'], ['<span', '</span>'], $extra_actions);
399
+			?>
400 400
         </div>
401 401
 
402 402
         <div id="txn-admin-apply-payment-dv" class="txn-admin-payment-option auto-hide" style="display: none;">
@@ -412,23 +412,23 @@  discard block
 block discarded – undo
412 412
                 style="display:none;"
413 413
             >
414 414
                 <?php
415
-                printf(
416
-                    esc_html__('Edit Payment #%s for Transaction #%s', 'event_espresso'),
417
-                    '<span class="ee-admin-payment-id"></span>',
418
-                    $txn_nmbr['value']
419
-                );
420
-                ?>
415
+				printf(
416
+					esc_html__('Edit Payment #%s for Transaction #%s', 'event_espresso'),
417
+					'<span class="ee-admin-payment-id"></span>',
418
+					$txn_nmbr['value']
419
+				);
420
+				?>
421 421
                 <span class='dashicons dashicons-money-alt'></span>
422 422
             </h2>
423 423
 
424 424
             <h2 id="admin-modal-dialog-edit-refund-h2" class="admin-modal-dialog-h2 hdr-has-icon" style="display:none;">
425 425
                 <?php
426
-                printf(
427
-                    esc_html__('Edit Refund #%s for Transaction #%s', 'event_espresso'),
428
-                    '<span class="ee-admin-payment-id"></span>',
429
-                    $txn_nmbr['value']
430
-                );
431
-                ?>
426
+				printf(
427
+					esc_html__('Edit Refund #%s for Transaction #%s', 'event_espresso'),
428
+					'<span class="ee-admin-payment-id"></span>',
429
+					$txn_nmbr['value']
430
+				);
431
+				?>
432 432
                 <span class='dashicons dashicons-money-alt'></span>
433 433
             </h2>
434 434
 
@@ -436,9 +436,9 @@  discard block
 block discarded – undo
436 436
                 style="display:none;"
437 437
             >
438 438
                 <?php
439
-                echo esc_html__('Apply a Refund to Transaction #', 'event_espresso');
440
-                echo esc_html($txn_nmbr['value']);
441
-                ?>
439
+				echo esc_html__('Apply a Refund to Transaction #', 'event_espresso');
440
+				echo esc_html($txn_nmbr['value']);
441
+				?>
442 442
                 <span class='dashicons dashicons-money-alt'></span>
443 443
             </h2>
444 444
 
@@ -551,20 +551,20 @@  discard block
 block discarded – undo
551 551
                                             <?php echo esc_attr($selected); ?>
552 552
                                         >
553 553
                                             <?php
554
-                                            echo esc_html(
555
-                                                sanitize_key($method->admin_desc())
556
-                                                    ? substr($method->admin_desc(), 0, 128)
557
-                                                    : $method->admin_name()
558
-                                            );
559
-                                            ?>&nbsp;&nbsp;
554
+											echo esc_html(
555
+												sanitize_key($method->admin_desc())
556
+													? substr($method->admin_desc(), 0, 128)
557
+													: $method->admin_name()
558
+											);
559
+											?>&nbsp;&nbsp;
560 560
                                         </option>
561 561
                                     <?php endforeach; ?>
562 562
                                 </select>
563 563
                                 <p class="description">
564 564
                                     <?php esc_html_e(
565
-                                        'Whether the payment was made via PayPal, Credit Card, Cheque, or Cash',
566
-                                        'event_espresso'
567
-                                    ); ?>
565
+										'Whether the payment was made via PayPal, Credit Card, Cheque, or Cash',
566
+										'event_espresso'
567
+									); ?>
568 568
                                 </p>
569 569
                             </div>
570 570
                         </div>
@@ -573,9 +573,9 @@  discard block
 block discarded – undo
573 573
                         admin-modal-dialog-row ee-layout-row">
574 574
                             <label for="txn-admin-payment-txn-id-chq-nmbr-inp" class="">
575 575
                                 <?php esc_html_e(
576
-                                    'TXN ID / CHQ #',
577
-                                    'event_espresso'
578
-                                ); ?>
576
+									'TXN ID / CHQ #',
577
+									'event_espresso'
578
+								); ?>
579 579
                             </label>
580 580
                             <div class='ee-layout-stack'>
581 581
                                 <input name="txn_admin_payment[txn_id_chq_nmbr]"
@@ -585,9 +585,9 @@  discard block
 block discarded – undo
585 585
                                 />
586 586
                                 <p class="description">
587 587
                                     <?php esc_html_e(
588
-                                        'The Transaction ID sent back from the payment gateway, or the Cheque #',
589
-                                        'event_espresso'
590
-                                    ); ?>
588
+										'The Transaction ID sent back from the payment gateway, or the Cheque #',
589
+										'event_espresso'
590
+									); ?>
591 591
                                 </p>
592 592
                             </div>
593 593
                         </div>
@@ -605,9 +605,9 @@  discard block
 block discarded – undo
605 605
                                 />
606 606
                                 <p class="description">
607 607
                                     <?php esc_html_e(
608
-                                        'The gateway response string (optional)',
609
-                                        'event_espresso'
610
-                                    ); ?>
608
+										'The gateway response string (optional)',
609
+										'event_espresso'
610
+									); ?>
611 611
                                 </p>
612 612
                             </div>
613 613
                         </div>
@@ -616,9 +616,9 @@  discard block
 block discarded – undo
616 616
                             ee-layout-row">
617 617
                             <label for="txn-admin-payment-status-slct" class="">
618 618
                                 <?php esc_html_e(
619
-                                    'Payment Status',
620
-                                    'event_espresso'
621
-                                ); ?>
619
+									'Payment Status',
620
+									'event_espresso'
621
+								); ?>
622 622
                             </label>
623 623
                             <div class='ee-layout-stack'>
624 624
                                 <select name="txn_admin_payment[status]"
@@ -628,10 +628,10 @@  discard block
 block discarded – undo
628 628
                                 >
629 629
                                     <?php foreach ($payment_status as $STS_ID => $STS_code) : ?>
630 630
                                         <?php
631
-                                        $selected = $STS_ID == 'PAP'
632
-                                            ? 'selected'
633
-                                            : '';
634
-                                        ?>
631
+										$selected = $STS_ID == 'PAP'
632
+											? 'selected'
633
+											: '';
634
+										?>
635 635
                                         <option id="payment-status-opt-<?php echo esc_attr($STS_ID); ?>"
636 636
                                                 value="<?php echo esc_attr($STS_ID); ?>"
637 637
                                             <?php echo esc_attr($selected); ?>
@@ -642,10 +642,10 @@  discard block
 block discarded – undo
642 642
                                 </select>
643 643
                                 <p class="description">
644 644
                                     <?php
645
-                                    esc_html_e(
646
-                                        'Whether the payment was approved, cancelled, declined or failed after submission to the gateway',
647
-                                        'event_espresso'
648
-                                    ); ?>
645
+									esc_html_e(
646
+										'Whether the payment was approved, cancelled, declined or failed after submission to the gateway',
647
+										'event_espresso'
648
+									); ?>
649 649
                                 </p>
650 650
                             </div>
651 651
                         </div>
@@ -663,9 +663,9 @@  discard block
 block discarded – undo
663 663
                                 />
664 664
                                 <p class="description">
665 665
                                     <?php esc_html_e(
666
-                                        'The Purchase or Sales Order Number if any (optional)',
667
-                                        'event_espresso'
668
-                                    ); ?>
666
+										'The Purchase or Sales Order Number if any (optional)',
667
+										'event_espresso'
668
+									); ?>
669 669
                                 </p>
670 670
                             </div>
671 671
                         </div>
@@ -688,9 +688,9 @@  discard block
 block discarded – undo
688 688
                                 />
689 689
                                 <p class="description">
690 690
                                     <?php esc_html_e(
691
-                                        'An extra field you may use for accounting purposes or simple notes. Defaults to the primary registrant\'s registration code.',
692
-                                        'event_espresso'
693
-                                    ); ?>
691
+										'An extra field you may use for accounting purposes or simple notes. Defaults to the primary registrant\'s registration code.',
692
+										'event_espresso'
693
+									); ?>
694 694
                                 </p>
695 695
                             </div>
696 696
                         </div>
@@ -729,9 +729,9 @@  discard block
 block discarded – undo
729 729
                                 <?php echo wp_kses($status_change_select, AllowedTags::getWithFormTags()); ?>
730 730
                                 <p class="description">
731 731
                                     <?php esc_html_e(
732
-                                        'If you wish to change the status for the registrations selected above, then select which status from this dropdown.',
733
-                                        'event_espresso'
734
-                                    ); ?>
732
+										'If you wish to change the status for the registrations selected above, then select which status from this dropdown.',
733
+										'event_espresso'
734
+									); ?>
735 735
                                 </p>
736 736
                             </div>
737 737
                         </div>
@@ -762,14 +762,14 @@  discard block
 block discarded – undo
762 762
                                 <br class="clear-float" />
763 763
                                 <p class="description">
764 764
                                     <?php printf(
765
-                                        esc_html__(
766
-                                            'By default %1$sa payment message is sent to the primary registrant%2$s after submitting this form.%3$sHowever, if you check the "Registration Messages" box, the system will also send any related messages matching the status of the registrations to %1$seach registration for this transaction%2$s.',
767
-                                            'event_espresso'
768
-                                        ),
769
-                                        '<strong>',
770
-                                        '</strong>',
771
-                                        '<br />'
772
-                                    ); ?>
765
+										esc_html__(
766
+											'By default %1$sa payment message is sent to the primary registrant%2$s after submitting this form.%3$sHowever, if you check the "Registration Messages" box, the system will also send any related messages matching the status of the registrations to %1$seach registration for this transaction%2$s.',
767
+											'event_espresso'
768
+										),
769
+										'<strong>',
770
+										'</strong>',
771
+										'<br />'
772
+									); ?>
773 773
                                 </p>
774 774
                             </div>
775 775
                         </div>
@@ -824,10 +824,10 @@  discard block
 block discarded – undo
824 824
                 style="display:none;"
825 825
             >
826 826
                 <?php printf(
827
-                    esc_html__('Delete Payment/Refund for Transaction #', 'event_espresso'),
828
-                    $txn_nmbr['value']
829
-                );
830
-                ?>
827
+					esc_html__('Delete Payment/Refund for Transaction #', 'event_espresso'),
828
+					$txn_nmbr['value']
829
+				);
830
+				?>
831 831
                 <span class='dashicons dashicons-money-alt'></span>
832 832
             </h2>
833 833
 
@@ -866,13 +866,13 @@  discard block
 block discarded – undo
866 866
                                 <?php echo wp_kses($delete_status_change_select, AllowedTags::getWithFormTags()); ?>
867 867
                                 <p class="description">
868 868
                                     <?php printf(
869
-                                        esc_html__(
870
-                                            'If you wish to change the status of all the registrations associated with this transaction after deleting this payment/refund, then select which status from this dropdown. %sNote: ALL registrations associated with this transaction will be updated to this new status.%s',
871
-                                            'event_espresso'
872
-                                        ),
873
-                                        '<strong>',
874
-                                        '</strong>'
875
-                                    ); ?>
869
+										esc_html__(
870
+											'If you wish to change the status of all the registrations associated with this transaction after deleting this payment/refund, then select which status from this dropdown. %sNote: ALL registrations associated with this transaction will be updated to this new status.%s',
871
+											'event_espresso'
872
+										),
873
+										'<strong>',
874
+										'</strong>'
875
+									); ?>
876 876
                                 </p>
877 877
                             </div>
878 878
                         </div>
@@ -889,10 +889,10 @@  discard block
 block discarded – undo
889 889
                                 />
890 890
                                 <p class="description">
891 891
                                     <?php
892
-                                    esc_html_e(
893
-                                        'If you check this box, the system will send any related registration messages matching the status of the registrations to each registration for this transaction. No Payment notifications are sent when deleting a payment.',
894
-                                        'event_espresso'
895
-                                    ); ?>
892
+									esc_html_e(
893
+										'If you check this box, the system will send any related registration messages matching the status of the registrations to each registration for this transaction. No Payment notifications are sent when deleting a payment.',
894
+										'event_espresso'
895
+									); ?>
896 896
                                 </p>
897 897
                             </div>
898 898
                         </div>
@@ -920,8 +920,8 @@  discard block
 block discarded – undo
920 920
     <?php endif; // $grand_raw_total > 0?>
921 921
 
922 922
     <?php if (WP_DEBUG) {
923
-        $delivered_messages = get_option('EED_Messages__payment', []);
924
-        if (isset($delivered_messages[ $TXN_ID ])) { ?>
923
+		$delivered_messages = get_option('EED_Messages__payment', []);
924
+		if (isset($delivered_messages[ $TXN_ID ])) { ?>
925 925
             <h4 class="admin-primary-mbox-h4 hdr-has-icon">
926 926
                 <?php esc_html_e('Messages Sent to Primary Registrant', 'event_espresso'); ?>
927 927
                 <span class="dashicons dashicons-email-alt"></span>
@@ -933,39 +933,39 @@  discard block
 block discarded – undo
933 933
                             <th class="jst-left"><?php esc_html_e('Date & Time', 'event_espresso'); ?></th>
934 934
                             <th class="jst-left"><?php esc_html_e('Message Type', 'event_espresso'); ?></th>
935 935
                             <th class="jst-left"><?php esc_html_e(
936
-                                'Payment Status Upon Sending',
937
-                                'event_espresso'
938
-                            ); ?></th>
936
+								'Payment Status Upon Sending',
937
+								'event_espresso'
938
+							); ?></th>
939 939
                             <th class="jst-left"><?php esc_html_e('TXN Status Upon Sending', 'event_espresso'); ?></th>
940 940
                         </tr>
941 941
                     </thead>
942 942
                     <tbody>
943 943
                         <?php
944
-                        foreach ($delivered_messages[ $TXN_ID ] as $timestamp => $delivered_message) :
945
-                            ?>
944
+						foreach ($delivered_messages[ $TXN_ID ] as $timestamp => $delivered_message) :
945
+							?>
946 946
                             <tr>
947 947
                                 <td class="jst-left">
948 948
                                     <?php echo esc_html(
949
-                                        date(
950
-                                            get_option('date_format') . ' ' . get_option('time_format'),
951
-                                            ($timestamp + (get_option('gmt_offset') * HOUR_IN_SECONDS))
952
-                                        )
953
-                                    ); ?>
949
+										date(
950
+											get_option('date_format') . ' ' . get_option('time_format'),
951
+											($timestamp + (get_option('gmt_offset') * HOUR_IN_SECONDS))
952
+										)
953
+									); ?>
954 954
                                 </td>
955 955
                                 <td class="jst-left"><?php
956
-                                    echo isset($delivered_message['message_type'])
957
-                                        ? esc_html($delivered_message['message_type'])
958
-                                        : ''; ?>
956
+									echo isset($delivered_message['message_type'])
957
+										? esc_html($delivered_message['message_type'])
958
+										: ''; ?>
959 959
                                 </td>
960 960
                                 <td class="jst-left"><?php
961
-                                    echo isset($delivered_message['pay_status'])
962
-                                        ? esc_html($delivered_message['pay_status'])
963
-                                        : ''; ?>
961
+									echo isset($delivered_message['pay_status'])
962
+										? esc_html($delivered_message['pay_status'])
963
+										: ''; ?>
964 964
                                 </td>
965 965
                                 <td class="jst-left"><?php
966
-                                    echo isset($delivered_message['txn_status'])
967
-                                        ? esc_html($delivered_message['txn_status'])
968
-                                        : ''; ?>
966
+									echo isset($delivered_message['txn_status'])
967
+										? esc_html($delivered_message['txn_status'])
968
+										: ''; ?>
969 969
                                 </td>
970 970
                             </tr>
971 971
                         <?php endforeach; // $delivered_messages?>
@@ -973,7 +973,7 @@  discard block
 block discarded – undo
973 973
                 </table>
974 974
             </div>
975 975
             <?php
976
-        }
977
-    }
978
-    ?>
976
+		}
977
+	}
978
+	?>
979 979
 </div>
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
                             <?php esc_html_e('ID', 'event_espresso'); ?>
114 114
                         </th>
115 115
                         <th class="txn-admin-payment-date-col jst-left">
116
-                            <?php esc_html_e('Date', 'event_espresso');?>
116
+                            <?php esc_html_e('Date', 'event_espresso'); ?>
117 117
                         </th>
118 118
                         <th class='jst-left'>
119 119
                             <?php esc_html_e('Method', 'event_espresso'); ?>
@@ -142,11 +142,11 @@  discard block
 block discarded – undo
142 142
                     <?php if ($payments) : ?>
143 143
                         <?php $payment_total = 0; ?>
144 144
                         <?php foreach ($payments as $PAY_ID => $payment) :
145
-                            if (! $payment instanceof EE_Payment) {
145
+                            if ( ! $payment instanceof EE_Payment) {
146 146
                                 continue;
147 147
                             }
148
-                            $existing_reg_payment_json = isset($existing_reg_payments[ $PAY_ID ])
149
-                                ? wp_json_encode($existing_reg_payments[ $PAY_ID ])
148
+                            $existing_reg_payment_json = isset($existing_reg_payments[$PAY_ID])
149
+                                ? wp_json_encode($existing_reg_payments[$PAY_ID])
150 150
                                 : '{}';
151 151
                             ?>
152 152
                             <tr id="txn-admin-payment-tr-<?php echo absint($PAY_ID); ?>" class=' jst-cntr'>
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
                                 <td class=' jst-rght'>
190 190
                                     <?php
191 191
                                     $payment_class = $payment->amount() > 0
192
-                                        ? 'txn-admin-payment-status-' . $payment->STS_ID()
192
+                                        ? 'txn-admin-payment-status-'.$payment->STS_ID()
193 193
                                         : 'txn-admin-payment-status-PDC';
194 194
                                     ?>
195 195
                                     <span class="<?php echo esc_attr($payment_class); ?>">
@@ -272,10 +272,10 @@  discard block
 block discarded – undo
272 272
                               . __('This transaction has been overpaid ! ', 'event_espresso')
273 273
                               . '</span>'
274 274
                             : '';
275
-                        echo $overpaid . esc_html(
275
+                        echo $overpaid.esc_html(
276 276
                             sprintf(
277 277
                                 __('Payments Total %s', 'event_espresso'),
278
-                                '(' . EE_Registry::instance()->CFG->currency->code . ')'
278
+                                '('.EE_Registry::instance()->CFG->currency->code.')'
279 279
                             )
280 280
                         ); ?>
281 281
                         </span>
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
             <h2 id="admin-modal-dialog-apply-payment-h2" class="admin-modal-dialog-h2 hdr-has-icon"
405 405
                 style="display:none;"
406 406
             >
407
-                <?php echo esc_html__('Apply a Payment to Transaction #', 'event_espresso') . esc_html($txn_nmbr['value']); ?>
407
+                <?php echo esc_html__('Apply a Payment to Transaction #', 'event_espresso').esc_html($txn_nmbr['value']); ?>
408 408
                 <span class='dashicons dashicons-money-alt'></span>
409 409
             </h2>
410 410
 
@@ -921,7 +921,7 @@  discard block
 block discarded – undo
921 921
 
922 922
     <?php if (WP_DEBUG) {
923 923
         $delivered_messages = get_option('EED_Messages__payment', []);
924
-        if (isset($delivered_messages[ $TXN_ID ])) { ?>
924
+        if (isset($delivered_messages[$TXN_ID])) { ?>
925 925
             <h4 class="admin-primary-mbox-h4 hdr-has-icon">
926 926
                 <?php esc_html_e('Messages Sent to Primary Registrant', 'event_espresso'); ?>
927 927
                 <span class="dashicons dashicons-email-alt"></span>
@@ -941,13 +941,13 @@  discard block
 block discarded – undo
941 941
                     </thead>
942 942
                     <tbody>
943 943
                         <?php
944
-                        foreach ($delivered_messages[ $TXN_ID ] as $timestamp => $delivered_message) :
944
+                        foreach ($delivered_messages[$TXN_ID] as $timestamp => $delivered_message) :
945 945
                             ?>
946 946
                             <tr>
947 947
                                 <td class="jst-left">
948 948
                                     <?php echo esc_html(
949 949
                                         date(
950
-                                            get_option('date_format') . ' ' . get_option('time_format'),
950
+                                            get_option('date_format').' '.get_option('time_format'),
951 951
                                             ($timestamp + (get_option('gmt_offset') * HOUR_IN_SECONDS))
952 952
                                         )
953 953
                                     ); ?>
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 1 patch
Indentation   +2516 added lines, -2516 removed lines patch added patch discarded remove patch
@@ -13,2520 +13,2520 @@
 block discarded – undo
13 13
  */
14 14
 class Transactions_Admin_Page extends EE_Admin_Page
15 15
 {
16
-    /**
17
-     * @var EE_Transaction
18
-     */
19
-    private $_transaction;
20
-
21
-    /**
22
-     * @var EE_Session
23
-     */
24
-    private $_session;
25
-
26
-    /**
27
-     * @var array $_txn_status
28
-     */
29
-    private static $_txn_status;
30
-
31
-    /**
32
-     * @var array $_pay_status
33
-     */
34
-    private static $_pay_status;
35
-
36
-    /**
37
-     * @var array $_existing_reg_payment_REG_IDs
38
-     */
39
-    protected $_existing_reg_payment_REG_IDs;
40
-
41
-
42
-    /**
43
-     *    _init_page_props
44
-     *
45
-     * @return void
46
-     */
47
-    protected function _init_page_props()
48
-    {
49
-        $this->page_slug        = TXN_PG_SLUG;
50
-        $this->page_label       = esc_html__('Transactions', 'event_espresso');
51
-        $this->_admin_base_url  = TXN_ADMIN_URL;
52
-        $this->_admin_base_path = TXN_ADMIN;
53
-    }
54
-
55
-
56
-    /**
57
-     *    _ajax_hooks
58
-     *
59
-     * @return void
60
-     */
61
-    protected function _ajax_hooks()
62
-    {
63
-        // add_action('wp_ajax_espresso_apply_payment', [$this, 'apply_payments_or_refunds']);
64
-        // add_action('wp_ajax_espresso_apply_refund', [$this, 'apply_payments_or_refunds']);
65
-        // add_action('wp_ajax_espresso_delete_payment', [$this, 'delete_payment']);
66
-    }
67
-
68
-
69
-    /**
70
-     *    _define_page_props
71
-     *
72
-     * @return void
73
-     */
74
-    protected function _define_page_props()
75
-    {
76
-        $this->_admin_page_title = $this->page_label;
77
-        $this->_labels           = [
78
-            'buttons' => [
79
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
80
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
81
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
82
-            ],
83
-        ];
84
-    }
85
-
86
-
87
-    /**
88
-     *        grab url requests and route them
89
-     *
90
-     * @access private
91
-     * @return void
92
-     * @throws EE_Error
93
-     * @throws InvalidArgumentException
94
-     * @throws InvalidDataTypeException
95
-     * @throws InvalidInterfaceException
96
-     */
97
-    public function _set_page_routes()
98
-    {
99
-
100
-        $this->_set_transaction_status_array();
101
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
102
-
103
-        $this->_page_routes = [
104
-
105
-            'default' => [
106
-                'func'       => '_transactions_overview_list_table',
107
-                'capability' => 'ee_read_transactions',
108
-            ],
109
-
110
-            'view_transaction' => [
111
-                'func'       => '_transaction_details',
112
-                'capability' => 'ee_read_transaction',
113
-                'obj_id'     => $TXN_ID,
114
-            ],
115
-
116
-            'send_payment_reminder' => [
117
-                'func'       => '_send_payment_reminder',
118
-                'noheader'   => true,
119
-                'capability' => 'ee_send_message',
120
-            ],
121
-
122
-            'espresso_apply_payment' => [
123
-                'func'       => 'apply_payments_or_refunds',
124
-                'noheader'   => true,
125
-                'capability' => 'ee_edit_payments',
126
-            ],
127
-
128
-            'espresso_apply_refund' => [
129
-                'func'       => 'apply_payments_or_refunds',
130
-                'noheader'   => true,
131
-                'capability' => 'ee_edit_payments',
132
-            ],
133
-
134
-            'espresso_delete_payment' => [
135
-                'func'       => [$this, 'delete_payment'],
136
-                'noheader'   => true,
137
-                'capability' => 'ee_delete_payments',
138
-            ],
139
-
140
-            'espresso_recalculate_line_items' => [
141
-                'func'       => 'recalculateLineItems',
142
-                'noheader'   => true,
143
-                'capability' => 'ee_edit_payments',
144
-            ],
145
-
146
-        ];
147
-    }
148
-
149
-
150
-    protected function _set_page_config()
151
-    {
152
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
153
-        $this->_page_config = [
154
-            'default'          => [
155
-                'nav'           => [
156
-                    'label' => esc_html__('Overview', 'event_espresso'),
157
-                    'order' => 10,
158
-                ],
159
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
160
-                'help_tabs'     => [
161
-                    'transactions_overview_help_tab'                       => [
162
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
163
-                        'filename' => 'transactions_overview',
164
-                    ],
165
-                    'transactions_overview_table_column_headings_help_tab' => [
166
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
167
-                        'filename' => 'transactions_overview_table_column_headings',
168
-                    ],
169
-                    'transactions_overview_views_filters_help_tab'         => [
170
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
171
-                        'filename' => 'transactions_overview_views_filters_search',
172
-                    ],
173
-                ],
174
-                'require_nonce' => false,
175
-            ],
176
-            'view_transaction' => [
177
-                'nav'       => [
178
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
179
-                    'order'      => 5,
180
-                    'url'        => $TXN_ID
181
-                        ? add_query_arg(['TXN_ID' => $TXN_ID], $this->_current_page_view_url)
182
-                        : $this->_admin_base_url,
183
-                    'persistent' => false,
184
-                ],
185
-                'help_tabs' => [
186
-                    'transactions_view_transaction_help_tab'                                              => [
187
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
188
-                        'filename' => 'transactions_view_transaction',
189
-                    ],
190
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => [
191
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
192
-                        'filename' => 'transactions_view_transaction_transaction_details_table',
193
-                    ],
194
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => [
195
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
196
-                        'filename' => 'transactions_view_transaction_attendees_registered',
197
-                    ],
198
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => [
199
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
200
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
201
-                    ],
202
-                ],
203
-                'qtips'     => ['Transaction_Details_Tips'],
204
-                'metaboxes' => ['_transaction_details_metaboxes'],
205
-
206
-                'require_nonce' => false,
207
-            ],
208
-        ];
209
-    }
210
-
211
-
212
-    /**
213
-     * The below methods aren't used by this class currently
214
-     */
215
-    protected function _add_screen_options()
216
-    {
217
-        // noop
218
-    }
219
-
220
-
221
-    protected function _add_feature_pointers()
222
-    {
223
-        // noop
224
-    }
225
-
226
-
227
-    public function admin_init()
228
-    {
229
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
230
-        $event_name = $this->request->getRequestParam('event_name');
231
-        $redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
232
-        // IF a registration was JUST added via the admin...
233
-        if ($EVT_ID && $event_name && $redirect_from) {
234
-            // then set a cookie so that we can block any attempts to use
235
-            // the back button as a way to enter another registration.
236
-            setcookie('ee_registration_added', $EVT_ID, time() + WEEK_IN_SECONDS, '/');
237
-            // and update the global
238
-            $_COOKIE['ee_registration_added'] = $EVT_ID;
239
-        }
240
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
241
-            'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
242
-            'event_espresso'
243
-        );
244
-        EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__(
245
-            'An error occurred! Please refresh the page and try again.',
246
-            'event_espresso'
247
-        );
248
-        EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
249
-        EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
250
-        EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
251
-        EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__(
252
-            'This transaction has been overpaid ! Payments Total',
253
-            'event_espresso'
254
-        );
255
-    }
256
-
257
-
258
-    public function admin_notices()
259
-    {
260
-        // noop
261
-    }
262
-
263
-
264
-    public function admin_footer_scripts()
265
-    {
266
-        // noop
267
-    }
268
-
269
-
270
-    /**
271
-     * _set_transaction_status_array
272
-     * sets list of transaction statuses
273
-     *
274
-     * @access private
275
-     * @return void
276
-     * @throws EE_Error
277
-     * @throws InvalidArgumentException
278
-     * @throws InvalidDataTypeException
279
-     * @throws InvalidInterfaceException
280
-     */
281
-    private function _set_transaction_status_array()
282
-    {
283
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
284
-    }
285
-
286
-
287
-    /**
288
-     * get_transaction_status_array
289
-     * return the transaction status array for wp_list_table
290
-     *
291
-     * @access public
292
-     * @return array
293
-     */
294
-    public function get_transaction_status_array()
295
-    {
296
-        return self::$_txn_status;
297
-    }
298
-
299
-
300
-    /**
301
-     *    get list of payment statuses
302
-     *
303
-     * @access private
304
-     * @return void
305
-     * @throws EE_Error
306
-     * @throws InvalidArgumentException
307
-     * @throws InvalidDataTypeException
308
-     * @throws InvalidInterfaceException
309
-     */
310
-    private function _get_payment_status_array()
311
-    {
312
-        self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
313
-        $this->_template_args['payment_status'] = self::$_pay_status;
314
-    }
315
-
316
-
317
-    /**
318
-     *    _add_screen_options_default
319
-     *
320
-     * @access protected
321
-     * @return void
322
-     * @throws InvalidArgumentException
323
-     * @throws InvalidDataTypeException
324
-     * @throws InvalidInterfaceException
325
-     */
326
-    protected function _add_screen_options_default()
327
-    {
328
-        $this->_per_page_screen_option();
329
-    }
330
-
331
-
332
-    /**
333
-     * load_scripts_styles
334
-     *
335
-     * @access public
336
-     * @return void
337
-     */
338
-    public function load_scripts_styles()
339
-    {
340
-        // enqueue style
341
-        wp_register_style(
342
-            'espresso_txn',
343
-            TXN_ASSETS_URL . 'espresso_transactions_admin.css',
344
-            [],
345
-            EVENT_ESPRESSO_VERSION
346
-        );
347
-        wp_enqueue_style('espresso_txn');
348
-        // scripts
349
-        wp_register_script(
350
-            'espresso_txn',
351
-            TXN_ASSETS_URL . 'espresso_transactions_admin.js',
352
-            [
353
-                'ee_admin_js',
354
-                'ee-datepicker',
355
-                'jquery-ui-datepicker',
356
-                'jquery-ui-draggable',
357
-                'ee-dialog',
358
-                'ee-accounting',
359
-                'ee-serialize-full-array',
360
-            ],
361
-            EVENT_ESPRESSO_VERSION,
362
-            true
363
-        );
364
-        wp_enqueue_script('espresso_txn');
365
-    }
366
-
367
-
368
-    /**
369
-     *    load_scripts_styles_view_transaction
370
-     *
371
-     * @access public
372
-     * @return void
373
-     */
374
-    public function load_scripts_styles_view_transaction()
375
-    {
376
-        // styles
377
-        wp_enqueue_style('espresso-ui-theme');
378
-    }
379
-
380
-
381
-    /**
382
-     *    load_scripts_styles_default
383
-     *
384
-     * @access public
385
-     * @return void
386
-     */
387
-    public function load_scripts_styles_default()
388
-    {
389
-        // styles
390
-        wp_enqueue_style('espresso-ui-theme');
391
-    }
392
-
393
-
394
-    /**
395
-     *    _set_list_table_views_default
396
-     *
397
-     * @access protected
398
-     * @return void
399
-     */
400
-    protected function _set_list_table_views_default()
401
-    {
402
-        $this->_views = [
403
-            'all'        => [
404
-                'slug'  => 'all',
405
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
406
-                'count' => 0,
407
-            ],
408
-            'abandoned'  => [
409
-                'slug'  => 'abandoned',
410
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
411
-                'count' => 0,
412
-            ],
413
-            'incomplete' => [
414
-                'slug'  => 'incomplete',
415
-                'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
416
-                'count' => 0,
417
-            ],
418
-        ];
419
-        if (
420
-            /**
421
-             * Filters whether a link to the "Failed Transactions" list table
422
-             * appears on the Transactions Admin Page list table.
423
-             * List display can be turned back on via the following:
424
-             * add_filter(
425
-             *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
426
-             *     '__return_true'
427
-             * );
428
-             *
429
-             * @param boolean                 $display_failed_txns_list
430
-             * @param Transactions_Admin_Page $this
431
-             * @since 4.9.70.p
432
-             */
433
-            apply_filters(
434
-                'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
435
-                false,
436
-                $this
437
-            )
438
-        ) {
439
-            $this->_views['failed'] = [
440
-                'slug'  => 'failed',
441
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
442
-                'count' => 0,
443
-            ];
444
-        }
445
-    }
446
-
447
-
448
-    /**
449
-     * _set_transaction_object
450
-     * This sets the _transaction property for the transaction details screen
451
-     *
452
-     * @access private
453
-     * @return void
454
-     * @throws EE_Error
455
-     * @throws InvalidArgumentException
456
-     * @throws RuntimeException
457
-     * @throws InvalidDataTypeException
458
-     * @throws InvalidInterfaceException
459
-     * @throws ReflectionException
460
-     */
461
-    private function _set_transaction_object()
462
-    {
463
-        if ($this->_transaction instanceof EE_Transaction) {
464
-            return;
465
-        } //get out we've already set the object
466
-
467
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
468
-
469
-        // get transaction object
470
-        $this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
471
-        $this->_session     = $this->_transaction instanceof EE_Transaction
472
-            ? $this->_transaction->session_data()
473
-            : null;
474
-        if ($this->_transaction instanceof EE_Transaction) {
475
-            $this->_transaction->verify_abandoned_transaction_status();
476
-        }
477
-
478
-        if (! $this->_transaction instanceof EE_Transaction) {
479
-            $error_msg = sprintf(
480
-                esc_html__(
481
-                    'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
482
-                    'event_espresso'
483
-                ),
484
-                $TXN_ID
485
-            );
486
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
487
-        }
488
-    }
489
-
490
-
491
-    /**
492
-     *    _transaction_legend_items
493
-     *
494
-     * @access protected
495
-     * @return array
496
-     * @throws EE_Error
497
-     * @throws InvalidArgumentException
498
-     * @throws ReflectionException
499
-     * @throws InvalidDataTypeException
500
-     * @throws InvalidInterfaceException
501
-     */
502
-    protected function _transaction_legend_items()
503
-    {
504
-        EE_Registry::instance()->load_helper('MSG_Template');
505
-        $items = [];
506
-
507
-        if (
508
-            EE_Registry::instance()->CAP->current_user_can(
509
-                'ee_read_global_messages',
510
-                'view_filtered_messages'
511
-            )
512
-        ) {
513
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
514
-            if (
515
-                is_array($related_for_icon)
516
-                && isset($related_for_icon['css_class'], $related_for_icon['label'])
517
-            ) {
518
-                $items['view_related_messages'] = [
519
-                    'class' => $related_for_icon['css_class'],
520
-                    'desc'  => $related_for_icon['label'],
521
-                ];
522
-            }
523
-        }
524
-
525
-        $items = apply_filters(
526
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
527
-            array_merge(
528
-                $items,
529
-                [
530
-                    'view_details'          => [
531
-                        'class' => 'dashicons dashicons-cart',
532
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
533
-                    ],
534
-                    'view_invoice'          => [
535
-                        'class' => 'dashicons dashicons-media-spreadsheet',
536
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
537
-                    ],
538
-                    'view_receipt'          => [
539
-                        'class' => 'dashicons dashicons-text-page',
540
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
541
-                    ],
542
-                    'view_registration'     => [
543
-                        'class' => 'dashicons dashicons-clipboard',
544
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso'),
545
-                    ],
546
-                    'payment_overview_link' => [
547
-                        'class' => 'dashicons dashicons-money',
548
-                        'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
549
-                    ],
550
-                ]
551
-            )
552
-        );
553
-
554
-        if (
555
-            EEH_MSG_Template::is_mt_active('payment_reminder')
556
-            && EE_Registry::instance()->CAP->current_user_can(
557
-                'ee_send_message',
558
-                'espresso_transactions_send_payment_reminder'
559
-            )
560
-        ) {
561
-            $items['send_payment_reminder'] = [
562
-                'class' => 'dashicons dashicons-email-alt',
563
-                'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
564
-            ];
565
-        } else {
566
-            $items['blank*'] = [
567
-                'class' => '',
568
-                'desc'  => '',
569
-            ];
570
-        }
571
-        $more_items = apply_filters(
572
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
573
-            [
574
-                'overpaid'   => [
575
-                    'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::overpaid_status_code,
576
-                    'desc'  => EEH_Template::pretty_status(
577
-                        EEM_Transaction::overpaid_status_code,
578
-                        false,
579
-                        'sentence'
580
-                    ),
581
-                ],
582
-                'complete'   => [
583
-                    'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::complete_status_code,
584
-                    'desc'  => EEH_Template::pretty_status(
585
-                        EEM_Transaction::complete_status_code,
586
-                        false,
587
-                        'sentence'
588
-                    ),
589
-                ],
590
-                'incomplete' => [
591
-                    'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::incomplete_status_code,
592
-                    'desc'  => EEH_Template::pretty_status(
593
-                        EEM_Transaction::incomplete_status_code,
594
-                        false,
595
-                        'sentence'
596
-                    ),
597
-                ],
598
-                'abandoned'  => [
599
-                    'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::abandoned_status_code,
600
-                    'desc'  => EEH_Template::pretty_status(
601
-                        EEM_Transaction::abandoned_status_code,
602
-                        false,
603
-                        'sentence'
604
-                    ),
605
-                ],
606
-                'failed'     => [
607
-                    'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::failed_status_code,
608
-                    'desc'  => EEH_Template::pretty_status(
609
-                        EEM_Transaction::failed_status_code,
610
-                        false,
611
-                        'sentence'
612
-                    ),
613
-                ],
614
-            ]
615
-        );
616
-
617
-        return array_merge($items, $more_items);
618
-    }
619
-
620
-
621
-    /**
622
-     *    _transactions_overview_list_table
623
-     *
624
-     * @access protected
625
-     * @return void
626
-     * @throws DomainException
627
-     * @throws EE_Error
628
-     * @throws InvalidArgumentException
629
-     * @throws InvalidDataTypeException
630
-     * @throws InvalidInterfaceException
631
-     * @throws ReflectionException
632
-     */
633
-    protected function _transactions_overview_list_table()
634
-    {
635
-        $this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
636
-
637
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
638
-        $event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
639
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event
640
-            ? sprintf(
641
-                esc_html__('%sViewing Transactions for the Event: %s%s', 'event_espresso'),
642
-                '<h3>',
643
-                '<a href="'
644
-                . EE_Admin_Page::add_query_args_and_nonce(
645
-                    ['action' => 'edit', 'post' => $event->ID()],
646
-                    EVENTS_ADMIN_URL
647
-                )
648
-                . '" title="'
649
-                . esc_attr__('Click to Edit event', 'event_espresso')
650
-                . '">' . $event->name() . '</a>',
651
-                '</h3>'
652
-            )
653
-            : '';
654
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
655
-        $this->display_admin_list_table_page_with_no_sidebar();
656
-    }
657
-
658
-
659
-    /**
660
-     *    _transaction_details
661
-     * generates HTML for the View Transaction Details Admin page
662
-     *
663
-     * @access protected
664
-     * @return void
665
-     * @throws DomainException
666
-     * @throws EE_Error
667
-     * @throws InvalidArgumentException
668
-     * @throws InvalidDataTypeException
669
-     * @throws InvalidInterfaceException
670
-     * @throws RuntimeException
671
-     * @throws ReflectionException
672
-     */
673
-    protected function _transaction_details()
674
-    {
675
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
676
-
677
-        $this->_set_transaction_status_array();
678
-
679
-        $this->_template_args                      = [];
680
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
681
-
682
-        $this->_set_transaction_object();
683
-
684
-        if (! $this->_transaction instanceof EE_Transaction) {
685
-            return;
686
-        }
687
-
688
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
689
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
690
-
691
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
692
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
693
-
694
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
695
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
696
-        $this->_template_args['txn_status']['class'] = $this->_transaction->status_ID();
697
-
698
-        $txn_total  = $this->_transaction->total();
699
-        $total_paid = $this->_transaction->paid();
700
-        $amount_due = $txn_total - $total_paid;
701
-
702
-        $this->_template_args['grand_total'] = $txn_total;
703
-        $this->_template_args['total_paid']  = $total_paid;
704
-
705
-        $this->_template_args['amount_due'] = EEH_Template::format_currency($amount_due, false, false);
706
-
707
-        $this->_template_args['amount_due_class'] = '';
708
-
709
-        if ($txn_total === (float) 0) {
710
-            // free event
711
-            $this->_template_args['amount_due'] = false;
712
-        } elseif ($amount_due < (float) 0) {
713
-            // overpaid
714
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
715
-        } elseif ($amount_due > (float) 0) {
716
-            // monies owing
717
-            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn ee-txn-amount-owing';
718
-        } elseif ($total_paid === (float) 0) {
719
-            // no payments made yet
720
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
721
-        }
722
-
723
-        $payment_method = $this->_transaction->payment_method();
724
-
725
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
726
-            ? $payment_method->admin_name()
727
-            : esc_html__('Unknown', 'event_espresso');
728
-
729
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
730
-        // link back to overview
731
-        $this->_template_args['txn_overview_url'] = $this->request->getServerParam(
732
-            'HTTP_REFERER',
733
-            TXN_ADMIN_URL
734
-        );
735
-
736
-
737
-        // next link
738
-        $next_txn                                 = $this->_transaction->next(
739
-            null,
740
-            [['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
741
-            'TXN_ID'
742
-        );
743
-        $this->_template_args['next_transaction'] = $next_txn
744
-            ? $this->_next_link(
745
-                EE_Admin_Page::add_query_args_and_nonce(
746
-                    ['action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']],
747
-                    TXN_ADMIN_URL
748
-                ),
749
-                'dashicons dashicons-arrow-right ee-icon-size-22'
750
-            )
751
-            : '';
752
-        // previous link
753
-        $previous_txn                                 = $this->_transaction->previous(
754
-            null,
755
-            [['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
756
-            'TXN_ID'
757
-        );
758
-        $this->_template_args['previous_transaction'] = $previous_txn
759
-            ? $this->_previous_link(
760
-                EE_Admin_Page::add_query_args_and_nonce(
761
-                    ['action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']],
762
-                    TXN_ADMIN_URL
763
-                ),
764
-                'dashicons dashicons-arrow-left ee-icon-size-22'
765
-            )
766
-            : '';
767
-
768
-        $EVT_ID        = $this->request->getRequestParam('EVT_ID', 0, 'int');
769
-        $event_name    = $this->request->getRequestParam('event_name');
770
-        $redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
771
-
772
-        // were we just redirected here after adding a new registration ???
773
-        if ($EVT_ID && $event_name && $redirect_from) {
774
-            if (
775
-                EE_Registry::instance()->CAP->current_user_can(
776
-                    'ee_edit_registrations',
777
-                    'espresso_registrations_new_registration',
778
-                    $EVT_ID
779
-                )
780
-            ) {
781
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button--primary" href="';
782
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
783
-                    [
784
-                        'page'     => 'espresso_registrations',
785
-                        'action'   => 'new_registration',
786
-                        'return'   => 'default',
787
-                        'TXN_ID'   => $this->_transaction->ID(),
788
-                        'event_id' => $EVT_ID,
789
-                    ],
790
-                    REG_ADMIN_URL
791
-                );
792
-                $this->_admin_page_title .= '">';
793
-
794
-                $this->_admin_page_title .= sprintf(
795
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
796
-                    htmlentities(urldecode($event_name), ENT_QUOTES, 'UTF-8')
797
-                );
798
-                $this->_admin_page_title .= '</a>';
799
-            }
800
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
801
-        }
802
-        // grab messages at the last second
803
-        $this->_template_args['notices'] = EE_Error::get_notices();
804
-        // path to template
805
-        $template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
806
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template(
807
-            $template_path,
808
-            $this->_template_args,
809
-            true
810
-        );
811
-
812
-        // the details template wrapper
813
-        $this->display_admin_page_with_sidebar();
814
-    }
815
-
816
-
817
-    /**
818
-     *        _transaction_details_metaboxes
819
-     *
820
-     * @access protected
821
-     * @return void
822
-     * @throws EE_Error
823
-     * @throws InvalidArgumentException
824
-     * @throws InvalidDataTypeException
825
-     * @throws InvalidInterfaceException
826
-     * @throws RuntimeException
827
-     * @throws ReflectionException
828
-     */
829
-    protected function _transaction_details_metaboxes()
830
-    {
831
-
832
-        $this->_set_transaction_object();
833
-
834
-        if (! $this->_transaction instanceof EE_Transaction) {
835
-            return;
836
-        }
837
-        $this->addMetaBox(
838
-            'edit-txn-details-mbox',
839
-            '<span>' . esc_html__('Transaction Details', 'event_espresso')
840
-            . '&nbsp;<span class="dashicons dashicons-cart" ></span></span>',
841
-            [$this, 'txn_details_meta_box'],
842
-            $this->_wp_page_slug
843
-        );
844
-        $this->addMetaBox(
845
-            'edit-txn-attendees-mbox',
846
-            '<span>' . esc_html__('Attendees Registered in this Transaction', 'event_espresso')
847
-            . '&nbsp;<span class="dashicons dashicons-groups" ></span></span>',
848
-            [$this, 'txn_attendees_meta_box'],
849
-            $this->_wp_page_slug,
850
-            'normal',
851
-            'high',
852
-            ['TXN_ID' => $this->_transaction->ID()]
853
-        );
854
-        $this->addMetaBox(
855
-            'edit-txn-registrant-mbox',
856
-            esc_html__('Primary Contact', 'event_espresso'),
857
-            [$this, 'txn_registrant_side_meta_box'],
858
-            $this->_wp_page_slug,
859
-            'side'
860
-        );
861
-        $this->addMetaBox(
862
-            'edit-txn-billing-info-mbox',
863
-            esc_html__('Billing Information', 'event_espresso'),
864
-            [$this, 'txn_billing_info_side_meta_box'],
865
-            $this->_wp_page_slug,
866
-            'side'
867
-        );
868
-    }
869
-
870
-
871
-    /**
872
-     * Callback for transaction actions metabox.
873
-     *
874
-     * @param EE_Transaction|null $transaction
875
-     * @return string
876
-     * @throws DomainException
877
-     * @throws EE_Error
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidDataTypeException
880
-     * @throws InvalidInterfaceException
881
-     * @throws ReflectionException
882
-     * @throws RuntimeException
883
-     */
884
-    public function getActionButtons(EE_Transaction $transaction = null)
885
-    {
886
-        $content = '';
887
-        $actions = [];
888
-        if (! $transaction instanceof EE_Transaction) {
889
-            return $content;
890
-        }
891
-        /** @var EE_Registration $primary_registration */
892
-        $primary_registration = $transaction->primary_registration();
893
-        $attendee             = $primary_registration instanceof EE_Registration
894
-            ? $primary_registration->attendee()
895
-            : null;
896
-
897
-        if (
898
-            $attendee instanceof EE_Attendee
899
-            && EE_Registry::instance()->CAP->current_user_can(
900
-                'ee_send_message',
901
-                'espresso_transactions_send_payment_reminder'
902
-            )
903
-        ) {
904
-            $actions['payment_reminder'] =
905
-                EEH_MSG_Template::is_mt_active('payment_reminder')
906
-                && $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
907
-                && $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
908
-                    ? EEH_Template::get_button_or_link(
909
-                        EE_Admin_Page::add_query_args_and_nonce(
910
-                            [
911
-                            'action'      => 'send_payment_reminder',
912
-                            'TXN_ID'      => $this->_transaction->ID(),
913
-                            'redirect_to' => 'view_transaction',
914
-                            ],
915
-                            TXN_ADMIN_URL
916
-                        ),
917
-                        esc_html__(' Send Payment Reminder', 'event_espresso'),
918
-                        'button button--secondary',
919
-                        'dashicons dashicons-email-alt'
920
-                    )
921
-                    : '';
922
-        }
923
-
924
-        if (
925
-            EE_Registry::instance()->CAP->current_user_can(
926
-                'ee_edit_payments',
927
-                'espresso_transactions_recalculate_line_items'
928
-            )
929
-        ) {
930
-            $actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
931
-                EE_Admin_Page::add_query_args_and_nonce(
932
-                    [
933
-                        'action'      => 'espresso_recalculate_line_items',
934
-                        'TXN_ID'      => $this->_transaction->ID(),
935
-                        'redirect_to' => 'view_transaction',
936
-                    ],
937
-                    TXN_ADMIN_URL
938
-                ),
939
-                esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
940
-                'button button--secondary',
941
-                'dashicons dashicons-update'
942
-            );
943
-        }
944
-
945
-        if (
946
-            $primary_registration instanceof EE_Registration
947
-            && EEH_MSG_Template::is_mt_active('receipt')
948
-        ) {
949
-            $actions['receipt'] = EEH_Template::get_button_or_link(
950
-                $primary_registration->receipt_url(),
951
-                esc_html__('View Receipt', 'event_espresso'),
952
-                'button button--secondary',
953
-                'dashicons dashicons-text-page'
954
-            );
955
-        }
956
-
957
-        if (
958
-            $primary_registration instanceof EE_Registration
959
-            && EEH_MSG_Template::is_mt_active('invoice')
960
-        ) {
961
-            $actions['invoice'] = EEH_Template::get_button_or_link(
962
-                $primary_registration->invoice_url(),
963
-                esc_html__('View Invoice', 'event_espresso'),
964
-                'button button--secondary',
965
-                'dashicons dashicons-media-spreadsheet'
966
-            );
967
-        }
968
-        $actions = array_filter(
969
-            apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
970
-        );
971
-        if ($actions) {
972
-            $content .= implode('', $actions);
973
-        }
974
-        return $content;
975
-    }
976
-
977
-
978
-    /**
979
-     * txn_details_meta_box
980
-     * generates HTML for the Transaction main meta box
981
-     *
982
-     * @return void
983
-     * @throws DomainException
984
-     * @throws EE_Error
985
-     * @throws InvalidArgumentException
986
-     * @throws InvalidDataTypeException
987
-     * @throws InvalidInterfaceException
988
-     * @throws RuntimeException
989
-     * @throws ReflectionException
990
-     */
991
-    public function txn_details_meta_box()
992
-    {
993
-        $this->_set_transaction_object();
994
-        $this->_template_args['TXN_ID']              = $this->_transaction->ID();
995
-        $this->_template_args['attendee']            =
996
-            $this->_transaction->primary_registration() instanceof EE_Registration
997
-                ? $this->_transaction->primary_registration()->attendee()
998
-                : null;
999
-        $this->_template_args['can_edit_payments']   = EE_Registry::instance()->CAP->current_user_can(
1000
-            'ee_edit_payments',
1001
-            'apply_payment_or_refund_from_registration_details'
1002
-        );
1003
-        $this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1004
-            'ee_delete_payments',
1005
-            'delete_payment_from_registration_details'
1006
-        );
1007
-
1008
-        // get line table
1009
-        EEH_Autoloader::register_line_item_display_autoloaders();
1010
-        $Line_Item_Display                       = new EE_Line_Item_Display(
1011
-            'admin_table',
1012
-            'EE_Admin_Table_Line_Item_Display_Strategy'
1013
-        );
1014
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1015
-            $this->_transaction->total_line_item()
1016
-        );
1017
-        $this->_template_args['REG_code']        =
1018
-            $this->_transaction->primary_registration() instanceof EE_Registration
1019
-                ? $this->_transaction->primary_registration()->reg_code()
1020
-                : null;
1021
-        // process taxes
1022
-        $taxes                         = $this->_transaction->line_items([['LIN_type' => EEM_Line_Item::type_tax]]);
1023
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1024
-
1025
-        $this->_template_args['grand_total']     = EEH_Template::format_currency(
1026
-            $this->_transaction->total(),
1027
-            false,
1028
-            false
1029
-        );
1030
-        $this->_template_args['grand_raw_total'] = $this->_transaction->total();
1031
-        $this->_template_args['TXN_status']      = $this->_transaction->status_ID();
1032
-
1033
-        // process payment details
1034
-        $payments = $this->_transaction->payments();
1035
-        if (! empty($payments)) {
1036
-            $this->_template_args['payments']              = $payments;
1037
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1038
-        } else {
1039
-            $this->_template_args['payments']              = false;
1040
-            $this->_template_args['existing_reg_payments'] = [];
1041
-        }
1042
-
1043
-        $this->_template_args['edit_payment_url']   = add_query_arg(['action' => 'edit_payment'], TXN_ADMIN_URL);
1044
-        $this->_template_args['delete_payment_url'] = add_query_arg(
1045
-            ['action' => 'espresso_delete_payment'],
1046
-            TXN_ADMIN_URL
1047
-        );
1048
-
1049
-        if (isset($txn_details['invoice_number'])) {
1050
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1051
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1052
-                'Invoice Number',
1053
-                'event_espresso'
1054
-            );
1055
-        }
1056
-
1057
-        $this->_template_args['txn_details']['registration_session']['value'] =
1058
-            $this->_transaction->primary_registration() instanceof EE_Registration
1059
-                ? $this->_transaction->primary_registration()->session_ID()
1060
-                : null;
1061
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1062
-            'Registration Session',
1063
-            'event_espresso'
1064
-        );
1065
-
1066
-        $this->_template_args['txn_details']['ip_address']['value'] = $this->_session['ip_address'] ?? '';
1067
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1068
-            'Transaction placed from IP',
1069
-            'event_espresso'
1070
-        );
1071
-
1072
-        $this->_template_args['txn_details']['user_agent']['value'] = $this->_session['user_agent'] ?? '';
1073
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1074
-            'Registrant User Agent',
1075
-            'event_espresso'
1076
-        );
1077
-
1078
-        $reg_steps = '<div class="ee-txn-reg-step-status-steps ee-layout-row">';
1079
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1080
-            if ($reg_step_status === true) {
1081
-                $reg_steps .= '<div class="ee-status-pill ee-status-bg--success">'
1082
-                              . sprintf(
1083
-                                  esc_html__('%1$s : Completed', 'event_espresso'),
1084
-                                  ucwords(str_replace('_', ' ', $reg_step))
1085
-                              )
1086
-                              . '</div>';
1087
-            } elseif ($reg_step_status !== false && is_numeric($reg_step_status)) {
1088
-                $reg_steps .= '<div class="ee-status-pill ee-status-bg--attention">'
1089
-                              . sprintf(
1090
-                                  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1091
-                                  ucwords(str_replace('_', ' ', $reg_step)),
1092
-                                  date(
1093
-                                      get_option('date_format') . ' ' . get_option('time_format'),
1094
-                                      $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1095
-                                  )
1096
-                              )
1097
-                              . '</div>';
1098
-            } else {
1099
-                $reg_steps .= '<div class="ee-status-pill ee-status-bg--error">'
1100
-                              . sprintf(
1101
-                                  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1102
-                                  ucwords(str_replace('_', ' ', $reg_step))
1103
-                              )
1104
-                              . '</div>';
1105
-            }
1106
-        }
1107
-        $reg_steps                                                 .= '</ul>';
1108
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1109
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1110
-            'Registration Step Progress',
1111
-            'event_espresso'
1112
-        );
1113
-
1114
-
1115
-        $this->_get_registrations_to_apply_payment_to();
1116
-        $this->_get_payment_methods($payments);
1117
-        $this->_get_payment_status_array();
1118
-        $this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1119
-
1120
-        $this->_template_args['transaction_form_url']    = add_query_arg(
1121
-            [
1122
-                'action'  => 'edit_transaction',
1123
-                'process' => 'transaction',
1124
-            ],
1125
-            TXN_ADMIN_URL
1126
-        );
1127
-        $this->_template_args['apply_payment_form_url']  = add_query_arg(
1128
-            [
1129
-                'page'   => 'espresso_transactions',
1130
-                'action' => 'espresso_apply_payment',
1131
-            ],
1132
-            TXN_ADMIN_URL
1133
-        );
1134
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(
1135
-            [
1136
-                'page'   => 'espresso_transactions',
1137
-                'action' => 'espresso_delete_payment',
1138
-            ],
1139
-            TXN_ADMIN_URL
1140
-        );
1141
-
1142
-        $this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1143
-
1144
-        // 'espresso_delete_payment_nonce'
1145
-
1146
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1147
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1148
-    }
1149
-
1150
-
1151
-    /**
1152
-     * _get_registration_payment_IDs
1153
-     *    generates an array of Payment IDs and their corresponding Registration IDs
1154
-     *
1155
-     * @access protected
1156
-     * @param EE_Payment[] $payments
1157
-     * @return array
1158
-     * @throws EE_Error
1159
-     * @throws InvalidArgumentException
1160
-     * @throws InvalidDataTypeException
1161
-     * @throws InvalidInterfaceException
1162
-     * @throws ReflectionException
1163
-     */
1164
-    protected function _get_registration_payment_IDs($payments = [])
1165
-    {
1166
-        $existing_reg_payments = [];
1167
-        // get all reg payments for these payments
1168
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(
1169
-            [
1170
-                [
1171
-                    'PAY_ID' => [
1172
-                        'IN',
1173
-                        array_keys($payments),
1174
-                    ],
1175
-                ],
1176
-            ]
1177
-        );
1178
-        if (! empty($reg_payments)) {
1179
-            foreach ($payments as $payment) {
1180
-                if (! $payment instanceof EE_Payment) {
1181
-                    continue;
1182
-                } elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1183
-                    $existing_reg_payments[ $payment->ID() ] = [];
1184
-                }
1185
-                foreach ($reg_payments as $reg_payment) {
1186
-                    if (
1187
-                        $reg_payment instanceof EE_Registration_Payment
1188
-                        && $reg_payment->payment_ID() === $payment->ID()
1189
-                    ) {
1190
-                        $existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1191
-                    }
1192
-                }
1193
-            }
1194
-        }
1195
-
1196
-        return $existing_reg_payments;
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * _get_registrations_to_apply_payment_to
1202
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1203
-     * which allows the admin to only apply the payment to the specific registrations
1204
-     *
1205
-     * @access protected
1206
-     * @return void
1207
-     * @throws EE_Error
1208
-     * @throws InvalidArgumentException
1209
-     * @throws InvalidDataTypeException
1210
-     * @throws InvalidInterfaceException
1211
-     * @throws ReflectionException
1212
-     */
1213
-    protected function _get_registrations_to_apply_payment_to()
1214
-    {
1215
-        // we want any registration with an active status (ie: not deleted or cancelled)
1216
-        $query_params                      = [
1217
-            [
1218
-                'STS_ID' => [
1219
-                    'IN',
1220
-                    [
1221
-                        EEM_Registration::status_id_approved,
1222
-                        EEM_Registration::status_id_pending_payment,
1223
-                        EEM_Registration::status_id_not_approved,
1224
-                    ],
1225
-                ],
1226
-            ],
1227
-        ];
1228
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1229
-            '',
1230
-            'txn-admin-apply-payment-to-registrations-dv',
1231
-            '',
1232
-            'clear: both; margin: 1.5em 0 0; display: none;'
1233
-        );
1234
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1235
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl striped');
1236
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
1237
-            EEH_HTML::tr(
1238
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1239
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1240
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1241
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1242
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1243
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1244
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1245
-            )
1246
-        );
1247
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
1248
-        // get registrations for TXN
1249
-        $registrations         = $this->_transaction->registrations($query_params);
1250
-        $existing_reg_payments = $this->_template_args['existing_reg_payments'];
1251
-        foreach ($registrations as $registration) {
1252
-            if ($registration instanceof EE_Registration) {
1253
-                $attendee_name                     = $registration->attendee() instanceof EE_Attendee
1254
-                    ? $registration->attendee()->full_name()
1255
-                    : esc_html__('Unknown Attendee', 'event_espresso');
1256
-                $owing                             = $registration->final_price() - $registration->paid();
1257
-                $taxable                           = $registration->ticket()->taxable()
1258
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1259
-                    : '';
1260
-                $checked                           = empty($existing_reg_payments)
1261
-                                                     || in_array($registration->ID(), $existing_reg_payments, true)
1262
-                    ? ' checked'
1263
-                    : '';
1264
-                $disabled                          = $registration->final_price() > 0 ? '' : ' disabled';
1265
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
1266
-                    EEH_HTML::td($registration->ID()) .
1267
-                    EEH_HTML::td($attendee_name) .
1268
-                    EEH_HTML::td(
1269
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1270
-                    ) .
1271
-                    EEH_HTML::td($registration->event_name()) .
1272
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1273
-                    EEH_HTML::td(
1274
-                        EEH_Template::format_currency($owing),
1275
-                        '',
1276
-                        'txn-admin-payment-owing-td jst-cntr'
1277
-                    ) .
1278
-                    EEH_HTML::td(
1279
-                        '<input type="checkbox" value="' . $registration->ID()
1280
-                        . '" name="txn_admin_payment[registrations]"'
1281
-                        . $checked . $disabled . '>',
1282
-                        '',
1283
-                        'jst-cntr'
1284
-                    ),
1285
-                    'apply-payment-registration-row-' . $registration->ID()
1286
-                );
1287
-            }
1288
-        }
1289
-        $registrations_to_apply_payment_to                         .= EEH_HTML::tbodyx();
1290
-        $registrations_to_apply_payment_to                         .= EEH_HTML::tablex();
1291
-        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1292
-        $registrations_to_apply_payment_to                         .= EEH_HTML::p(
1293
-            esc_html__(
1294
-                'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1295
-                'event_espresso'
1296
-            ),
1297
-            '',
1298
-            'clear description'
1299
-        );
1300
-        $registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1301
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1302
-    }
1303
-
1304
-
1305
-    /**
1306
-     * _get_reg_status_selection
1307
-     *
1308
-     * @return void
1309
-     * @throws EE_Error
1310
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1311
-     *         instead of events.
1312
-     * @access protected
1313
-     */
1314
-    protected function _get_reg_status_selection()
1315
-    {
1316
-        // first get all possible statuses
1317
-        $statuses = EEM_Registration::reg_status_array([], true);
1318
-        // let's add a "don't change" option.
1319
-        $status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
1320
-        $status_array                                        = array_merge($status_array, $statuses);
1321
-        $this->_template_args['status_change_select']        = EEH_Form_Fields::select_input(
1322
-            'txn_reg_status_change[reg_status]',
1323
-            $status_array,
1324
-            'NAN',
1325
-            'id="txn-admin-payment-reg-status-inp"',
1326
-            'txn-reg-status-change-reg-status'
1327
-        );
1328
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1329
-            'delete_txn_reg_status_change[reg_status]',
1330
-            $status_array,
1331
-            'NAN',
1332
-            'delete-txn-admin-payment-reg-status-inp',
1333
-            'delete-txn-reg-status-change-reg-status'
1334
-        );
1335
-    }
1336
-
1337
-
1338
-    /**
1339
-     *    _get_payment_methods
1340
-     * Gets all the payment methods available generally, or the ones that are already
1341
-     * selected on these payments (in case their payment methods are no longer active).
1342
-     * Has the side-effect of updating the template args' payment_methods item
1343
-     *
1344
-     * @access private
1345
-     * @param EE_Payment[] to show on this page
1346
-     * @return void
1347
-     * @throws EE_Error
1348
-     * @throws InvalidArgumentException
1349
-     * @throws InvalidDataTypeException
1350
-     * @throws InvalidInterfaceException
1351
-     * @throws ReflectionException
1352
-     */
1353
-    private function _get_payment_methods($payments = [])
1354
-    {
1355
-        $payment_methods_of_payments = [];
1356
-        foreach ($payments as $payment) {
1357
-            if ($payment instanceof EE_Payment) {
1358
-                $payment_methods_of_payments[] = $payment->ID();
1359
-            }
1360
-        }
1361
-        if ($payment_methods_of_payments) {
1362
-            $query_args = [
1363
-                [
1364
-                    'OR*payment_method_for_payment' => [
1365
-                        'PMD_ID'    => ['IN', $payment_methods_of_payments],
1366
-                        'PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%'],
1367
-                    ],
1368
-                ],
1369
-            ];
1370
-        } else {
1371
-            $query_args = [['PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%']]];
1372
-        }
1373
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1374
-    }
1375
-
1376
-
1377
-    /**
1378
-     * txn_attendees_meta_box
1379
-     *    generates HTML for the Attendees Transaction main meta box
1380
-     *
1381
-     * @access public
1382
-     * @param WP_Post $post
1383
-     * @param array   $metabox
1384
-     * @return void
1385
-     * @throws DomainException
1386
-     * @throws EE_Error
1387
-     * @throws InvalidArgumentException
1388
-     * @throws InvalidDataTypeException
1389
-     * @throws InvalidInterfaceException
1390
-     * @throws ReflectionException
1391
-     */
1392
-    public function txn_attendees_meta_box($post, $metabox = ['args' => []])
1393
-    {
1394
-
1395
-        /** @noinspection NonSecureExtractUsageInspection */
1396
-        extract($metabox['args']);
1397
-        $this->_template_args['post']            = $post;
1398
-        $this->_template_args['event_attendees'] = [];
1399
-        // process items in cart
1400
-        $line_items = $this->_transaction->get_many_related(
1401
-            'Line_Item',
1402
-            [['LIN_type' => 'line-item']]
1403
-        );
1404
-        if (! empty($line_items)) {
1405
-            foreach ($line_items as $item) {
1406
-                if ($item instanceof EE_Line_Item) {
1407
-                    switch ($item->OBJ_type()) {
1408
-                        case 'Event':
1409
-                            break;
1410
-                        case 'Ticket':
1411
-                            $ticket = $item->ticket();
1412
-                            // right now we're only handling tickets here.
1413
-                            // Cause its expected that only tickets will have attendees right?
1414
-                            if (! $ticket instanceof EE_Ticket) {
1415
-                                break;
1416
-                            }
1417
-                            try {
1418
-                                $event_name = $ticket->get_event_name();
1419
-                            } catch (Exception $e) {
1420
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1421
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1422
-                            }
1423
-                            $event_name   .= ' - ' . $item->name();
1424
-                            $ticket_price = EEH_Template::format_currency($item->unit_price());
1425
-                            // now get all of the registrations for this transaction that use this ticket
1426
-                            $registrations = $ticket->registrations(
1427
-                                [['TXN_ID' => $this->_transaction->ID()]]
1428
-                            );
1429
-                            foreach ($registrations as $registration) {
1430
-                                if (! $registration instanceof EE_Registration) {
1431
-                                    break;
1432
-                                }
1433
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1434
-                                    = $registration->status_ID();
1435
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1436
-                                    = $registration->count();
1437
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1438
-                                    = $event_name;
1439
-                                $this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1440
-                                    = $ticket_price;
1441
-                                // attendee info
1442
-                                $attendee = $registration->get_first_related('Attendee');
1443
-                                if ($attendee instanceof EE_Attendee) {
1444
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1445
-                                        = $attendee->ID();
1446
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1447
-                                        = $attendee->full_name();
1448
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']
1449
-                                        = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1450
-                                          . esc_html__(
1451
-                                              ' Event',
1452
-                                              'event_espresso'
1453
-                                          )
1454
-                                          . '">' . $attendee->email() . '</a>';
1455
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']
1456
-                                        = EEH_Address::format($attendee, 'inline', false, false);
1457
-                                } else {
1458
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['att_id']   = '';
1459
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1460
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['email']    = '';
1461
-                                    $this->_template_args['event_attendees'][ $registration->ID() ]['address']  = '';
1462
-                                }
1463
-                            }
1464
-                            break;
1465
-                    }
1466
-                }
1467
-            }
1468
-
1469
-            $this->_template_args['transaction_form_url'] = add_query_arg(
1470
-                [
1471
-                    'action'  => 'edit_transaction',
1472
-                    'process' => 'attendees',
1473
-                ],
1474
-                TXN_ADMIN_URL
1475
-            );
1476
-            echo EEH_Template::display_template(
1477
-                TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1478
-                $this->_template_args,
1479
-                true
1480
-            );
1481
-        } else {
1482
-            printf(
1483
-                esc_html__(
1484
-                    '%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1485
-                    'event_espresso'
1486
-                ),
1487
-                '<p class="important-notice">',
1488
-                '</p>'
1489
-            );
1490
-        }
1491
-    }
1492
-
1493
-
1494
-    /**
1495
-     * txn_registrant_side_meta_box
1496
-     * generates HTML for the Edit Transaction side meta box
1497
-     *
1498
-     * @access public
1499
-     * @return void
1500
-     * @throws DomainException
1501
-     * @throws EE_Error
1502
-     * @throws InvalidArgumentException
1503
-     * @throws InvalidDataTypeException
1504
-     * @throws InvalidInterfaceException
1505
-     * @throws ReflectionException
1506
-     */
1507
-    public function txn_registrant_side_meta_box()
1508
-    {
1509
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1510
-            ? $this->_transaction->primary_registration()->get_first_related('Attendee')
1511
-            : null;
1512
-        if (! $primary_att instanceof EE_Attendee) {
1513
-            $this->_template_args['no_attendee_message'] = esc_html__(
1514
-                'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1515
-                'event_espresso'
1516
-            );
1517
-            $primary_att                           = EEM_Attendee::instance()->create_default_object();
1518
-        }
1519
-        $this->_template_args['ATT_ID']            = $primary_att->ID();
1520
-        $this->_template_args['prime_reg_fname']   = $primary_att->fname();
1521
-        $this->_template_args['prime_reg_lname']   = $primary_att->lname();
1522
-        $this->_template_args['prime_reg_email']   = $primary_att->email();
1523
-        $this->_template_args['prime_reg_phone']   = $primary_att->phone();
1524
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1525
-            [
1526
-                'action' => 'edit_attendee',
1527
-                'post'   => $primary_att->ID(),
1528
-            ],
1529
-            REG_ADMIN_URL
1530
-        );
1531
-        // get formatted address for registrant
1532
-        $formatted_address = EEH_Address::format($primary_att);
1533
-        $formatted_address = $formatted_address !== '<div class="espresso-address-dv"><div></div></div>'
1534
-            ? $formatted_address
1535
-            : '';
1536
-        $this->_template_args['formatted_address'] = $formatted_address;
1537
-        echo EEH_Template::display_template(
1538
-            TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1539
-            $this->_template_args,
1540
-            true
1541
-        );
1542
-    }
1543
-
1544
-
1545
-    /**
1546
-     * txn_billing_info_side_meta_box
1547
-     *    generates HTML for the Edit Transaction side meta box
1548
-     *
1549
-     * @access public
1550
-     * @return void
1551
-     * @throws DomainException
1552
-     * @throws EE_Error
1553
-     * @throws ReflectionException
1554
-     */
1555
-    public function txn_billing_info_side_meta_box()
1556
-    {
1557
-
1558
-        $this->_template_args['billing_form']     = $this->_transaction->billing_info();
1559
-        $this->_template_args['billing_form_url'] = add_query_arg(
1560
-            ['action' => 'edit_transaction', 'process' => 'billing'],
1561
-            TXN_ADMIN_URL
1562
-        );
1563
-
1564
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1565
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
1566
-    }
1567
-
1568
-
1569
-    /**
1570
-     * apply_payments_or_refunds
1571
-     *    registers a payment or refund made towards a transaction
1572
-     *
1573
-     * @access public
1574
-     * @return void
1575
-     * @throws EE_Error
1576
-     * @throws InvalidArgumentException
1577
-     * @throws ReflectionException
1578
-     * @throws RuntimeException
1579
-     * @throws InvalidDataTypeException
1580
-     * @throws InvalidInterfaceException
1581
-     */
1582
-    public function apply_payments_or_refunds()
1583
-    {
1584
-        $valid_data         = $this->_validate_payment_request_data();
1585
-        $has_access         = EE_Registry::instance()->CAP->current_user_can(
1586
-            'ee_edit_payments',
1587
-            'apply_payment_or_refund_from_registration_details'
1588
-        );
1589
-        $TXD_ID = $this->request->getRequestParam('txn_admin_payment[TXN_ID]', 0, 'int');
1590
-        $amount = 0;
1591
-        if (! empty($valid_data) && $has_access) {
1592
-            $PAY_ID = $valid_data['PAY_ID'];
1593
-            // save  the new payment
1594
-            $payment = $this->_create_payment_from_request_data($valid_data);
1595
-            $amount = $payment->amount();
1596
-            // get the TXN for this payment
1597
-            $transaction = $payment->transaction();
1598
-            // verify transaction
1599
-            if ($transaction instanceof EE_Transaction) {
1600
-                // calculate_total_payments_and_update_status
1601
-                $this->_process_transaction_payments($transaction);
1602
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1603
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1604
-                // apply payment to registrations (if applicable)
1605
-                if (! empty($REG_IDs)) {
1606
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1607
-                    $this->_maybe_send_notifications();
1608
-                    // now process status changes for the same registrations
1609
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1610
-                }
1611
-                $this->_maybe_send_notifications($payment);
1612
-                // prepare to render page
1613
-                do_action(
1614
-                    'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1615
-                    $transaction,
1616
-                    $payment
1617
-                );
1618
-            } else {
1619
-                EE_Error::add_error(
1620
-                    esc_html__(
1621
-                        'A valid Transaction for this payment could not be retrieved.',
1622
-                        'event_espresso'
1623
-                    ),
1624
-                    __FILE__,
1625
-                    __FUNCTION__,
1626
-                    __LINE__
1627
-                );
1628
-            }
1629
-        } elseif ($has_access) {
1630
-            EE_Error::add_error(
1631
-                esc_html__(
1632
-                    'The payment form data could not be processed. Please try again.',
1633
-                    'event_espresso'
1634
-                ),
1635
-                __FILE__,
1636
-                __FUNCTION__,
1637
-                __LINE__
1638
-            );
1639
-        } else {
1640
-            EE_Error::add_error(
1641
-                esc_html__(
1642
-                    'You do not have access to apply payments or refunds to a registration.',
1643
-                    'event_espresso'
1644
-                ),
1645
-                __FILE__,
1646
-                __FUNCTION__,
1647
-                __LINE__
1648
-            );
1649
-        }
1650
-        $query_args = [
1651
-            'page' => 'espresso_transactions',
1652
-             'action' => 'view_transaction',
1653
-             'TXN_ID' => $TXD_ID
1654
-        ];
1655
-
1656
-        $this->_redirect_after_action(
1657
-            ! EE_Error::has_error(),
1658
-            $amount > 0
1659
-                ? esc_html__('payment', 'event_espresso')
1660
-                : esc_html__('refund', 'event_espresso'),
1661
-            esc_html__('processed', 'event_espresso'),
1662
-            $query_args
1663
-        );
1664
-    }
1665
-
1666
-
1667
-    /**
1668
-     * _validate_payment_request_data
1669
-     *
1670
-     * @return array
1671
-     * @throws EE_Error
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidDataTypeException
1674
-     * @throws InvalidInterfaceException
1675
-     */
1676
-    protected function _validate_payment_request_data()
1677
-    {
1678
-        if (! $this->request->requestParamIsSet('txn_admin_payment')) {
1679
-            return [];
1680
-        }
1681
-        $payment_form = $this->_generate_payment_form_section();
1682
-        try {
1683
-            if ($payment_form->was_submitted()) {
1684
-                $payment_form->receive_form_submission();
1685
-                if (! $payment_form->is_valid()) {
1686
-                    $submission_error_messages = [];
1687
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1688
-                        if ($validation_error instanceof EE_Validation_Error) {
1689
-                            $form_input = $validation_error->get_form_section();
1690
-                            $submission_error_messages[] = sprintf(
1691
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1692
-                                $form_input instanceof EE_Form_Input_Base ? $form_input->html_label_text() : '',
1693
-                                $validation_error->getMessage()
1694
-                            );
1695
-                        }
1696
-                    }
1697
-                    EE_Error::add_error(
1698
-                        implode('<br />', $submission_error_messages),
1699
-                        __FILE__,
1700
-                        __FUNCTION__,
1701
-                        __LINE__
1702
-                    );
1703
-                    return [];
1704
-                }
1705
-            }
1706
-        } catch (EE_Error $e) {
1707
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1708
-            return [];
1709
-        }
1710
-
1711
-        return $payment_form->valid_data();
1712
-    }
1713
-
1714
-
1715
-    /**
1716
-     * _generate_payment_form_section
1717
-     *
1718
-     * @return EE_Form_Section_Proper
1719
-     * @throws EE_Error
1720
-     */
1721
-    protected function _generate_payment_form_section()
1722
-    {
1723
-        return new EE_Form_Section_Proper(
1724
-            [
1725
-                'name'        => 'txn_admin_payment',
1726
-                'subsections' => [
1727
-                    'PAY_ID'          => new EE_Text_Input(
1728
-                        [
1729
-                            'default'               => 0,
1730
-                            'required'              => false,
1731
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1732
-                            'validation_strategies' => [new EE_Int_Normalization()],
1733
-                        ]
1734
-                    ),
1735
-                    'TXN_ID'          => new EE_Text_Input(
1736
-                        [
1737
-                            'default'               => 0,
1738
-                            'required'              => true,
1739
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1740
-                            'validation_strategies' => [new EE_Int_Normalization()],
1741
-                        ]
1742
-                    ),
1743
-                    'type'            => new EE_Text_Input(
1744
-                        [
1745
-                            'default'               => 1,
1746
-                            'required'              => true,
1747
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1748
-                            'validation_strategies' => [new EE_Int_Normalization()],
1749
-                        ]
1750
-                    ),
1751
-                    'amount'          => new EE_Text_Input(
1752
-                        [
1753
-                            'default'               => 0,
1754
-                            'required'              => true,
1755
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1756
-                            'validation_strategies' => [new EE_Float_Normalization()],
1757
-                        ]
1758
-                    ),
1759
-                    'status'          => new EE_Text_Input(
1760
-                        [
1761
-                            'default'         => EEM_Payment::status_id_approved,
1762
-                            'required'        => true,
1763
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1764
-                        ]
1765
-                    ),
1766
-                    'PMD_ID'          => new EE_Text_Input(
1767
-                        [
1768
-                            'default'               => 2,
1769
-                            'required'              => true,
1770
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1771
-                            'validation_strategies' => [new EE_Int_Normalization()],
1772
-                        ]
1773
-                    ),
1774
-                    'date'            => new EE_Text_Input(
1775
-                        [
1776
-                            'default'         => time(),
1777
-                            'required'        => true,
1778
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1779
-                        ]
1780
-                    ),
1781
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1782
-                        [
1783
-                            'default'               => '',
1784
-                            'required'              => false,
1785
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1786
-                            'validation_strategies' => [
1787
-                                new EE_Max_Length_Validation_Strategy(
1788
-                                    esc_html__('Input too long', 'event_espresso'),
1789
-                                    100
1790
-                                ),
1791
-                            ],
1792
-                        ]
1793
-                    ),
1794
-                    'po_number'       => new EE_Text_Input(
1795
-                        [
1796
-                            'default'               => '',
1797
-                            'required'              => false,
1798
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1799
-                            'validation_strategies' => [
1800
-                                new EE_Max_Length_Validation_Strategy(
1801
-                                    esc_html__('Input too long', 'event_espresso'),
1802
-                                    100
1803
-                                ),
1804
-                            ],
1805
-                        ]
1806
-                    ),
1807
-                    'accounting'      => new EE_Text_Input(
1808
-                        [
1809
-                            'default'               => '',
1810
-                            'required'              => false,
1811
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1812
-                            'validation_strategies' => [
1813
-                                new EE_Max_Length_Validation_Strategy(
1814
-                                    esc_html__('Input too long', 'event_espresso'),
1815
-                                    100
1816
-                                ),
1817
-                            ],
1818
-                        ]
1819
-                    ),
1820
-                ],
1821
-            ]
1822
-        );
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     * _create_payment_from_request_data
1828
-     *
1829
-     * @param array $valid_data
1830
-     * @return EE_Payment
1831
-     * @throws EE_Error
1832
-     * @throws InvalidArgumentException
1833
-     * @throws InvalidDataTypeException
1834
-     * @throws InvalidInterfaceException
1835
-     * @throws ReflectionException
1836
-     */
1837
-    protected function _create_payment_from_request_data($valid_data)
1838
-    {
1839
-        $PAY_ID = $valid_data['PAY_ID'];
1840
-        // get payment amount
1841
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1842
-        // payments have a type value of 1 and refunds have a type value of -1
1843
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1844
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1845
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1846
-        $date    = $valid_data['date']
1847
-            ? preg_replace('/\s+/', ' ', $valid_data['date'])
1848
-            : date('Y-m-d g:i a', current_time('timestamp'));
1849
-        $payment = EE_Payment::new_instance(
1850
-            [
1851
-                'TXN_ID'              => $valid_data['TXN_ID'],
1852
-                'STS_ID'              => $valid_data['status'],
1853
-                'PAY_timestamp'       => $date,
1854
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1855
-                'PMD_ID'              => $valid_data['PMD_ID'],
1856
-                'PAY_amount'          => $amount,
1857
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1858
-                'PAY_po_number'       => $valid_data['po_number'],
1859
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1860
-                'PAY_details'         => $valid_data,
1861
-                'PAY_ID'              => $PAY_ID,
1862
-            ],
1863
-            '',
1864
-            ['Y-m-d', 'g:i a']
1865
-        );
1866
-
1867
-        if (! $payment->save()) {
1868
-            EE_Error::add_error(
1869
-                sprintf(
1870
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1871
-                    $payment->ID()
1872
-                ),
1873
-                __FILE__,
1874
-                __FUNCTION__,
1875
-                __LINE__
1876
-            );
1877
-        }
1878
-
1879
-        return $payment;
1880
-    }
1881
-
1882
-
1883
-    /**
1884
-     * _process_transaction_payments
1885
-     *
1886
-     * @param EE_Transaction $transaction
1887
-     * @return void
1888
-     * @throws EE_Error
1889
-     * @throws InvalidArgumentException
1890
-     * @throws ReflectionException
1891
-     * @throws InvalidDataTypeException
1892
-     * @throws InvalidInterfaceException
1893
-     */
1894
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1895
-    {
1896
-        /** @type EE_Transaction_Payments $transaction_payments */
1897
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1898
-        // update the transaction with this payment
1899
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1900
-            EE_Error::add_success(
1901
-                esc_html__(
1902
-                    'The payment has been processed successfully.',
1903
-                    'event_espresso'
1904
-                ),
1905
-                __FILE__,
1906
-                __FUNCTION__,
1907
-                __LINE__
1908
-            );
1909
-        } else {
1910
-            EE_Error::add_error(
1911
-                esc_html__(
1912
-                    'The payment was processed successfully but the amount paid for the transaction was not updated.',
1913
-                    'event_espresso'
1914
-                ),
1915
-                __FILE__,
1916
-                __FUNCTION__,
1917
-                __LINE__
1918
-            );
1919
-        }
1920
-    }
1921
-
1922
-
1923
-    /**
1924
-     * _get_REG_IDs_to_apply_payment_to
1925
-     * returns a list of registration IDs that the payment will apply to
1926
-     *
1927
-     * @param EE_Payment $payment
1928
-     * @return array
1929
-     * @throws EE_Error
1930
-     * @throws InvalidArgumentException
1931
-     * @throws InvalidDataTypeException
1932
-     * @throws InvalidInterfaceException
1933
-     * @throws ReflectionException
1934
-     */
1935
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1936
-    {
1937
-        // grab array of IDs for specific registrations to apply changes to
1938
-        $apply_to_all = $this->request->getRequestParam(
1939
-            'txn_admin_payment[apply_to_all_registrations]',
1940
-            false,
1941
-            DataType::BOOL
1942
-        );
1943
-        $REG_IDs = ! $apply_to_all
1944
-            ? $this->request->getRequestParam(
1945
-                'txn_admin_payment[registrations]',
1946
-                [],
1947
-                DataType::INT,
1948
-                true
1949
-            )
1950
-            : [];
1951
-        // nothing specified ? then get all reg IDs
1952
-        if ($apply_to_all || empty($REG_IDs)) {
1953
-            $registrations = $payment->transaction()->registrations();
1954
-            $REG_IDs       = ! empty($registrations)
1955
-                ? array_keys($registrations)
1956
-                : $this->_get_existing_reg_payment_REG_IDs($payment);
1957
-        }
1958
-        // ensure that REG_IDs are integers and NOT strings
1959
-        return array_map('absint', $REG_IDs);
1960
-    }
1961
-
1962
-
1963
-    /**
1964
-     * @return array
1965
-     */
1966
-    public function existing_reg_payment_REG_IDs()
1967
-    {
1968
-        return $this->_existing_reg_payment_REG_IDs;
1969
-    }
1970
-
1971
-
1972
-    /**
1973
-     * @param array $existing_reg_payment_REG_IDs
1974
-     */
1975
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1976
-    {
1977
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1978
-    }
1979
-
1980
-
1981
-    /**
1982
-     * _get_existing_reg_payment_REG_IDs
1983
-     * returns a list of registration IDs that the payment is currently related to
1984
-     * as recorded in the database
1985
-     *
1986
-     * @param EE_Payment $payment
1987
-     * @return array
1988
-     * @throws EE_Error
1989
-     * @throws InvalidArgumentException
1990
-     * @throws InvalidDataTypeException
1991
-     * @throws InvalidInterfaceException
1992
-     * @throws ReflectionException
1993
-     */
1994
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1995
-    {
1996
-        if ($this->existing_reg_payment_REG_IDs() === null) {
1997
-            // let's get any existing reg payment records for this payment
1998
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1999
-            // but we only want the REG IDs, so grab the array keys
2000
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2001
-                ? array_keys($existing_reg_payment_REG_IDs)
2002
-                : [];
2003
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2004
-        }
2005
-
2006
-        return $this->existing_reg_payment_REG_IDs();
2007
-    }
2008
-
2009
-
2010
-    /**
2011
-     * _remove_existing_registration_payments
2012
-     * this calculates the difference between existing relations
2013
-     * to the supplied payment and the new list registration IDs,
2014
-     * removes any related registrations that no longer apply,
2015
-     * and then updates the registration paid fields
2016
-     *
2017
-     * @param EE_Payment $payment
2018
-     * @param int        $PAY_ID
2019
-     * @return bool;
2020
-     * @throws EE_Error
2021
-     * @throws InvalidArgumentException
2022
-     * @throws ReflectionException
2023
-     * @throws InvalidDataTypeException
2024
-     * @throws InvalidInterfaceException
2025
-     */
2026
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2027
-    {
2028
-        // newly created payments will have nothing recorded for $PAY_ID
2029
-        if (absint($PAY_ID) === 0) {
2030
-            return false;
2031
-        }
2032
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2033
-        if (empty($existing_reg_payment_REG_IDs)) {
2034
-            return false;
2035
-        }
2036
-        /** @type EE_Transaction_Payments $transaction_payments */
2037
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2038
-
2039
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
2040
-            $payment,
2041
-            [
2042
-                [
2043
-                    'PAY_ID' => $payment->ID(),
2044
-                    'REG_ID' => ['IN', $existing_reg_payment_REG_IDs],
2045
-                ],
2046
-            ]
2047
-        );
2048
-    }
2049
-
2050
-
2051
-    /**
2052
-     * _update_registration_payments
2053
-     * this applies the payments to the selected registrations
2054
-     * but only if they have not already been paid for
2055
-     *
2056
-     * @param EE_Transaction $transaction
2057
-     * @param EE_Payment     $payment
2058
-     * @param array          $REG_IDs
2059
-     * @return void
2060
-     * @throws EE_Error
2061
-     * @throws InvalidArgumentException
2062
-     * @throws ReflectionException
2063
-     * @throws RuntimeException
2064
-     * @throws InvalidDataTypeException
2065
-     * @throws InvalidInterfaceException
2066
-     */
2067
-    protected function _update_registration_payments(
2068
-        EE_Transaction $transaction,
2069
-        EE_Payment $payment,
2070
-        $REG_IDs = []
2071
-    ) {
2072
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2073
-        // so let's do that using our set of REG_IDs from the form
2074
-        $registration_query_where_params = [
2075
-            'REG_ID' => ['IN', $REG_IDs],
2076
-        ];
2077
-        // but add in some conditions regarding payment,
2078
-        // so that we don't apply payments to registrations that are free or have already been paid for
2079
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2080
-        if (! $payment->is_a_refund()) {
2081
-            $registration_query_where_params['REG_final_price']  = ['!=', 0];
2082
-            $registration_query_where_params['REG_final_price*'] = ['!=', 'REG_paid', true];
2083
-        }
2084
-        $registrations = $transaction->registrations([$registration_query_where_params]);
2085
-        if (! empty($registrations)) {
2086
-            /** @type EE_Payment_Processor $payment_processor */
2087
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2088
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
2089
-        }
2090
-    }
2091
-
2092
-
2093
-    /**
2094
-     * _process_registration_status_change
2095
-     * This processes requested registration status changes for all the registrations
2096
-     * on a given transaction and (optionally) sends out notifications for the changes.
2097
-     *
2098
-     * @param EE_Transaction $transaction
2099
-     * @param array          $REG_IDs
2100
-     * @return bool
2101
-     * @throws EE_Error
2102
-     * @throws InvalidArgumentException
2103
-     * @throws ReflectionException
2104
-     * @throws InvalidDataTypeException
2105
-     * @throws InvalidInterfaceException
2106
-     */
2107
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = [], $reg_status = '')
2108
-    {
2109
-        // first if there is no change in status then we get out.
2110
-        $reg_status = $reg_status ?: $this->request->getRequestParam('txn_reg_status_change[reg_status]', 'NAN');
2111
-        if ($reg_status === 'NAN') {
2112
-            // no error message, no change requested, just nothing to do man.
2113
-            return false;
2114
-        }
2115
-        /** @type EE_Transaction_Processor $transaction_processor */
2116
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2117
-
2118
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2119
-        return $transaction_processor->manually_update_registration_statuses(
2120
-            $transaction,
2121
-            $reg_status,
2122
-            [['REG_ID' => ['IN', $REG_IDs]]]
2123
-        );
2124
-    }
2125
-
2126
-
2127
-    /**
2128
-     * _build_payment_json_response
2129
-     *
2130
-     * @access public
2131
-     * @param EE_Payment  $payment
2132
-     * @param array       $REG_IDs
2133
-     * @param bool | null $delete_txn_reg_status_change
2134
-     * @return array
2135
-     * @throws EE_Error
2136
-     * @throws InvalidArgumentException
2137
-     * @throws InvalidDataTypeException
2138
-     * @throws InvalidInterfaceException
2139
-     * @throws ReflectionException
2140
-     */
2141
-    protected function _build_payment_json_response(
2142
-        EE_Payment $payment,
2143
-        $REG_IDs = [],
2144
-        $delete_txn_reg_status_change = null
2145
-    ) {
2146
-        // was the payment deleted ?
2147
-        if (is_bool($delete_txn_reg_status_change)) {
2148
-            return [
2149
-                'PAY_ID'                       => $payment->ID(),
2150
-                'amount'                       => $payment->amount(),
2151
-                'total_paid'                   => $payment->transaction()->paid(),
2152
-                'txn_status'                   => $payment->transaction()->status_ID(),
2153
-                'pay_status'                   => $payment->STS_ID(),
2154
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2155
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2156
-            ];
2157
-        }
2158
-
2159
-        $this->_get_payment_status_array();
2160
-        return [
2161
-            'amount'           => $payment->amount(),
2162
-            'total_paid'       => $payment->transaction()->paid(),
2163
-            'txn_status'       => $payment->transaction()->status_ID(),
2164
-            'pay_status'       => $payment->STS_ID(),
2165
-            'PAY_ID'           => $payment->ID(),
2166
-            'STS_ID'           => $payment->STS_ID(),
2167
-            'status'           => self::$_pay_status[ $payment->STS_ID() ],
2168
-            'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2169
-            'method'           => strtoupper($payment->source()),
2170
-            'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2171
-            'gateway'          => $payment->payment_method()
2172
-                ? $payment->payment_method()->admin_name()
2173
-                : esc_html__('Unknown', 'event_espresso'),
2174
-            'gateway_response' => $payment->gateway_response(),
2175
-            'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2176
-            'po_number'        => $payment->po_number(),
2177
-            'extra_accntng'    => $payment->extra_accntng(),
2178
-            'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2179
-        ];
2180
-    }
2181
-
2182
-
2183
-    /**
2184
-     * delete_payment
2185
-     *    delete a payment or refund made towards a transaction
2186
-     *
2187
-     * @access public
2188
-     * @return void
2189
-     * @throws EE_Error
2190
-     * @throws InvalidArgumentException
2191
-     * @throws ReflectionException
2192
-     * @throws InvalidDataTypeException
2193
-     * @throws InvalidInterfaceException
2194
-     */
2195
-    public function delete_payment()
2196
-    {
2197
-        $TXD_ID = $this->request->getRequestParam('delete_txn_admin_payment[TXN_ID]', 0, 'int');
2198
-        // $json_response_data = ['return_data' => false];
2199
-        $PAY_ID = $this->request->getRequestParam('delete_txn_admin_payment[PAY_ID]', 0, 'int');
2200
-        $amount = 0;
2201
-        $can_delete         = EE_Registry::instance()->CAP->current_user_can(
2202
-            'ee_delete_payments',
2203
-            'delete_payment_from_registration_details'
2204
-        );
2205
-        if ($PAY_ID && $can_delete) {
2206
-            $delete_txn_reg_status_change = $this->request->getRequestParam('delete_txn_reg_status_change[reg_status]');
2207
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2208
-            if ($payment instanceof EE_Payment) {
2209
-                $amount = $payment->amount();
2210
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2211
-                /** @type EE_Transaction_Payments $transaction_payments */
2212
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2213
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2214
-                    if ($delete_txn_reg_status_change) {
2215
-                        $this->_maybe_send_notifications();
2216
-                        $this->_process_registration_status_change(
2217
-                            $payment->transaction(),
2218
-                            $REG_IDs,
2219
-                            $delete_txn_reg_status_change
2220
-                        );
2221
-                    }
2222
-                }
2223
-            } else {
2224
-                EE_Error::add_error(
2225
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2226
-                    __FILE__,
2227
-                    __FUNCTION__,
2228
-                    __LINE__
2229
-                );
2230
-            }
2231
-        } elseif ($can_delete) {
2232
-            EE_Error::add_error(
2233
-                esc_html__(
2234
-                    'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2235
-                    'event_espresso'
2236
-                ),
2237
-                __FILE__,
2238
-                __FUNCTION__,
2239
-                __LINE__
2240
-            );
2241
-        } else {
2242
-            EE_Error::add_error(
2243
-                esc_html__(
2244
-                    'You do not have access to delete a payment.',
2245
-                    'event_espresso'
2246
-                ),
2247
-                __FILE__,
2248
-                __FUNCTION__,
2249
-                __LINE__
2250
-            );
2251
-        }
2252
-        $query_args = [
2253
-            'page'   => 'espresso_transactions',
2254
-            'action' => 'view_transaction',
2255
-            'TXN_ID' => $TXD_ID
2256
-        ];
2257
-        $this->_redirect_after_action(
2258
-            ! EE_Error::has_error(),
2259
-            $amount > 0
2260
-                ? esc_html__('payment', 'event_espresso')
2261
-                : esc_html__('refund', 'event_espresso'),
2262
-            esc_html__('deleted', 'event_espresso'),
2263
-            $query_args
2264
-        );
2265
-    }
2266
-
2267
-
2268
-    /**
2269
-     * _registration_payment_data_array
2270
-     * adds info for 'owing' and 'paid' for each registration to the json response
2271
-     *
2272
-     * @access protected
2273
-     * @param array $REG_IDs
2274
-     * @return array
2275
-     * @throws EE_Error
2276
-     * @throws InvalidArgumentException
2277
-     * @throws InvalidDataTypeException
2278
-     * @throws InvalidInterfaceException
2279
-     * @throws ReflectionException
2280
-     */
2281
-    protected function _registration_payment_data_array($REG_IDs)
2282
-    {
2283
-        $registration_payment_data = [];
2284
-        // if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2285
-        if (! empty($REG_IDs)) {
2286
-            $registrations = EEM_Registration::instance()->get_all([['REG_ID' => ['IN', $REG_IDs]]]);
2287
-            foreach ($registrations as $registration) {
2288
-                if ($registration instanceof EE_Registration) {
2289
-                    $registration_payment_data[ $registration->ID() ] = [
2290
-                        'paid'  => $registration->pretty_paid(),
2291
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2292
-                    ];
2293
-                }
2294
-            }
2295
-        }
2296
-
2297
-        return $registration_payment_data;
2298
-    }
2299
-
2300
-
2301
-    /**
2302
-     * _maybe_send_notifications
2303
-     * determines whether or not the admin has indicated that notifications should be sent.
2304
-     * If so, will toggle a filter switch for delivering registration notices.
2305
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
2306
-     *
2307
-     * @access protected
2308
-     * @param EE_Payment | null $payment
2309
-     */
2310
-    protected function _maybe_send_notifications($payment = null)
2311
-    {
2312
-        switch ($payment instanceof EE_Payment) {
2313
-            // payment notifications
2314
-            case true:
2315
-                if ($this->request->getRequestParam('txn_payments[send_notifications]', false, 'bool')) {
2316
-                    $this->_process_payment_notification($payment);
2317
-                }
2318
-                break;
2319
-            // registration notifications
2320
-            case false:
2321
-                if ($this->request->getRequestParam('txn_reg_status_change[send_notifications]', false, 'bool')) {
2322
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2323
-                }
2324
-                break;
2325
-        }
2326
-    }
2327
-
2328
-
2329
-    /**
2330
-     * _send_payment_reminder
2331
-     *    generates HTML for the View Transaction Details Admin page
2332
-     *
2333
-     * @access protected
2334
-     * @return void
2335
-     * @throws EE_Error
2336
-     * @throws InvalidArgumentException
2337
-     * @throws InvalidDataTypeException
2338
-     * @throws InvalidInterfaceException
2339
-     */
2340
-    protected function _send_payment_reminder()
2341
-    {
2342
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2343
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2344
-        $redirect_to = $this->request->getRequestParam('redirect_to');
2345
-        $query_args  = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2346
-        do_action(
2347
-            'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2348
-            $transaction
2349
-        );
2350
-        $this->_redirect_after_action(
2351
-            false,
2352
-            esc_html__('payment reminder', 'event_espresso'),
2353
-            esc_html__('sent', 'event_espresso'),
2354
-            $query_args,
2355
-            true
2356
-        );
2357
-    }
2358
-
2359
-
2360
-    /**
2361
-     *  get_transactions
2362
-     *    get transactions for given parameters (used by list table)
2363
-     *
2364
-     * @param int     $per_page how many transactions displayed per page
2365
-     * @param boolean $count   return the count or objects
2366
-     * @param string  $view
2367
-     * @return EE_Transaction[]|int int = count || array of transaction objects
2368
-     * @throws EE_Error
2369
-     * @throws InvalidArgumentException
2370
-     * @throws InvalidDataTypeException
2371
-     * @throws InvalidInterfaceException
2372
-     */
2373
-    public function get_transactions($per_page, $count = false, $view = '')
2374
-    {
2375
-        $start_date = wp_strip_all_tags(
2376
-            $this->request->getRequestParam('txn-filter-start-date', date('m/d/Y', strtotime('-10 year')))
2377
-        );
2378
-        $end_date = wp_strip_all_tags(
2379
-            $this->request->getRequestParam('txn-filter-end-date', date('m/d/Y'))
2380
-        );
2381
-
2382
-        // make sure our timestamps start and end right at the boundaries for each day
2383
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2384
-        $end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2385
-
2386
-
2387
-        // convert to timestamps
2388
-        $start_date = strtotime($start_date);
2389
-        $end_date   = strtotime($end_date);
2390
-
2391
-        // makes sure start date is the lowest value and vice versa
2392
-        $start_date = min($start_date, $end_date);
2393
-        $end_date   = max($start_date, $end_date);
2394
-
2395
-        // convert to correct format for query
2396
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2397
-            'TXN_timestamp',
2398
-            date('Y-m-d H:i:s', $start_date),
2399
-            'Y-m-d H:i:s'
2400
-        );
2401
-        $end_date   = EEM_Transaction::instance()->convert_datetime_for_query(
2402
-            'TXN_timestamp',
2403
-            date('Y-m-d H:i:s', $end_date),
2404
-            'Y-m-d H:i:s'
2405
-        );
2406
-
2407
-
2408
-        // set orderby
2409
-        $orderby = $this->request->getRequestParam('orderby');
2410
-
2411
-        switch ($orderby) {
2412
-            case 'TXN_ID':
2413
-                break;
2414
-            case 'ATT_fname':
2415
-                $orderby = 'Registration.Attendee.ATT_fname';
2416
-                break;
2417
-            case 'event_name':
2418
-                $orderby = 'Registration.Event.EVT_name';
2419
-                break;
2420
-            default: // 'TXN_timestamp'
2421
-                $orderby = 'TXN_timestamp';
2422
-        }
2423
-
2424
-        $sort         = $this->request->getRequestParam('order', 'DESC');
2425
-        $current_page = $this->request->getRequestParam('paged', 1, 'int');
2426
-
2427
-        $per_page = absint($per_page) ? $per_page : 10;
2428
-        $per_page = $this->request->getRequestParam('perpage', $per_page, 'int');
2429
-
2430
-        $offset = ($current_page - 1) * $per_page;
2431
-        $limit  = [$offset, $per_page];
2432
-
2433
-        $_where = [
2434
-            'TXN_timestamp'          => ['BETWEEN', [$start_date, $end_date]],
2435
-            'Registration.REG_count' => 1,
2436
-        ];
2437
-
2438
-        $EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2439
-        if ($EVT_ID) {
2440
-            $_where['Registration.EVT_ID'] = $EVT_ID;
2441
-        }
2442
-
2443
-        $search_term = $this->request->getRequestParam('s');
2444
-        if ($search_term) {
2445
-            $search_term = '%' . $search_term . '%';
2446
-            $_where['OR']  = [
2447
-                'Registration.Event.EVT_name'         => ['LIKE', $search_term],
2448
-                'Registration.Event.EVT_desc'         => ['LIKE', $search_term],
2449
-                'Registration.Event.EVT_short_desc'   => ['LIKE', $search_term],
2450
-                'Registration.Attendee.ATT_full_name' => ['LIKE', $search_term],
2451
-                'Registration.Attendee.ATT_fname'     => ['LIKE', $search_term],
2452
-                'Registration.Attendee.ATT_lname'     => ['LIKE', $search_term],
2453
-                'Registration.Attendee.ATT_short_bio' => ['LIKE', $search_term],
2454
-                'Registration.Attendee.ATT_email'     => ['LIKE', $search_term],
2455
-                'Registration.Attendee.ATT_address'   => ['LIKE', $search_term],
2456
-                'Registration.Attendee.ATT_address2'  => ['LIKE', $search_term],
2457
-                'Registration.Attendee.ATT_city'      => ['LIKE', $search_term],
2458
-                'Registration.REG_final_price'        => ['LIKE', $search_term],
2459
-                'Registration.REG_code'               => ['LIKE', $search_term],
2460
-                'Registration.REG_count'              => ['LIKE', $search_term],
2461
-                'Registration.REG_group_size'         => ['LIKE', $search_term],
2462
-                'Registration.Ticket.TKT_name'        => ['LIKE', $search_term],
2463
-                'Registration.Ticket.TKT_description' => ['LIKE', $search_term],
2464
-                'Payment.PAY_source'                  => ['LIKE', $search_term],
2465
-                'Payment.Payment_Method.PMD_name'     => ['LIKE', $search_term],
2466
-                'TXN_session_data'                    => ['LIKE', $search_term],
2467
-                'Payment.PAY_txn_id_chq_nmbr'         => ['LIKE', $search_term],
2468
-            ];
2469
-        }
2470
-
2471
-        $status = $this->request->getRequestParam('status');
2472
-        // failed transactions
2473
-        $failed     = (! empty($status) && $status === 'failed' && ! $count) || ($count && $view === 'failed');
2474
-        $abandoned  = (! empty($status) && $status === 'abandoned' && ! $count) || ($count && $view === 'abandoned');
2475
-        $incomplete = (! empty($status) && $status === 'incomplete' && ! $count) || ($count && $view === 'incomplete');
2476
-
2477
-        if ($failed) {
2478
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
2479
-        } elseif ($abandoned) {
2480
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2481
-        } elseif ($incomplete) {
2482
-            $_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2483
-        } else {
2484
-            $_where['STS_ID']  = ['!=', EEM_Transaction::failed_status_code];
2485
-            $_where['STS_ID*'] = ['!=', EEM_Transaction::abandoned_status_code];
2486
-        }
2487
-
2488
-        $query_params = apply_filters(
2489
-            'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2490
-            [
2491
-                $_where,
2492
-                'order_by'                 => [$orderby => $sort],
2493
-                'limit'                    => $limit,
2494
-                'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2495
-            ],
2496
-            $this->request->requestParams(),
2497
-            $view,
2498
-            $count
2499
-        );
2500
-
2501
-        return $count
2502
-            ? EEM_Transaction::instance()->count([$query_params[0]], 'TXN_ID', true)
2503
-            : EEM_Transaction::instance()->get_all($query_params);
2504
-    }
2505
-
2506
-
2507
-    /**
2508
-     * @throws EE_Error
2509
-     * @throws InvalidArgumentException
2510
-     * @throws InvalidDataTypeException
2511
-     * @throws InvalidInterfaceException
2512
-     * @throws ReflectionException
2513
-     * @throws RuntimeException
2514
-     * @since 4.9.79.p
2515
-     */
2516
-    public function recalculateLineItems()
2517
-    {
2518
-        $TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2519
-        /** @var EE_Transaction $transaction */
2520
-        $transaction     = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2521
-        $success         = $transaction->recalculateLineItems();
2522
-        $redirect_to = $this->request->getRequestParam('redirect_to');
2523
-        $query_args = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2524
-        $this->_redirect_after_action(
2525
-            $success,
2526
-            esc_html__('Transaction taxes and totals', 'event_espresso'),
2527
-            esc_html__('recalculated', 'event_espresso'),
2528
-            $query_args,
2529
-            true
2530
-        );
2531
-    }
16
+	/**
17
+	 * @var EE_Transaction
18
+	 */
19
+	private $_transaction;
20
+
21
+	/**
22
+	 * @var EE_Session
23
+	 */
24
+	private $_session;
25
+
26
+	/**
27
+	 * @var array $_txn_status
28
+	 */
29
+	private static $_txn_status;
30
+
31
+	/**
32
+	 * @var array $_pay_status
33
+	 */
34
+	private static $_pay_status;
35
+
36
+	/**
37
+	 * @var array $_existing_reg_payment_REG_IDs
38
+	 */
39
+	protected $_existing_reg_payment_REG_IDs;
40
+
41
+
42
+	/**
43
+	 *    _init_page_props
44
+	 *
45
+	 * @return void
46
+	 */
47
+	protected function _init_page_props()
48
+	{
49
+		$this->page_slug        = TXN_PG_SLUG;
50
+		$this->page_label       = esc_html__('Transactions', 'event_espresso');
51
+		$this->_admin_base_url  = TXN_ADMIN_URL;
52
+		$this->_admin_base_path = TXN_ADMIN;
53
+	}
54
+
55
+
56
+	/**
57
+	 *    _ajax_hooks
58
+	 *
59
+	 * @return void
60
+	 */
61
+	protected function _ajax_hooks()
62
+	{
63
+		// add_action('wp_ajax_espresso_apply_payment', [$this, 'apply_payments_or_refunds']);
64
+		// add_action('wp_ajax_espresso_apply_refund', [$this, 'apply_payments_or_refunds']);
65
+		// add_action('wp_ajax_espresso_delete_payment', [$this, 'delete_payment']);
66
+	}
67
+
68
+
69
+	/**
70
+	 *    _define_page_props
71
+	 *
72
+	 * @return void
73
+	 */
74
+	protected function _define_page_props()
75
+	{
76
+		$this->_admin_page_title = $this->page_label;
77
+		$this->_labels           = [
78
+			'buttons' => [
79
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
80
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
81
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
82
+			],
83
+		];
84
+	}
85
+
86
+
87
+	/**
88
+	 *        grab url requests and route them
89
+	 *
90
+	 * @access private
91
+	 * @return void
92
+	 * @throws EE_Error
93
+	 * @throws InvalidArgumentException
94
+	 * @throws InvalidDataTypeException
95
+	 * @throws InvalidInterfaceException
96
+	 */
97
+	public function _set_page_routes()
98
+	{
99
+
100
+		$this->_set_transaction_status_array();
101
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
102
+
103
+		$this->_page_routes = [
104
+
105
+			'default' => [
106
+				'func'       => '_transactions_overview_list_table',
107
+				'capability' => 'ee_read_transactions',
108
+			],
109
+
110
+			'view_transaction' => [
111
+				'func'       => '_transaction_details',
112
+				'capability' => 'ee_read_transaction',
113
+				'obj_id'     => $TXN_ID,
114
+			],
115
+
116
+			'send_payment_reminder' => [
117
+				'func'       => '_send_payment_reminder',
118
+				'noheader'   => true,
119
+				'capability' => 'ee_send_message',
120
+			],
121
+
122
+			'espresso_apply_payment' => [
123
+				'func'       => 'apply_payments_or_refunds',
124
+				'noheader'   => true,
125
+				'capability' => 'ee_edit_payments',
126
+			],
127
+
128
+			'espresso_apply_refund' => [
129
+				'func'       => 'apply_payments_or_refunds',
130
+				'noheader'   => true,
131
+				'capability' => 'ee_edit_payments',
132
+			],
133
+
134
+			'espresso_delete_payment' => [
135
+				'func'       => [$this, 'delete_payment'],
136
+				'noheader'   => true,
137
+				'capability' => 'ee_delete_payments',
138
+			],
139
+
140
+			'espresso_recalculate_line_items' => [
141
+				'func'       => 'recalculateLineItems',
142
+				'noheader'   => true,
143
+				'capability' => 'ee_edit_payments',
144
+			],
145
+
146
+		];
147
+	}
148
+
149
+
150
+	protected function _set_page_config()
151
+	{
152
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
153
+		$this->_page_config = [
154
+			'default'          => [
155
+				'nav'           => [
156
+					'label' => esc_html__('Overview', 'event_espresso'),
157
+					'order' => 10,
158
+				],
159
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
160
+				'help_tabs'     => [
161
+					'transactions_overview_help_tab'                       => [
162
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
163
+						'filename' => 'transactions_overview',
164
+					],
165
+					'transactions_overview_table_column_headings_help_tab' => [
166
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
167
+						'filename' => 'transactions_overview_table_column_headings',
168
+					],
169
+					'transactions_overview_views_filters_help_tab'         => [
170
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
171
+						'filename' => 'transactions_overview_views_filters_search',
172
+					],
173
+				],
174
+				'require_nonce' => false,
175
+			],
176
+			'view_transaction' => [
177
+				'nav'       => [
178
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
179
+					'order'      => 5,
180
+					'url'        => $TXN_ID
181
+						? add_query_arg(['TXN_ID' => $TXN_ID], $this->_current_page_view_url)
182
+						: $this->_admin_base_url,
183
+					'persistent' => false,
184
+				],
185
+				'help_tabs' => [
186
+					'transactions_view_transaction_help_tab'                                              => [
187
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
188
+						'filename' => 'transactions_view_transaction',
189
+					],
190
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => [
191
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
192
+						'filename' => 'transactions_view_transaction_transaction_details_table',
193
+					],
194
+					'transactions_view_transaction_attendees_registered_help_tab'                         => [
195
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
196
+						'filename' => 'transactions_view_transaction_attendees_registered',
197
+					],
198
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => [
199
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
200
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information',
201
+					],
202
+				],
203
+				'qtips'     => ['Transaction_Details_Tips'],
204
+				'metaboxes' => ['_transaction_details_metaboxes'],
205
+
206
+				'require_nonce' => false,
207
+			],
208
+		];
209
+	}
210
+
211
+
212
+	/**
213
+	 * The below methods aren't used by this class currently
214
+	 */
215
+	protected function _add_screen_options()
216
+	{
217
+		// noop
218
+	}
219
+
220
+
221
+	protected function _add_feature_pointers()
222
+	{
223
+		// noop
224
+	}
225
+
226
+
227
+	public function admin_init()
228
+	{
229
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
230
+		$event_name = $this->request->getRequestParam('event_name');
231
+		$redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
232
+		// IF a registration was JUST added via the admin...
233
+		if ($EVT_ID && $event_name && $redirect_from) {
234
+			// then set a cookie so that we can block any attempts to use
235
+			// the back button as a way to enter another registration.
236
+			setcookie('ee_registration_added', $EVT_ID, time() + WEEK_IN_SECONDS, '/');
237
+			// and update the global
238
+			$_COOKIE['ee_registration_added'] = $EVT_ID;
239
+		}
240
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__(
241
+			'An error occurred! Your request may have been processed, but a valid response from the server was not received. Please refresh the page and try again.',
242
+			'event_espresso'
243
+		);
244
+		EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__(
245
+			'An error occurred! Please refresh the page and try again.',
246
+			'event_espresso'
247
+		);
248
+		EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
249
+		EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
250
+		EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
251
+		EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__(
252
+			'This transaction has been overpaid ! Payments Total',
253
+			'event_espresso'
254
+		);
255
+	}
256
+
257
+
258
+	public function admin_notices()
259
+	{
260
+		// noop
261
+	}
262
+
263
+
264
+	public function admin_footer_scripts()
265
+	{
266
+		// noop
267
+	}
268
+
269
+
270
+	/**
271
+	 * _set_transaction_status_array
272
+	 * sets list of transaction statuses
273
+	 *
274
+	 * @access private
275
+	 * @return void
276
+	 * @throws EE_Error
277
+	 * @throws InvalidArgumentException
278
+	 * @throws InvalidDataTypeException
279
+	 * @throws InvalidInterfaceException
280
+	 */
281
+	private function _set_transaction_status_array()
282
+	{
283
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
284
+	}
285
+
286
+
287
+	/**
288
+	 * get_transaction_status_array
289
+	 * return the transaction status array for wp_list_table
290
+	 *
291
+	 * @access public
292
+	 * @return array
293
+	 */
294
+	public function get_transaction_status_array()
295
+	{
296
+		return self::$_txn_status;
297
+	}
298
+
299
+
300
+	/**
301
+	 *    get list of payment statuses
302
+	 *
303
+	 * @access private
304
+	 * @return void
305
+	 * @throws EE_Error
306
+	 * @throws InvalidArgumentException
307
+	 * @throws InvalidDataTypeException
308
+	 * @throws InvalidInterfaceException
309
+	 */
310
+	private function _get_payment_status_array()
311
+	{
312
+		self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
313
+		$this->_template_args['payment_status'] = self::$_pay_status;
314
+	}
315
+
316
+
317
+	/**
318
+	 *    _add_screen_options_default
319
+	 *
320
+	 * @access protected
321
+	 * @return void
322
+	 * @throws InvalidArgumentException
323
+	 * @throws InvalidDataTypeException
324
+	 * @throws InvalidInterfaceException
325
+	 */
326
+	protected function _add_screen_options_default()
327
+	{
328
+		$this->_per_page_screen_option();
329
+	}
330
+
331
+
332
+	/**
333
+	 * load_scripts_styles
334
+	 *
335
+	 * @access public
336
+	 * @return void
337
+	 */
338
+	public function load_scripts_styles()
339
+	{
340
+		// enqueue style
341
+		wp_register_style(
342
+			'espresso_txn',
343
+			TXN_ASSETS_URL . 'espresso_transactions_admin.css',
344
+			[],
345
+			EVENT_ESPRESSO_VERSION
346
+		);
347
+		wp_enqueue_style('espresso_txn');
348
+		// scripts
349
+		wp_register_script(
350
+			'espresso_txn',
351
+			TXN_ASSETS_URL . 'espresso_transactions_admin.js',
352
+			[
353
+				'ee_admin_js',
354
+				'ee-datepicker',
355
+				'jquery-ui-datepicker',
356
+				'jquery-ui-draggable',
357
+				'ee-dialog',
358
+				'ee-accounting',
359
+				'ee-serialize-full-array',
360
+			],
361
+			EVENT_ESPRESSO_VERSION,
362
+			true
363
+		);
364
+		wp_enqueue_script('espresso_txn');
365
+	}
366
+
367
+
368
+	/**
369
+	 *    load_scripts_styles_view_transaction
370
+	 *
371
+	 * @access public
372
+	 * @return void
373
+	 */
374
+	public function load_scripts_styles_view_transaction()
375
+	{
376
+		// styles
377
+		wp_enqueue_style('espresso-ui-theme');
378
+	}
379
+
380
+
381
+	/**
382
+	 *    load_scripts_styles_default
383
+	 *
384
+	 * @access public
385
+	 * @return void
386
+	 */
387
+	public function load_scripts_styles_default()
388
+	{
389
+		// styles
390
+		wp_enqueue_style('espresso-ui-theme');
391
+	}
392
+
393
+
394
+	/**
395
+	 *    _set_list_table_views_default
396
+	 *
397
+	 * @access protected
398
+	 * @return void
399
+	 */
400
+	protected function _set_list_table_views_default()
401
+	{
402
+		$this->_views = [
403
+			'all'        => [
404
+				'slug'  => 'all',
405
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
406
+				'count' => 0,
407
+			],
408
+			'abandoned'  => [
409
+				'slug'  => 'abandoned',
410
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
411
+				'count' => 0,
412
+			],
413
+			'incomplete' => [
414
+				'slug'  => 'incomplete',
415
+				'label' => esc_html__('Incomplete Transactions', 'event_espresso'),
416
+				'count' => 0,
417
+			],
418
+		];
419
+		if (
420
+			/**
421
+			 * Filters whether a link to the "Failed Transactions" list table
422
+			 * appears on the Transactions Admin Page list table.
423
+			 * List display can be turned back on via the following:
424
+			 * add_filter(
425
+			 *     'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
426
+			 *     '__return_true'
427
+			 * );
428
+			 *
429
+			 * @param boolean                 $display_failed_txns_list
430
+			 * @param Transactions_Admin_Page $this
431
+			 * @since 4.9.70.p
432
+			 */
433
+			apply_filters(
434
+				'FHEE__Transactions_Admin_Page___set_list_table_views_default__display_failed_txns_list',
435
+				false,
436
+				$this
437
+			)
438
+		) {
439
+			$this->_views['failed'] = [
440
+				'slug'  => 'failed',
441
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
442
+				'count' => 0,
443
+			];
444
+		}
445
+	}
446
+
447
+
448
+	/**
449
+	 * _set_transaction_object
450
+	 * This sets the _transaction property for the transaction details screen
451
+	 *
452
+	 * @access private
453
+	 * @return void
454
+	 * @throws EE_Error
455
+	 * @throws InvalidArgumentException
456
+	 * @throws RuntimeException
457
+	 * @throws InvalidDataTypeException
458
+	 * @throws InvalidInterfaceException
459
+	 * @throws ReflectionException
460
+	 */
461
+	private function _set_transaction_object()
462
+	{
463
+		if ($this->_transaction instanceof EE_Transaction) {
464
+			return;
465
+		} //get out we've already set the object
466
+
467
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
468
+
469
+		// get transaction object
470
+		$this->_transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
471
+		$this->_session     = $this->_transaction instanceof EE_Transaction
472
+			? $this->_transaction->session_data()
473
+			: null;
474
+		if ($this->_transaction instanceof EE_Transaction) {
475
+			$this->_transaction->verify_abandoned_transaction_status();
476
+		}
477
+
478
+		if (! $this->_transaction instanceof EE_Transaction) {
479
+			$error_msg = sprintf(
480
+				esc_html__(
481
+					'An error occurred and the details for the transaction with the ID # %d could not be retrieved.',
482
+					'event_espresso'
483
+				),
484
+				$TXN_ID
485
+			);
486
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
487
+		}
488
+	}
489
+
490
+
491
+	/**
492
+	 *    _transaction_legend_items
493
+	 *
494
+	 * @access protected
495
+	 * @return array
496
+	 * @throws EE_Error
497
+	 * @throws InvalidArgumentException
498
+	 * @throws ReflectionException
499
+	 * @throws InvalidDataTypeException
500
+	 * @throws InvalidInterfaceException
501
+	 */
502
+	protected function _transaction_legend_items()
503
+	{
504
+		EE_Registry::instance()->load_helper('MSG_Template');
505
+		$items = [];
506
+
507
+		if (
508
+			EE_Registry::instance()->CAP->current_user_can(
509
+				'ee_read_global_messages',
510
+				'view_filtered_messages'
511
+			)
512
+		) {
513
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
514
+			if (
515
+				is_array($related_for_icon)
516
+				&& isset($related_for_icon['css_class'], $related_for_icon['label'])
517
+			) {
518
+				$items['view_related_messages'] = [
519
+					'class' => $related_for_icon['css_class'],
520
+					'desc'  => $related_for_icon['label'],
521
+				];
522
+			}
523
+		}
524
+
525
+		$items = apply_filters(
526
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
527
+			array_merge(
528
+				$items,
529
+				[
530
+					'view_details'          => [
531
+						'class' => 'dashicons dashicons-cart',
532
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso'),
533
+					],
534
+					'view_invoice'          => [
535
+						'class' => 'dashicons dashicons-media-spreadsheet',
536
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso'),
537
+					],
538
+					'view_receipt'          => [
539
+						'class' => 'dashicons dashicons-text-page',
540
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso'),
541
+					],
542
+					'view_registration'     => [
543
+						'class' => 'dashicons dashicons-clipboard',
544
+						'desc'  => esc_html__('View Registration Details', 'event_espresso'),
545
+					],
546
+					'payment_overview_link' => [
547
+						'class' => 'dashicons dashicons-money',
548
+						'desc'  => esc_html__('Make Payment on Frontend', 'event_espresso'),
549
+					],
550
+				]
551
+			)
552
+		);
553
+
554
+		if (
555
+			EEH_MSG_Template::is_mt_active('payment_reminder')
556
+			&& EE_Registry::instance()->CAP->current_user_can(
557
+				'ee_send_message',
558
+				'espresso_transactions_send_payment_reminder'
559
+			)
560
+		) {
561
+			$items['send_payment_reminder'] = [
562
+				'class' => 'dashicons dashicons-email-alt',
563
+				'desc'  => esc_html__('Send Payment Reminder', 'event_espresso'),
564
+			];
565
+		} else {
566
+			$items['blank*'] = [
567
+				'class' => '',
568
+				'desc'  => '',
569
+			];
570
+		}
571
+		$more_items = apply_filters(
572
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
573
+			[
574
+				'overpaid'   => [
575
+					'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::overpaid_status_code,
576
+					'desc'  => EEH_Template::pretty_status(
577
+						EEM_Transaction::overpaid_status_code,
578
+						false,
579
+						'sentence'
580
+					),
581
+				],
582
+				'complete'   => [
583
+					'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::complete_status_code,
584
+					'desc'  => EEH_Template::pretty_status(
585
+						EEM_Transaction::complete_status_code,
586
+						false,
587
+						'sentence'
588
+					),
589
+				],
590
+				'incomplete' => [
591
+					'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::incomplete_status_code,
592
+					'desc'  => EEH_Template::pretty_status(
593
+						EEM_Transaction::incomplete_status_code,
594
+						false,
595
+						'sentence'
596
+					),
597
+				],
598
+				'abandoned'  => [
599
+					'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::abandoned_status_code,
600
+					'desc'  => EEH_Template::pretty_status(
601
+						EEM_Transaction::abandoned_status_code,
602
+						false,
603
+						'sentence'
604
+					),
605
+				],
606
+				'failed'     => [
607
+					'class' => 'ee-status-legend ee-status-bg--' . EEM_Transaction::failed_status_code,
608
+					'desc'  => EEH_Template::pretty_status(
609
+						EEM_Transaction::failed_status_code,
610
+						false,
611
+						'sentence'
612
+					),
613
+				],
614
+			]
615
+		);
616
+
617
+		return array_merge($items, $more_items);
618
+	}
619
+
620
+
621
+	/**
622
+	 *    _transactions_overview_list_table
623
+	 *
624
+	 * @access protected
625
+	 * @return void
626
+	 * @throws DomainException
627
+	 * @throws EE_Error
628
+	 * @throws InvalidArgumentException
629
+	 * @throws InvalidDataTypeException
630
+	 * @throws InvalidInterfaceException
631
+	 * @throws ReflectionException
632
+	 */
633
+	protected function _transactions_overview_list_table()
634
+	{
635
+		$this->_admin_page_title = esc_html__('Transactions', 'event_espresso');
636
+
637
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
638
+		$event = EEM_Event::instance()->get_one_by_ID($EVT_ID);
639
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event
640
+			? sprintf(
641
+				esc_html__('%sViewing Transactions for the Event: %s%s', 'event_espresso'),
642
+				'<h3>',
643
+				'<a href="'
644
+				. EE_Admin_Page::add_query_args_and_nonce(
645
+					['action' => 'edit', 'post' => $event->ID()],
646
+					EVENTS_ADMIN_URL
647
+				)
648
+				. '" title="'
649
+				. esc_attr__('Click to Edit event', 'event_espresso')
650
+				. '">' . $event->name() . '</a>',
651
+				'</h3>'
652
+			)
653
+			: '';
654
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
655
+		$this->display_admin_list_table_page_with_no_sidebar();
656
+	}
657
+
658
+
659
+	/**
660
+	 *    _transaction_details
661
+	 * generates HTML for the View Transaction Details Admin page
662
+	 *
663
+	 * @access protected
664
+	 * @return void
665
+	 * @throws DomainException
666
+	 * @throws EE_Error
667
+	 * @throws InvalidArgumentException
668
+	 * @throws InvalidDataTypeException
669
+	 * @throws InvalidInterfaceException
670
+	 * @throws RuntimeException
671
+	 * @throws ReflectionException
672
+	 */
673
+	protected function _transaction_details()
674
+	{
675
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
676
+
677
+		$this->_set_transaction_status_array();
678
+
679
+		$this->_template_args                      = [];
680
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
681
+
682
+		$this->_set_transaction_object();
683
+
684
+		if (! $this->_transaction instanceof EE_Transaction) {
685
+			return;
686
+		}
687
+
688
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
689
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
690
+
691
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
692
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
693
+
694
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[ $this->_transaction->status_ID() ];
695
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
696
+		$this->_template_args['txn_status']['class'] = $this->_transaction->status_ID();
697
+
698
+		$txn_total  = $this->_transaction->total();
699
+		$total_paid = $this->_transaction->paid();
700
+		$amount_due = $txn_total - $total_paid;
701
+
702
+		$this->_template_args['grand_total'] = $txn_total;
703
+		$this->_template_args['total_paid']  = $total_paid;
704
+
705
+		$this->_template_args['amount_due'] = EEH_Template::format_currency($amount_due, false, false);
706
+
707
+		$this->_template_args['amount_due_class'] = '';
708
+
709
+		if ($txn_total === (float) 0) {
710
+			// free event
711
+			$this->_template_args['amount_due'] = false;
712
+		} elseif ($amount_due < (float) 0) {
713
+			// overpaid
714
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
715
+		} elseif ($amount_due > (float) 0) {
716
+			// monies owing
717
+			$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn ee-txn-amount-owing';
718
+		} elseif ($total_paid === (float) 0) {
719
+			// no payments made yet
720
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
721
+		}
722
+
723
+		$payment_method = $this->_transaction->payment_method();
724
+
725
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
726
+			? $payment_method->admin_name()
727
+			: esc_html__('Unknown', 'event_espresso');
728
+
729
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
730
+		// link back to overview
731
+		$this->_template_args['txn_overview_url'] = $this->request->getServerParam(
732
+			'HTTP_REFERER',
733
+			TXN_ADMIN_URL
734
+		);
735
+
736
+
737
+		// next link
738
+		$next_txn                                 = $this->_transaction->next(
739
+			null,
740
+			[['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
741
+			'TXN_ID'
742
+		);
743
+		$this->_template_args['next_transaction'] = $next_txn
744
+			? $this->_next_link(
745
+				EE_Admin_Page::add_query_args_and_nonce(
746
+					['action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']],
747
+					TXN_ADMIN_URL
748
+				),
749
+				'dashicons dashicons-arrow-right ee-icon-size-22'
750
+			)
751
+			: '';
752
+		// previous link
753
+		$previous_txn                                 = $this->_transaction->previous(
754
+			null,
755
+			[['STS_ID' => ['!=', EEM_Transaction::failed_status_code]]],
756
+			'TXN_ID'
757
+		);
758
+		$this->_template_args['previous_transaction'] = $previous_txn
759
+			? $this->_previous_link(
760
+				EE_Admin_Page::add_query_args_and_nonce(
761
+					['action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']],
762
+					TXN_ADMIN_URL
763
+				),
764
+				'dashicons dashicons-arrow-left ee-icon-size-22'
765
+			)
766
+			: '';
767
+
768
+		$EVT_ID        = $this->request->getRequestParam('EVT_ID', 0, 'int');
769
+		$event_name    = $this->request->getRequestParam('event_name');
770
+		$redirect_from = $this->request->getRequestParam('redirect_from', '', 'url');
771
+
772
+		// were we just redirected here after adding a new registration ???
773
+		if ($EVT_ID && $event_name && $redirect_from) {
774
+			if (
775
+				EE_Registry::instance()->CAP->current_user_can(
776
+					'ee_edit_registrations',
777
+					'espresso_registrations_new_registration',
778
+					$EVT_ID
779
+				)
780
+			) {
781
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button--primary" href="';
782
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
783
+					[
784
+						'page'     => 'espresso_registrations',
785
+						'action'   => 'new_registration',
786
+						'return'   => 'default',
787
+						'TXN_ID'   => $this->_transaction->ID(),
788
+						'event_id' => $EVT_ID,
789
+					],
790
+					REG_ADMIN_URL
791
+				);
792
+				$this->_admin_page_title .= '">';
793
+
794
+				$this->_admin_page_title .= sprintf(
795
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
796
+					htmlentities(urldecode($event_name), ENT_QUOTES, 'UTF-8')
797
+				);
798
+				$this->_admin_page_title .= '</a>';
799
+			}
800
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
801
+		}
802
+		// grab messages at the last second
803
+		$this->_template_args['notices'] = EE_Error::get_notices();
804
+		// path to template
805
+		$template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
806
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template(
807
+			$template_path,
808
+			$this->_template_args,
809
+			true
810
+		);
811
+
812
+		// the details template wrapper
813
+		$this->display_admin_page_with_sidebar();
814
+	}
815
+
816
+
817
+	/**
818
+	 *        _transaction_details_metaboxes
819
+	 *
820
+	 * @access protected
821
+	 * @return void
822
+	 * @throws EE_Error
823
+	 * @throws InvalidArgumentException
824
+	 * @throws InvalidDataTypeException
825
+	 * @throws InvalidInterfaceException
826
+	 * @throws RuntimeException
827
+	 * @throws ReflectionException
828
+	 */
829
+	protected function _transaction_details_metaboxes()
830
+	{
831
+
832
+		$this->_set_transaction_object();
833
+
834
+		if (! $this->_transaction instanceof EE_Transaction) {
835
+			return;
836
+		}
837
+		$this->addMetaBox(
838
+			'edit-txn-details-mbox',
839
+			'<span>' . esc_html__('Transaction Details', 'event_espresso')
840
+			. '&nbsp;<span class="dashicons dashicons-cart" ></span></span>',
841
+			[$this, 'txn_details_meta_box'],
842
+			$this->_wp_page_slug
843
+		);
844
+		$this->addMetaBox(
845
+			'edit-txn-attendees-mbox',
846
+			'<span>' . esc_html__('Attendees Registered in this Transaction', 'event_espresso')
847
+			. '&nbsp;<span class="dashicons dashicons-groups" ></span></span>',
848
+			[$this, 'txn_attendees_meta_box'],
849
+			$this->_wp_page_slug,
850
+			'normal',
851
+			'high',
852
+			['TXN_ID' => $this->_transaction->ID()]
853
+		);
854
+		$this->addMetaBox(
855
+			'edit-txn-registrant-mbox',
856
+			esc_html__('Primary Contact', 'event_espresso'),
857
+			[$this, 'txn_registrant_side_meta_box'],
858
+			$this->_wp_page_slug,
859
+			'side'
860
+		);
861
+		$this->addMetaBox(
862
+			'edit-txn-billing-info-mbox',
863
+			esc_html__('Billing Information', 'event_espresso'),
864
+			[$this, 'txn_billing_info_side_meta_box'],
865
+			$this->_wp_page_slug,
866
+			'side'
867
+		);
868
+	}
869
+
870
+
871
+	/**
872
+	 * Callback for transaction actions metabox.
873
+	 *
874
+	 * @param EE_Transaction|null $transaction
875
+	 * @return string
876
+	 * @throws DomainException
877
+	 * @throws EE_Error
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws InvalidInterfaceException
881
+	 * @throws ReflectionException
882
+	 * @throws RuntimeException
883
+	 */
884
+	public function getActionButtons(EE_Transaction $transaction = null)
885
+	{
886
+		$content = '';
887
+		$actions = [];
888
+		if (! $transaction instanceof EE_Transaction) {
889
+			return $content;
890
+		}
891
+		/** @var EE_Registration $primary_registration */
892
+		$primary_registration = $transaction->primary_registration();
893
+		$attendee             = $primary_registration instanceof EE_Registration
894
+			? $primary_registration->attendee()
895
+			: null;
896
+
897
+		if (
898
+			$attendee instanceof EE_Attendee
899
+			&& EE_Registry::instance()->CAP->current_user_can(
900
+				'ee_send_message',
901
+				'espresso_transactions_send_payment_reminder'
902
+			)
903
+		) {
904
+			$actions['payment_reminder'] =
905
+				EEH_MSG_Template::is_mt_active('payment_reminder')
906
+				&& $this->_transaction->status_ID() !== EEM_Transaction::complete_status_code
907
+				&& $this->_transaction->status_ID() !== EEM_Transaction::overpaid_status_code
908
+					? EEH_Template::get_button_or_link(
909
+						EE_Admin_Page::add_query_args_and_nonce(
910
+							[
911
+							'action'      => 'send_payment_reminder',
912
+							'TXN_ID'      => $this->_transaction->ID(),
913
+							'redirect_to' => 'view_transaction',
914
+							],
915
+							TXN_ADMIN_URL
916
+						),
917
+						esc_html__(' Send Payment Reminder', 'event_espresso'),
918
+						'button button--secondary',
919
+						'dashicons dashicons-email-alt'
920
+					)
921
+					: '';
922
+		}
923
+
924
+		if (
925
+			EE_Registry::instance()->CAP->current_user_can(
926
+				'ee_edit_payments',
927
+				'espresso_transactions_recalculate_line_items'
928
+			)
929
+		) {
930
+			$actions['recalculate_line_items'] = EEH_Template::get_button_or_link(
931
+				EE_Admin_Page::add_query_args_and_nonce(
932
+					[
933
+						'action'      => 'espresso_recalculate_line_items',
934
+						'TXN_ID'      => $this->_transaction->ID(),
935
+						'redirect_to' => 'view_transaction',
936
+					],
937
+					TXN_ADMIN_URL
938
+				),
939
+				esc_html__(' Recalculate Taxes and Total', 'event_espresso'),
940
+				'button button--secondary',
941
+				'dashicons dashicons-update'
942
+			);
943
+		}
944
+
945
+		if (
946
+			$primary_registration instanceof EE_Registration
947
+			&& EEH_MSG_Template::is_mt_active('receipt')
948
+		) {
949
+			$actions['receipt'] = EEH_Template::get_button_or_link(
950
+				$primary_registration->receipt_url(),
951
+				esc_html__('View Receipt', 'event_espresso'),
952
+				'button button--secondary',
953
+				'dashicons dashicons-text-page'
954
+			);
955
+		}
956
+
957
+		if (
958
+			$primary_registration instanceof EE_Registration
959
+			&& EEH_MSG_Template::is_mt_active('invoice')
960
+		) {
961
+			$actions['invoice'] = EEH_Template::get_button_or_link(
962
+				$primary_registration->invoice_url(),
963
+				esc_html__('View Invoice', 'event_espresso'),
964
+				'button button--secondary',
965
+				'dashicons dashicons-media-spreadsheet'
966
+			);
967
+		}
968
+		$actions = array_filter(
969
+			apply_filters('FHEE__Transactions_Admin_Page__getActionButtons__actions', $actions, $transaction)
970
+		);
971
+		if ($actions) {
972
+			$content .= implode('', $actions);
973
+		}
974
+		return $content;
975
+	}
976
+
977
+
978
+	/**
979
+	 * txn_details_meta_box
980
+	 * generates HTML for the Transaction main meta box
981
+	 *
982
+	 * @return void
983
+	 * @throws DomainException
984
+	 * @throws EE_Error
985
+	 * @throws InvalidArgumentException
986
+	 * @throws InvalidDataTypeException
987
+	 * @throws InvalidInterfaceException
988
+	 * @throws RuntimeException
989
+	 * @throws ReflectionException
990
+	 */
991
+	public function txn_details_meta_box()
992
+	{
993
+		$this->_set_transaction_object();
994
+		$this->_template_args['TXN_ID']              = $this->_transaction->ID();
995
+		$this->_template_args['attendee']            =
996
+			$this->_transaction->primary_registration() instanceof EE_Registration
997
+				? $this->_transaction->primary_registration()->attendee()
998
+				: null;
999
+		$this->_template_args['can_edit_payments']   = EE_Registry::instance()->CAP->current_user_can(
1000
+			'ee_edit_payments',
1001
+			'apply_payment_or_refund_from_registration_details'
1002
+		);
1003
+		$this->_template_args['can_delete_payments'] = EE_Registry::instance()->CAP->current_user_can(
1004
+			'ee_delete_payments',
1005
+			'delete_payment_from_registration_details'
1006
+		);
1007
+
1008
+		// get line table
1009
+		EEH_Autoloader::register_line_item_display_autoloaders();
1010
+		$Line_Item_Display                       = new EE_Line_Item_Display(
1011
+			'admin_table',
1012
+			'EE_Admin_Table_Line_Item_Display_Strategy'
1013
+		);
1014
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item(
1015
+			$this->_transaction->total_line_item()
1016
+		);
1017
+		$this->_template_args['REG_code']        =
1018
+			$this->_transaction->primary_registration() instanceof EE_Registration
1019
+				? $this->_transaction->primary_registration()->reg_code()
1020
+				: null;
1021
+		// process taxes
1022
+		$taxes                         = $this->_transaction->line_items([['LIN_type' => EEM_Line_Item::type_tax]]);
1023
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
1024
+
1025
+		$this->_template_args['grand_total']     = EEH_Template::format_currency(
1026
+			$this->_transaction->total(),
1027
+			false,
1028
+			false
1029
+		);
1030
+		$this->_template_args['grand_raw_total'] = $this->_transaction->total();
1031
+		$this->_template_args['TXN_status']      = $this->_transaction->status_ID();
1032
+
1033
+		// process payment details
1034
+		$payments = $this->_transaction->payments();
1035
+		if (! empty($payments)) {
1036
+			$this->_template_args['payments']              = $payments;
1037
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
1038
+		} else {
1039
+			$this->_template_args['payments']              = false;
1040
+			$this->_template_args['existing_reg_payments'] = [];
1041
+		}
1042
+
1043
+		$this->_template_args['edit_payment_url']   = add_query_arg(['action' => 'edit_payment'], TXN_ADMIN_URL);
1044
+		$this->_template_args['delete_payment_url'] = add_query_arg(
1045
+			['action' => 'espresso_delete_payment'],
1046
+			TXN_ADMIN_URL
1047
+		);
1048
+
1049
+		if (isset($txn_details['invoice_number'])) {
1050
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
1051
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__(
1052
+				'Invoice Number',
1053
+				'event_espresso'
1054
+			);
1055
+		}
1056
+
1057
+		$this->_template_args['txn_details']['registration_session']['value'] =
1058
+			$this->_transaction->primary_registration() instanceof EE_Registration
1059
+				? $this->_transaction->primary_registration()->session_ID()
1060
+				: null;
1061
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__(
1062
+			'Registration Session',
1063
+			'event_espresso'
1064
+		);
1065
+
1066
+		$this->_template_args['txn_details']['ip_address']['value'] = $this->_session['ip_address'] ?? '';
1067
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__(
1068
+			'Transaction placed from IP',
1069
+			'event_espresso'
1070
+		);
1071
+
1072
+		$this->_template_args['txn_details']['user_agent']['value'] = $this->_session['user_agent'] ?? '';
1073
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__(
1074
+			'Registrant User Agent',
1075
+			'event_espresso'
1076
+		);
1077
+
1078
+		$reg_steps = '<div class="ee-txn-reg-step-status-steps ee-layout-row">';
1079
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
1080
+			if ($reg_step_status === true) {
1081
+				$reg_steps .= '<div class="ee-status-pill ee-status-bg--success">'
1082
+							  . sprintf(
1083
+								  esc_html__('%1$s : Completed', 'event_espresso'),
1084
+								  ucwords(str_replace('_', ' ', $reg_step))
1085
+							  )
1086
+							  . '</div>';
1087
+			} elseif ($reg_step_status !== false && is_numeric($reg_step_status)) {
1088
+				$reg_steps .= '<div class="ee-status-pill ee-status-bg--attention">'
1089
+							  . sprintf(
1090
+								  esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
1091
+								  ucwords(str_replace('_', ' ', $reg_step)),
1092
+								  date(
1093
+									  get_option('date_format') . ' ' . get_option('time_format'),
1094
+									  $reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1095
+								  )
1096
+							  )
1097
+							  . '</div>';
1098
+			} else {
1099
+				$reg_steps .= '<div class="ee-status-pill ee-status-bg--error">'
1100
+							  . sprintf(
1101
+								  esc_html__('%1$s : Never Initiated', 'event_espresso'),
1102
+								  ucwords(str_replace('_', ' ', $reg_step))
1103
+							  )
1104
+							  . '</div>';
1105
+			}
1106
+		}
1107
+		$reg_steps                                                 .= '</ul>';
1108
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
1109
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__(
1110
+			'Registration Step Progress',
1111
+			'event_espresso'
1112
+		);
1113
+
1114
+
1115
+		$this->_get_registrations_to_apply_payment_to();
1116
+		$this->_get_payment_methods($payments);
1117
+		$this->_get_payment_status_array();
1118
+		$this->_get_reg_status_selection(); // sets up the template args for the reg status array for the transaction.
1119
+
1120
+		$this->_template_args['transaction_form_url']    = add_query_arg(
1121
+			[
1122
+				'action'  => 'edit_transaction',
1123
+				'process' => 'transaction',
1124
+			],
1125
+			TXN_ADMIN_URL
1126
+		);
1127
+		$this->_template_args['apply_payment_form_url']  = add_query_arg(
1128
+			[
1129
+				'page'   => 'espresso_transactions',
1130
+				'action' => 'espresso_apply_payment',
1131
+			],
1132
+			TXN_ADMIN_URL
1133
+		);
1134
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(
1135
+			[
1136
+				'page'   => 'espresso_transactions',
1137
+				'action' => 'espresso_delete_payment',
1138
+			],
1139
+			TXN_ADMIN_URL
1140
+		);
1141
+
1142
+		$this->_template_args['action_buttons'] = $this->getActionButtons($this->_transaction);
1143
+
1144
+		// 'espresso_delete_payment_nonce'
1145
+
1146
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
1147
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1148
+	}
1149
+
1150
+
1151
+	/**
1152
+	 * _get_registration_payment_IDs
1153
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
1154
+	 *
1155
+	 * @access protected
1156
+	 * @param EE_Payment[] $payments
1157
+	 * @return array
1158
+	 * @throws EE_Error
1159
+	 * @throws InvalidArgumentException
1160
+	 * @throws InvalidDataTypeException
1161
+	 * @throws InvalidInterfaceException
1162
+	 * @throws ReflectionException
1163
+	 */
1164
+	protected function _get_registration_payment_IDs($payments = [])
1165
+	{
1166
+		$existing_reg_payments = [];
1167
+		// get all reg payments for these payments
1168
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(
1169
+			[
1170
+				[
1171
+					'PAY_ID' => [
1172
+						'IN',
1173
+						array_keys($payments),
1174
+					],
1175
+				],
1176
+			]
1177
+		);
1178
+		if (! empty($reg_payments)) {
1179
+			foreach ($payments as $payment) {
1180
+				if (! $payment instanceof EE_Payment) {
1181
+					continue;
1182
+				} elseif (! isset($existing_reg_payments[ $payment->ID() ])) {
1183
+					$existing_reg_payments[ $payment->ID() ] = [];
1184
+				}
1185
+				foreach ($reg_payments as $reg_payment) {
1186
+					if (
1187
+						$reg_payment instanceof EE_Registration_Payment
1188
+						&& $reg_payment->payment_ID() === $payment->ID()
1189
+					) {
1190
+						$existing_reg_payments[ $payment->ID() ][] = $reg_payment->registration_ID();
1191
+					}
1192
+				}
1193
+			}
1194
+		}
1195
+
1196
+		return $existing_reg_payments;
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * _get_registrations_to_apply_payment_to
1202
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
1203
+	 * which allows the admin to only apply the payment to the specific registrations
1204
+	 *
1205
+	 * @access protected
1206
+	 * @return void
1207
+	 * @throws EE_Error
1208
+	 * @throws InvalidArgumentException
1209
+	 * @throws InvalidDataTypeException
1210
+	 * @throws InvalidInterfaceException
1211
+	 * @throws ReflectionException
1212
+	 */
1213
+	protected function _get_registrations_to_apply_payment_to()
1214
+	{
1215
+		// we want any registration with an active status (ie: not deleted or cancelled)
1216
+		$query_params                      = [
1217
+			[
1218
+				'STS_ID' => [
1219
+					'IN',
1220
+					[
1221
+						EEM_Registration::status_id_approved,
1222
+						EEM_Registration::status_id_pending_payment,
1223
+						EEM_Registration::status_id_not_approved,
1224
+					],
1225
+				],
1226
+			],
1227
+		];
1228
+		$registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
1229
+			'',
1230
+			'txn-admin-apply-payment-to-registrations-dv',
1231
+			'',
1232
+			'clear: both; margin: 1.5em 0 0; display: none;'
1233
+		);
1234
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
1235
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl striped');
1236
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
1237
+			EEH_HTML::tr(
1238
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
1239
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
1240
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
1241
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
1242
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
1243
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
1244
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
1245
+			)
1246
+		);
1247
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
1248
+		// get registrations for TXN
1249
+		$registrations         = $this->_transaction->registrations($query_params);
1250
+		$existing_reg_payments = $this->_template_args['existing_reg_payments'];
1251
+		foreach ($registrations as $registration) {
1252
+			if ($registration instanceof EE_Registration) {
1253
+				$attendee_name                     = $registration->attendee() instanceof EE_Attendee
1254
+					? $registration->attendee()->full_name()
1255
+					: esc_html__('Unknown Attendee', 'event_espresso');
1256
+				$owing                             = $registration->final_price() - $registration->paid();
1257
+				$taxable                           = $registration->ticket()->taxable()
1258
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
1259
+					: '';
1260
+				$checked                           = empty($existing_reg_payments)
1261
+													 || in_array($registration->ID(), $existing_reg_payments, true)
1262
+					? ' checked'
1263
+					: '';
1264
+				$disabled                          = $registration->final_price() > 0 ? '' : ' disabled';
1265
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
1266
+					EEH_HTML::td($registration->ID()) .
1267
+					EEH_HTML::td($attendee_name) .
1268
+					EEH_HTML::td(
1269
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
1270
+					) .
1271
+					EEH_HTML::td($registration->event_name()) .
1272
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
1273
+					EEH_HTML::td(
1274
+						EEH_Template::format_currency($owing),
1275
+						'',
1276
+						'txn-admin-payment-owing-td jst-cntr'
1277
+					) .
1278
+					EEH_HTML::td(
1279
+						'<input type="checkbox" value="' . $registration->ID()
1280
+						. '" name="txn_admin_payment[registrations]"'
1281
+						. $checked . $disabled . '>',
1282
+						'',
1283
+						'jst-cntr'
1284
+					),
1285
+					'apply-payment-registration-row-' . $registration->ID()
1286
+				);
1287
+			}
1288
+		}
1289
+		$registrations_to_apply_payment_to                         .= EEH_HTML::tbodyx();
1290
+		$registrations_to_apply_payment_to                         .= EEH_HTML::tablex();
1291
+		$registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1292
+		$registrations_to_apply_payment_to                         .= EEH_HTML::p(
1293
+			esc_html__(
1294
+				'The payment will only be applied to the registrations that have a check mark in their corresponding check box. Checkboxes for free registrations have been disabled.',
1295
+				'event_espresso'
1296
+			),
1297
+			'',
1298
+			'clear description'
1299
+		);
1300
+		$registrations_to_apply_payment_to                         .= EEH_HTML::divx();
1301
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1302
+	}
1303
+
1304
+
1305
+	/**
1306
+	 * _get_reg_status_selection
1307
+	 *
1308
+	 * @return void
1309
+	 * @throws EE_Error
1310
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1311
+	 *         instead of events.
1312
+	 * @access protected
1313
+	 */
1314
+	protected function _get_reg_status_selection()
1315
+	{
1316
+		// first get all possible statuses
1317
+		$statuses = EEM_Registration::reg_status_array([], true);
1318
+		// let's add a "don't change" option.
1319
+		$status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
1320
+		$status_array                                        = array_merge($status_array, $statuses);
1321
+		$this->_template_args['status_change_select']        = EEH_Form_Fields::select_input(
1322
+			'txn_reg_status_change[reg_status]',
1323
+			$status_array,
1324
+			'NAN',
1325
+			'id="txn-admin-payment-reg-status-inp"',
1326
+			'txn-reg-status-change-reg-status'
1327
+		);
1328
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input(
1329
+			'delete_txn_reg_status_change[reg_status]',
1330
+			$status_array,
1331
+			'NAN',
1332
+			'delete-txn-admin-payment-reg-status-inp',
1333
+			'delete-txn-reg-status-change-reg-status'
1334
+		);
1335
+	}
1336
+
1337
+
1338
+	/**
1339
+	 *    _get_payment_methods
1340
+	 * Gets all the payment methods available generally, or the ones that are already
1341
+	 * selected on these payments (in case their payment methods are no longer active).
1342
+	 * Has the side-effect of updating the template args' payment_methods item
1343
+	 *
1344
+	 * @access private
1345
+	 * @param EE_Payment[] to show on this page
1346
+	 * @return void
1347
+	 * @throws EE_Error
1348
+	 * @throws InvalidArgumentException
1349
+	 * @throws InvalidDataTypeException
1350
+	 * @throws InvalidInterfaceException
1351
+	 * @throws ReflectionException
1352
+	 */
1353
+	private function _get_payment_methods($payments = [])
1354
+	{
1355
+		$payment_methods_of_payments = [];
1356
+		foreach ($payments as $payment) {
1357
+			if ($payment instanceof EE_Payment) {
1358
+				$payment_methods_of_payments[] = $payment->ID();
1359
+			}
1360
+		}
1361
+		if ($payment_methods_of_payments) {
1362
+			$query_args = [
1363
+				[
1364
+					'OR*payment_method_for_payment' => [
1365
+						'PMD_ID'    => ['IN', $payment_methods_of_payments],
1366
+						'PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%'],
1367
+					],
1368
+				],
1369
+			];
1370
+		} else {
1371
+			$query_args = [['PMD_scope' => ['LIKE', '%' . EEM_Payment_Method::scope_admin . '%']]];
1372
+		}
1373
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1374
+	}
1375
+
1376
+
1377
+	/**
1378
+	 * txn_attendees_meta_box
1379
+	 *    generates HTML for the Attendees Transaction main meta box
1380
+	 *
1381
+	 * @access public
1382
+	 * @param WP_Post $post
1383
+	 * @param array   $metabox
1384
+	 * @return void
1385
+	 * @throws DomainException
1386
+	 * @throws EE_Error
1387
+	 * @throws InvalidArgumentException
1388
+	 * @throws InvalidDataTypeException
1389
+	 * @throws InvalidInterfaceException
1390
+	 * @throws ReflectionException
1391
+	 */
1392
+	public function txn_attendees_meta_box($post, $metabox = ['args' => []])
1393
+	{
1394
+
1395
+		/** @noinspection NonSecureExtractUsageInspection */
1396
+		extract($metabox['args']);
1397
+		$this->_template_args['post']            = $post;
1398
+		$this->_template_args['event_attendees'] = [];
1399
+		// process items in cart
1400
+		$line_items = $this->_transaction->get_many_related(
1401
+			'Line_Item',
1402
+			[['LIN_type' => 'line-item']]
1403
+		);
1404
+		if (! empty($line_items)) {
1405
+			foreach ($line_items as $item) {
1406
+				if ($item instanceof EE_Line_Item) {
1407
+					switch ($item->OBJ_type()) {
1408
+						case 'Event':
1409
+							break;
1410
+						case 'Ticket':
1411
+							$ticket = $item->ticket();
1412
+							// right now we're only handling tickets here.
1413
+							// Cause its expected that only tickets will have attendees right?
1414
+							if (! $ticket instanceof EE_Ticket) {
1415
+								break;
1416
+							}
1417
+							try {
1418
+								$event_name = $ticket->get_event_name();
1419
+							} catch (Exception $e) {
1420
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1421
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1422
+							}
1423
+							$event_name   .= ' - ' . $item->name();
1424
+							$ticket_price = EEH_Template::format_currency($item->unit_price());
1425
+							// now get all of the registrations for this transaction that use this ticket
1426
+							$registrations = $ticket->registrations(
1427
+								[['TXN_ID' => $this->_transaction->ID()]]
1428
+							);
1429
+							foreach ($registrations as $registration) {
1430
+								if (! $registration instanceof EE_Registration) {
1431
+									break;
1432
+								}
1433
+								$this->_template_args['event_attendees'][ $registration->ID() ]['STS_ID']
1434
+									= $registration->status_ID();
1435
+								$this->_template_args['event_attendees'][ $registration->ID() ]['att_num']
1436
+									= $registration->count();
1437
+								$this->_template_args['event_attendees'][ $registration->ID() ]['event_ticket_name']
1438
+									= $event_name;
1439
+								$this->_template_args['event_attendees'][ $registration->ID() ]['ticket_price']
1440
+									= $ticket_price;
1441
+								// attendee info
1442
+								$attendee = $registration->get_first_related('Attendee');
1443
+								if ($attendee instanceof EE_Attendee) {
1444
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']
1445
+										= $attendee->ID();
1446
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee']
1447
+										= $attendee->full_name();
1448
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']
1449
+										= '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name
1450
+										  . esc_html__(
1451
+											  ' Event',
1452
+											  'event_espresso'
1453
+										  )
1454
+										  . '">' . $attendee->email() . '</a>';
1455
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']
1456
+										= EEH_Address::format($attendee, 'inline', false, false);
1457
+								} else {
1458
+									$this->_template_args['event_attendees'][ $registration->ID() ]['att_id']   = '';
1459
+									$this->_template_args['event_attendees'][ $registration->ID() ]['attendee'] = '';
1460
+									$this->_template_args['event_attendees'][ $registration->ID() ]['email']    = '';
1461
+									$this->_template_args['event_attendees'][ $registration->ID() ]['address']  = '';
1462
+								}
1463
+							}
1464
+							break;
1465
+					}
1466
+				}
1467
+			}
1468
+
1469
+			$this->_template_args['transaction_form_url'] = add_query_arg(
1470
+				[
1471
+					'action'  => 'edit_transaction',
1472
+					'process' => 'attendees',
1473
+				],
1474
+				TXN_ADMIN_URL
1475
+			);
1476
+			echo EEH_Template::display_template(
1477
+				TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1478
+				$this->_template_args,
1479
+				true
1480
+			);
1481
+		} else {
1482
+			printf(
1483
+				esc_html__(
1484
+					'%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1485
+					'event_espresso'
1486
+				),
1487
+				'<p class="important-notice">',
1488
+				'</p>'
1489
+			);
1490
+		}
1491
+	}
1492
+
1493
+
1494
+	/**
1495
+	 * txn_registrant_side_meta_box
1496
+	 * generates HTML for the Edit Transaction side meta box
1497
+	 *
1498
+	 * @access public
1499
+	 * @return void
1500
+	 * @throws DomainException
1501
+	 * @throws EE_Error
1502
+	 * @throws InvalidArgumentException
1503
+	 * @throws InvalidDataTypeException
1504
+	 * @throws InvalidInterfaceException
1505
+	 * @throws ReflectionException
1506
+	 */
1507
+	public function txn_registrant_side_meta_box()
1508
+	{
1509
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration
1510
+			? $this->_transaction->primary_registration()->get_first_related('Attendee')
1511
+			: null;
1512
+		if (! $primary_att instanceof EE_Attendee) {
1513
+			$this->_template_args['no_attendee_message'] = esc_html__(
1514
+				'There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1515
+				'event_espresso'
1516
+			);
1517
+			$primary_att                           = EEM_Attendee::instance()->create_default_object();
1518
+		}
1519
+		$this->_template_args['ATT_ID']            = $primary_att->ID();
1520
+		$this->_template_args['prime_reg_fname']   = $primary_att->fname();
1521
+		$this->_template_args['prime_reg_lname']   = $primary_att->lname();
1522
+		$this->_template_args['prime_reg_email']   = $primary_att->email();
1523
+		$this->_template_args['prime_reg_phone']   = $primary_att->phone();
1524
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(
1525
+			[
1526
+				'action' => 'edit_attendee',
1527
+				'post'   => $primary_att->ID(),
1528
+			],
1529
+			REG_ADMIN_URL
1530
+		);
1531
+		// get formatted address for registrant
1532
+		$formatted_address = EEH_Address::format($primary_att);
1533
+		$formatted_address = $formatted_address !== '<div class="espresso-address-dv"><div></div></div>'
1534
+			? $formatted_address
1535
+			: '';
1536
+		$this->_template_args['formatted_address'] = $formatted_address;
1537
+		echo EEH_Template::display_template(
1538
+			TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1539
+			$this->_template_args,
1540
+			true
1541
+		);
1542
+	}
1543
+
1544
+
1545
+	/**
1546
+	 * txn_billing_info_side_meta_box
1547
+	 *    generates HTML for the Edit Transaction side meta box
1548
+	 *
1549
+	 * @access public
1550
+	 * @return void
1551
+	 * @throws DomainException
1552
+	 * @throws EE_Error
1553
+	 * @throws ReflectionException
1554
+	 */
1555
+	public function txn_billing_info_side_meta_box()
1556
+	{
1557
+
1558
+		$this->_template_args['billing_form']     = $this->_transaction->billing_info();
1559
+		$this->_template_args['billing_form_url'] = add_query_arg(
1560
+			['action' => 'edit_transaction', 'process' => 'billing'],
1561
+			TXN_ADMIN_URL
1562
+		);
1563
+
1564
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1565
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
1566
+	}
1567
+
1568
+
1569
+	/**
1570
+	 * apply_payments_or_refunds
1571
+	 *    registers a payment or refund made towards a transaction
1572
+	 *
1573
+	 * @access public
1574
+	 * @return void
1575
+	 * @throws EE_Error
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws ReflectionException
1578
+	 * @throws RuntimeException
1579
+	 * @throws InvalidDataTypeException
1580
+	 * @throws InvalidInterfaceException
1581
+	 */
1582
+	public function apply_payments_or_refunds()
1583
+	{
1584
+		$valid_data         = $this->_validate_payment_request_data();
1585
+		$has_access         = EE_Registry::instance()->CAP->current_user_can(
1586
+			'ee_edit_payments',
1587
+			'apply_payment_or_refund_from_registration_details'
1588
+		);
1589
+		$TXD_ID = $this->request->getRequestParam('txn_admin_payment[TXN_ID]', 0, 'int');
1590
+		$amount = 0;
1591
+		if (! empty($valid_data) && $has_access) {
1592
+			$PAY_ID = $valid_data['PAY_ID'];
1593
+			// save  the new payment
1594
+			$payment = $this->_create_payment_from_request_data($valid_data);
1595
+			$amount = $payment->amount();
1596
+			// get the TXN for this payment
1597
+			$transaction = $payment->transaction();
1598
+			// verify transaction
1599
+			if ($transaction instanceof EE_Transaction) {
1600
+				// calculate_total_payments_and_update_status
1601
+				$this->_process_transaction_payments($transaction);
1602
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1603
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1604
+				// apply payment to registrations (if applicable)
1605
+				if (! empty($REG_IDs)) {
1606
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1607
+					$this->_maybe_send_notifications();
1608
+					// now process status changes for the same registrations
1609
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1610
+				}
1611
+				$this->_maybe_send_notifications($payment);
1612
+				// prepare to render page
1613
+				do_action(
1614
+					'AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording',
1615
+					$transaction,
1616
+					$payment
1617
+				);
1618
+			} else {
1619
+				EE_Error::add_error(
1620
+					esc_html__(
1621
+						'A valid Transaction for this payment could not be retrieved.',
1622
+						'event_espresso'
1623
+					),
1624
+					__FILE__,
1625
+					__FUNCTION__,
1626
+					__LINE__
1627
+				);
1628
+			}
1629
+		} elseif ($has_access) {
1630
+			EE_Error::add_error(
1631
+				esc_html__(
1632
+					'The payment form data could not be processed. Please try again.',
1633
+					'event_espresso'
1634
+				),
1635
+				__FILE__,
1636
+				__FUNCTION__,
1637
+				__LINE__
1638
+			);
1639
+		} else {
1640
+			EE_Error::add_error(
1641
+				esc_html__(
1642
+					'You do not have access to apply payments or refunds to a registration.',
1643
+					'event_espresso'
1644
+				),
1645
+				__FILE__,
1646
+				__FUNCTION__,
1647
+				__LINE__
1648
+			);
1649
+		}
1650
+		$query_args = [
1651
+			'page' => 'espresso_transactions',
1652
+			 'action' => 'view_transaction',
1653
+			 'TXN_ID' => $TXD_ID
1654
+		];
1655
+
1656
+		$this->_redirect_after_action(
1657
+			! EE_Error::has_error(),
1658
+			$amount > 0
1659
+				? esc_html__('payment', 'event_espresso')
1660
+				: esc_html__('refund', 'event_espresso'),
1661
+			esc_html__('processed', 'event_espresso'),
1662
+			$query_args
1663
+		);
1664
+	}
1665
+
1666
+
1667
+	/**
1668
+	 * _validate_payment_request_data
1669
+	 *
1670
+	 * @return array
1671
+	 * @throws EE_Error
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidDataTypeException
1674
+	 * @throws InvalidInterfaceException
1675
+	 */
1676
+	protected function _validate_payment_request_data()
1677
+	{
1678
+		if (! $this->request->requestParamIsSet('txn_admin_payment')) {
1679
+			return [];
1680
+		}
1681
+		$payment_form = $this->_generate_payment_form_section();
1682
+		try {
1683
+			if ($payment_form->was_submitted()) {
1684
+				$payment_form->receive_form_submission();
1685
+				if (! $payment_form->is_valid()) {
1686
+					$submission_error_messages = [];
1687
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1688
+						if ($validation_error instanceof EE_Validation_Error) {
1689
+							$form_input = $validation_error->get_form_section();
1690
+							$submission_error_messages[] = sprintf(
1691
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1692
+								$form_input instanceof EE_Form_Input_Base ? $form_input->html_label_text() : '',
1693
+								$validation_error->getMessage()
1694
+							);
1695
+						}
1696
+					}
1697
+					EE_Error::add_error(
1698
+						implode('<br />', $submission_error_messages),
1699
+						__FILE__,
1700
+						__FUNCTION__,
1701
+						__LINE__
1702
+					);
1703
+					return [];
1704
+				}
1705
+			}
1706
+		} catch (EE_Error $e) {
1707
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1708
+			return [];
1709
+		}
1710
+
1711
+		return $payment_form->valid_data();
1712
+	}
1713
+
1714
+
1715
+	/**
1716
+	 * _generate_payment_form_section
1717
+	 *
1718
+	 * @return EE_Form_Section_Proper
1719
+	 * @throws EE_Error
1720
+	 */
1721
+	protected function _generate_payment_form_section()
1722
+	{
1723
+		return new EE_Form_Section_Proper(
1724
+			[
1725
+				'name'        => 'txn_admin_payment',
1726
+				'subsections' => [
1727
+					'PAY_ID'          => new EE_Text_Input(
1728
+						[
1729
+							'default'               => 0,
1730
+							'required'              => false,
1731
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1732
+							'validation_strategies' => [new EE_Int_Normalization()],
1733
+						]
1734
+					),
1735
+					'TXN_ID'          => new EE_Text_Input(
1736
+						[
1737
+							'default'               => 0,
1738
+							'required'              => true,
1739
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1740
+							'validation_strategies' => [new EE_Int_Normalization()],
1741
+						]
1742
+					),
1743
+					'type'            => new EE_Text_Input(
1744
+						[
1745
+							'default'               => 1,
1746
+							'required'              => true,
1747
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1748
+							'validation_strategies' => [new EE_Int_Normalization()],
1749
+						]
1750
+					),
1751
+					'amount'          => new EE_Text_Input(
1752
+						[
1753
+							'default'               => 0,
1754
+							'required'              => true,
1755
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1756
+							'validation_strategies' => [new EE_Float_Normalization()],
1757
+						]
1758
+					),
1759
+					'status'          => new EE_Text_Input(
1760
+						[
1761
+							'default'         => EEM_Payment::status_id_approved,
1762
+							'required'        => true,
1763
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1764
+						]
1765
+					),
1766
+					'PMD_ID'          => new EE_Text_Input(
1767
+						[
1768
+							'default'               => 2,
1769
+							'required'              => true,
1770
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1771
+							'validation_strategies' => [new EE_Int_Normalization()],
1772
+						]
1773
+					),
1774
+					'date'            => new EE_Text_Input(
1775
+						[
1776
+							'default'         => time(),
1777
+							'required'        => true,
1778
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1779
+						]
1780
+					),
1781
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1782
+						[
1783
+							'default'               => '',
1784
+							'required'              => false,
1785
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1786
+							'validation_strategies' => [
1787
+								new EE_Max_Length_Validation_Strategy(
1788
+									esc_html__('Input too long', 'event_espresso'),
1789
+									100
1790
+								),
1791
+							],
1792
+						]
1793
+					),
1794
+					'po_number'       => new EE_Text_Input(
1795
+						[
1796
+							'default'               => '',
1797
+							'required'              => false,
1798
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1799
+							'validation_strategies' => [
1800
+								new EE_Max_Length_Validation_Strategy(
1801
+									esc_html__('Input too long', 'event_espresso'),
1802
+									100
1803
+								),
1804
+							],
1805
+						]
1806
+					),
1807
+					'accounting'      => new EE_Text_Input(
1808
+						[
1809
+							'default'               => '',
1810
+							'required'              => false,
1811
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1812
+							'validation_strategies' => [
1813
+								new EE_Max_Length_Validation_Strategy(
1814
+									esc_html__('Input too long', 'event_espresso'),
1815
+									100
1816
+								),
1817
+							],
1818
+						]
1819
+					),
1820
+				],
1821
+			]
1822
+		);
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 * _create_payment_from_request_data
1828
+	 *
1829
+	 * @param array $valid_data
1830
+	 * @return EE_Payment
1831
+	 * @throws EE_Error
1832
+	 * @throws InvalidArgumentException
1833
+	 * @throws InvalidDataTypeException
1834
+	 * @throws InvalidInterfaceException
1835
+	 * @throws ReflectionException
1836
+	 */
1837
+	protected function _create_payment_from_request_data($valid_data)
1838
+	{
1839
+		$PAY_ID = $valid_data['PAY_ID'];
1840
+		// get payment amount
1841
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1842
+		// payments have a type value of 1 and refunds have a type value of -1
1843
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1844
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1845
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1846
+		$date    = $valid_data['date']
1847
+			? preg_replace('/\s+/', ' ', $valid_data['date'])
1848
+			: date('Y-m-d g:i a', current_time('timestamp'));
1849
+		$payment = EE_Payment::new_instance(
1850
+			[
1851
+				'TXN_ID'              => $valid_data['TXN_ID'],
1852
+				'STS_ID'              => $valid_data['status'],
1853
+				'PAY_timestamp'       => $date,
1854
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1855
+				'PMD_ID'              => $valid_data['PMD_ID'],
1856
+				'PAY_amount'          => $amount,
1857
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1858
+				'PAY_po_number'       => $valid_data['po_number'],
1859
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1860
+				'PAY_details'         => $valid_data,
1861
+				'PAY_ID'              => $PAY_ID,
1862
+			],
1863
+			'',
1864
+			['Y-m-d', 'g:i a']
1865
+		);
1866
+
1867
+		if (! $payment->save()) {
1868
+			EE_Error::add_error(
1869
+				sprintf(
1870
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1871
+					$payment->ID()
1872
+				),
1873
+				__FILE__,
1874
+				__FUNCTION__,
1875
+				__LINE__
1876
+			);
1877
+		}
1878
+
1879
+		return $payment;
1880
+	}
1881
+
1882
+
1883
+	/**
1884
+	 * _process_transaction_payments
1885
+	 *
1886
+	 * @param EE_Transaction $transaction
1887
+	 * @return void
1888
+	 * @throws EE_Error
1889
+	 * @throws InvalidArgumentException
1890
+	 * @throws ReflectionException
1891
+	 * @throws InvalidDataTypeException
1892
+	 * @throws InvalidInterfaceException
1893
+	 */
1894
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1895
+	{
1896
+		/** @type EE_Transaction_Payments $transaction_payments */
1897
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1898
+		// update the transaction with this payment
1899
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1900
+			EE_Error::add_success(
1901
+				esc_html__(
1902
+					'The payment has been processed successfully.',
1903
+					'event_espresso'
1904
+				),
1905
+				__FILE__,
1906
+				__FUNCTION__,
1907
+				__LINE__
1908
+			);
1909
+		} else {
1910
+			EE_Error::add_error(
1911
+				esc_html__(
1912
+					'The payment was processed successfully but the amount paid for the transaction was not updated.',
1913
+					'event_espresso'
1914
+				),
1915
+				__FILE__,
1916
+				__FUNCTION__,
1917
+				__LINE__
1918
+			);
1919
+		}
1920
+	}
1921
+
1922
+
1923
+	/**
1924
+	 * _get_REG_IDs_to_apply_payment_to
1925
+	 * returns a list of registration IDs that the payment will apply to
1926
+	 *
1927
+	 * @param EE_Payment $payment
1928
+	 * @return array
1929
+	 * @throws EE_Error
1930
+	 * @throws InvalidArgumentException
1931
+	 * @throws InvalidDataTypeException
1932
+	 * @throws InvalidInterfaceException
1933
+	 * @throws ReflectionException
1934
+	 */
1935
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1936
+	{
1937
+		// grab array of IDs for specific registrations to apply changes to
1938
+		$apply_to_all = $this->request->getRequestParam(
1939
+			'txn_admin_payment[apply_to_all_registrations]',
1940
+			false,
1941
+			DataType::BOOL
1942
+		);
1943
+		$REG_IDs = ! $apply_to_all
1944
+			? $this->request->getRequestParam(
1945
+				'txn_admin_payment[registrations]',
1946
+				[],
1947
+				DataType::INT,
1948
+				true
1949
+			)
1950
+			: [];
1951
+		// nothing specified ? then get all reg IDs
1952
+		if ($apply_to_all || empty($REG_IDs)) {
1953
+			$registrations = $payment->transaction()->registrations();
1954
+			$REG_IDs       = ! empty($registrations)
1955
+				? array_keys($registrations)
1956
+				: $this->_get_existing_reg_payment_REG_IDs($payment);
1957
+		}
1958
+		// ensure that REG_IDs are integers and NOT strings
1959
+		return array_map('absint', $REG_IDs);
1960
+	}
1961
+
1962
+
1963
+	/**
1964
+	 * @return array
1965
+	 */
1966
+	public function existing_reg_payment_REG_IDs()
1967
+	{
1968
+		return $this->_existing_reg_payment_REG_IDs;
1969
+	}
1970
+
1971
+
1972
+	/**
1973
+	 * @param array $existing_reg_payment_REG_IDs
1974
+	 */
1975
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1976
+	{
1977
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1978
+	}
1979
+
1980
+
1981
+	/**
1982
+	 * _get_existing_reg_payment_REG_IDs
1983
+	 * returns a list of registration IDs that the payment is currently related to
1984
+	 * as recorded in the database
1985
+	 *
1986
+	 * @param EE_Payment $payment
1987
+	 * @return array
1988
+	 * @throws EE_Error
1989
+	 * @throws InvalidArgumentException
1990
+	 * @throws InvalidDataTypeException
1991
+	 * @throws InvalidInterfaceException
1992
+	 * @throws ReflectionException
1993
+	 */
1994
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1995
+	{
1996
+		if ($this->existing_reg_payment_REG_IDs() === null) {
1997
+			// let's get any existing reg payment records for this payment
1998
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1999
+			// but we only want the REG IDs, so grab the array keys
2000
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs)
2001
+				? array_keys($existing_reg_payment_REG_IDs)
2002
+				: [];
2003
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
2004
+		}
2005
+
2006
+		return $this->existing_reg_payment_REG_IDs();
2007
+	}
2008
+
2009
+
2010
+	/**
2011
+	 * _remove_existing_registration_payments
2012
+	 * this calculates the difference between existing relations
2013
+	 * to the supplied payment and the new list registration IDs,
2014
+	 * removes any related registrations that no longer apply,
2015
+	 * and then updates the registration paid fields
2016
+	 *
2017
+	 * @param EE_Payment $payment
2018
+	 * @param int        $PAY_ID
2019
+	 * @return bool;
2020
+	 * @throws EE_Error
2021
+	 * @throws InvalidArgumentException
2022
+	 * @throws ReflectionException
2023
+	 * @throws InvalidDataTypeException
2024
+	 * @throws InvalidInterfaceException
2025
+	 */
2026
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
2027
+	{
2028
+		// newly created payments will have nothing recorded for $PAY_ID
2029
+		if (absint($PAY_ID) === 0) {
2030
+			return false;
2031
+		}
2032
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2033
+		if (empty($existing_reg_payment_REG_IDs)) {
2034
+			return false;
2035
+		}
2036
+		/** @type EE_Transaction_Payments $transaction_payments */
2037
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2038
+
2039
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
2040
+			$payment,
2041
+			[
2042
+				[
2043
+					'PAY_ID' => $payment->ID(),
2044
+					'REG_ID' => ['IN', $existing_reg_payment_REG_IDs],
2045
+				],
2046
+			]
2047
+		);
2048
+	}
2049
+
2050
+
2051
+	/**
2052
+	 * _update_registration_payments
2053
+	 * this applies the payments to the selected registrations
2054
+	 * but only if they have not already been paid for
2055
+	 *
2056
+	 * @param EE_Transaction $transaction
2057
+	 * @param EE_Payment     $payment
2058
+	 * @param array          $REG_IDs
2059
+	 * @return void
2060
+	 * @throws EE_Error
2061
+	 * @throws InvalidArgumentException
2062
+	 * @throws ReflectionException
2063
+	 * @throws RuntimeException
2064
+	 * @throws InvalidDataTypeException
2065
+	 * @throws InvalidInterfaceException
2066
+	 */
2067
+	protected function _update_registration_payments(
2068
+		EE_Transaction $transaction,
2069
+		EE_Payment $payment,
2070
+		$REG_IDs = []
2071
+	) {
2072
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
2073
+		// so let's do that using our set of REG_IDs from the form
2074
+		$registration_query_where_params = [
2075
+			'REG_ID' => ['IN', $REG_IDs],
2076
+		];
2077
+		// but add in some conditions regarding payment,
2078
+		// so that we don't apply payments to registrations that are free or have already been paid for
2079
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
2080
+		if (! $payment->is_a_refund()) {
2081
+			$registration_query_where_params['REG_final_price']  = ['!=', 0];
2082
+			$registration_query_where_params['REG_final_price*'] = ['!=', 'REG_paid', true];
2083
+		}
2084
+		$registrations = $transaction->registrations([$registration_query_where_params]);
2085
+		if (! empty($registrations)) {
2086
+			/** @type EE_Payment_Processor $payment_processor */
2087
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
2088
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
2089
+		}
2090
+	}
2091
+
2092
+
2093
+	/**
2094
+	 * _process_registration_status_change
2095
+	 * This processes requested registration status changes for all the registrations
2096
+	 * on a given transaction and (optionally) sends out notifications for the changes.
2097
+	 *
2098
+	 * @param EE_Transaction $transaction
2099
+	 * @param array          $REG_IDs
2100
+	 * @return bool
2101
+	 * @throws EE_Error
2102
+	 * @throws InvalidArgumentException
2103
+	 * @throws ReflectionException
2104
+	 * @throws InvalidDataTypeException
2105
+	 * @throws InvalidInterfaceException
2106
+	 */
2107
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = [], $reg_status = '')
2108
+	{
2109
+		// first if there is no change in status then we get out.
2110
+		$reg_status = $reg_status ?: $this->request->getRequestParam('txn_reg_status_change[reg_status]', 'NAN');
2111
+		if ($reg_status === 'NAN') {
2112
+			// no error message, no change requested, just nothing to do man.
2113
+			return false;
2114
+		}
2115
+		/** @type EE_Transaction_Processor $transaction_processor */
2116
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
2117
+
2118
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
2119
+		return $transaction_processor->manually_update_registration_statuses(
2120
+			$transaction,
2121
+			$reg_status,
2122
+			[['REG_ID' => ['IN', $REG_IDs]]]
2123
+		);
2124
+	}
2125
+
2126
+
2127
+	/**
2128
+	 * _build_payment_json_response
2129
+	 *
2130
+	 * @access public
2131
+	 * @param EE_Payment  $payment
2132
+	 * @param array       $REG_IDs
2133
+	 * @param bool | null $delete_txn_reg_status_change
2134
+	 * @return array
2135
+	 * @throws EE_Error
2136
+	 * @throws InvalidArgumentException
2137
+	 * @throws InvalidDataTypeException
2138
+	 * @throws InvalidInterfaceException
2139
+	 * @throws ReflectionException
2140
+	 */
2141
+	protected function _build_payment_json_response(
2142
+		EE_Payment $payment,
2143
+		$REG_IDs = [],
2144
+		$delete_txn_reg_status_change = null
2145
+	) {
2146
+		// was the payment deleted ?
2147
+		if (is_bool($delete_txn_reg_status_change)) {
2148
+			return [
2149
+				'PAY_ID'                       => $payment->ID(),
2150
+				'amount'                       => $payment->amount(),
2151
+				'total_paid'                   => $payment->transaction()->paid(),
2152
+				'txn_status'                   => $payment->transaction()->status_ID(),
2153
+				'pay_status'                   => $payment->STS_ID(),
2154
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
2155
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
2156
+			];
2157
+		}
2158
+
2159
+		$this->_get_payment_status_array();
2160
+		return [
2161
+			'amount'           => $payment->amount(),
2162
+			'total_paid'       => $payment->transaction()->paid(),
2163
+			'txn_status'       => $payment->transaction()->status_ID(),
2164
+			'pay_status'       => $payment->STS_ID(),
2165
+			'PAY_ID'           => $payment->ID(),
2166
+			'STS_ID'           => $payment->STS_ID(),
2167
+			'status'           => self::$_pay_status[ $payment->STS_ID() ],
2168
+			'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
2169
+			'method'           => strtoupper($payment->source()),
2170
+			'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
2171
+			'gateway'          => $payment->payment_method()
2172
+				? $payment->payment_method()->admin_name()
2173
+				: esc_html__('Unknown', 'event_espresso'),
2174
+			'gateway_response' => $payment->gateway_response(),
2175
+			'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
2176
+			'po_number'        => $payment->po_number(),
2177
+			'extra_accntng'    => $payment->extra_accntng(),
2178
+			'registrations'    => $this->_registration_payment_data_array($REG_IDs),
2179
+		];
2180
+	}
2181
+
2182
+
2183
+	/**
2184
+	 * delete_payment
2185
+	 *    delete a payment or refund made towards a transaction
2186
+	 *
2187
+	 * @access public
2188
+	 * @return void
2189
+	 * @throws EE_Error
2190
+	 * @throws InvalidArgumentException
2191
+	 * @throws ReflectionException
2192
+	 * @throws InvalidDataTypeException
2193
+	 * @throws InvalidInterfaceException
2194
+	 */
2195
+	public function delete_payment()
2196
+	{
2197
+		$TXD_ID = $this->request->getRequestParam('delete_txn_admin_payment[TXN_ID]', 0, 'int');
2198
+		// $json_response_data = ['return_data' => false];
2199
+		$PAY_ID = $this->request->getRequestParam('delete_txn_admin_payment[PAY_ID]', 0, 'int');
2200
+		$amount = 0;
2201
+		$can_delete         = EE_Registry::instance()->CAP->current_user_can(
2202
+			'ee_delete_payments',
2203
+			'delete_payment_from_registration_details'
2204
+		);
2205
+		if ($PAY_ID && $can_delete) {
2206
+			$delete_txn_reg_status_change = $this->request->getRequestParam('delete_txn_reg_status_change[reg_status]');
2207
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
2208
+			if ($payment instanceof EE_Payment) {
2209
+				$amount = $payment->amount();
2210
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
2211
+				/** @type EE_Transaction_Payments $transaction_payments */
2212
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
2213
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
2214
+					if ($delete_txn_reg_status_change) {
2215
+						$this->_maybe_send_notifications();
2216
+						$this->_process_registration_status_change(
2217
+							$payment->transaction(),
2218
+							$REG_IDs,
2219
+							$delete_txn_reg_status_change
2220
+						);
2221
+					}
2222
+				}
2223
+			} else {
2224
+				EE_Error::add_error(
2225
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
2226
+					__FILE__,
2227
+					__FUNCTION__,
2228
+					__LINE__
2229
+				);
2230
+			}
2231
+		} elseif ($can_delete) {
2232
+			EE_Error::add_error(
2233
+				esc_html__(
2234
+					'A valid Payment ID was not received, therefore payment form data could not be loaded.',
2235
+					'event_espresso'
2236
+				),
2237
+				__FILE__,
2238
+				__FUNCTION__,
2239
+				__LINE__
2240
+			);
2241
+		} else {
2242
+			EE_Error::add_error(
2243
+				esc_html__(
2244
+					'You do not have access to delete a payment.',
2245
+					'event_espresso'
2246
+				),
2247
+				__FILE__,
2248
+				__FUNCTION__,
2249
+				__LINE__
2250
+			);
2251
+		}
2252
+		$query_args = [
2253
+			'page'   => 'espresso_transactions',
2254
+			'action' => 'view_transaction',
2255
+			'TXN_ID' => $TXD_ID
2256
+		];
2257
+		$this->_redirect_after_action(
2258
+			! EE_Error::has_error(),
2259
+			$amount > 0
2260
+				? esc_html__('payment', 'event_espresso')
2261
+				: esc_html__('refund', 'event_espresso'),
2262
+			esc_html__('deleted', 'event_espresso'),
2263
+			$query_args
2264
+		);
2265
+	}
2266
+
2267
+
2268
+	/**
2269
+	 * _registration_payment_data_array
2270
+	 * adds info for 'owing' and 'paid' for each registration to the json response
2271
+	 *
2272
+	 * @access protected
2273
+	 * @param array $REG_IDs
2274
+	 * @return array
2275
+	 * @throws EE_Error
2276
+	 * @throws InvalidArgumentException
2277
+	 * @throws InvalidDataTypeException
2278
+	 * @throws InvalidInterfaceException
2279
+	 * @throws ReflectionException
2280
+	 */
2281
+	protected function _registration_payment_data_array($REG_IDs)
2282
+	{
2283
+		$registration_payment_data = [];
2284
+		// if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
2285
+		if (! empty($REG_IDs)) {
2286
+			$registrations = EEM_Registration::instance()->get_all([['REG_ID' => ['IN', $REG_IDs]]]);
2287
+			foreach ($registrations as $registration) {
2288
+				if ($registration instanceof EE_Registration) {
2289
+					$registration_payment_data[ $registration->ID() ] = [
2290
+						'paid'  => $registration->pretty_paid(),
2291
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
2292
+					];
2293
+				}
2294
+			}
2295
+		}
2296
+
2297
+		return $registration_payment_data;
2298
+	}
2299
+
2300
+
2301
+	/**
2302
+	 * _maybe_send_notifications
2303
+	 * determines whether or not the admin has indicated that notifications should be sent.
2304
+	 * If so, will toggle a filter switch for delivering registration notices.
2305
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
2306
+	 *
2307
+	 * @access protected
2308
+	 * @param EE_Payment | null $payment
2309
+	 */
2310
+	protected function _maybe_send_notifications($payment = null)
2311
+	{
2312
+		switch ($payment instanceof EE_Payment) {
2313
+			// payment notifications
2314
+			case true:
2315
+				if ($this->request->getRequestParam('txn_payments[send_notifications]', false, 'bool')) {
2316
+					$this->_process_payment_notification($payment);
2317
+				}
2318
+				break;
2319
+			// registration notifications
2320
+			case false:
2321
+				if ($this->request->getRequestParam('txn_reg_status_change[send_notifications]', false, 'bool')) {
2322
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
2323
+				}
2324
+				break;
2325
+		}
2326
+	}
2327
+
2328
+
2329
+	/**
2330
+	 * _send_payment_reminder
2331
+	 *    generates HTML for the View Transaction Details Admin page
2332
+	 *
2333
+	 * @access protected
2334
+	 * @return void
2335
+	 * @throws EE_Error
2336
+	 * @throws InvalidArgumentException
2337
+	 * @throws InvalidDataTypeException
2338
+	 * @throws InvalidInterfaceException
2339
+	 */
2340
+	protected function _send_payment_reminder()
2341
+	{
2342
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2343
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2344
+		$redirect_to = $this->request->getRequestParam('redirect_to');
2345
+		$query_args  = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2346
+		do_action(
2347
+			'AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
2348
+			$transaction
2349
+		);
2350
+		$this->_redirect_after_action(
2351
+			false,
2352
+			esc_html__('payment reminder', 'event_espresso'),
2353
+			esc_html__('sent', 'event_espresso'),
2354
+			$query_args,
2355
+			true
2356
+		);
2357
+	}
2358
+
2359
+
2360
+	/**
2361
+	 *  get_transactions
2362
+	 *    get transactions for given parameters (used by list table)
2363
+	 *
2364
+	 * @param int     $per_page how many transactions displayed per page
2365
+	 * @param boolean $count   return the count or objects
2366
+	 * @param string  $view
2367
+	 * @return EE_Transaction[]|int int = count || array of transaction objects
2368
+	 * @throws EE_Error
2369
+	 * @throws InvalidArgumentException
2370
+	 * @throws InvalidDataTypeException
2371
+	 * @throws InvalidInterfaceException
2372
+	 */
2373
+	public function get_transactions($per_page, $count = false, $view = '')
2374
+	{
2375
+		$start_date = wp_strip_all_tags(
2376
+			$this->request->getRequestParam('txn-filter-start-date', date('m/d/Y', strtotime('-10 year')))
2377
+		);
2378
+		$end_date = wp_strip_all_tags(
2379
+			$this->request->getRequestParam('txn-filter-end-date', date('m/d/Y'))
2380
+		);
2381
+
2382
+		// make sure our timestamps start and end right at the boundaries for each day
2383
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
2384
+		$end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
2385
+
2386
+
2387
+		// convert to timestamps
2388
+		$start_date = strtotime($start_date);
2389
+		$end_date   = strtotime($end_date);
2390
+
2391
+		// makes sure start date is the lowest value and vice versa
2392
+		$start_date = min($start_date, $end_date);
2393
+		$end_date   = max($start_date, $end_date);
2394
+
2395
+		// convert to correct format for query
2396
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query(
2397
+			'TXN_timestamp',
2398
+			date('Y-m-d H:i:s', $start_date),
2399
+			'Y-m-d H:i:s'
2400
+		);
2401
+		$end_date   = EEM_Transaction::instance()->convert_datetime_for_query(
2402
+			'TXN_timestamp',
2403
+			date('Y-m-d H:i:s', $end_date),
2404
+			'Y-m-d H:i:s'
2405
+		);
2406
+
2407
+
2408
+		// set orderby
2409
+		$orderby = $this->request->getRequestParam('orderby');
2410
+
2411
+		switch ($orderby) {
2412
+			case 'TXN_ID':
2413
+				break;
2414
+			case 'ATT_fname':
2415
+				$orderby = 'Registration.Attendee.ATT_fname';
2416
+				break;
2417
+			case 'event_name':
2418
+				$orderby = 'Registration.Event.EVT_name';
2419
+				break;
2420
+			default: // 'TXN_timestamp'
2421
+				$orderby = 'TXN_timestamp';
2422
+		}
2423
+
2424
+		$sort         = $this->request->getRequestParam('order', 'DESC');
2425
+		$current_page = $this->request->getRequestParam('paged', 1, 'int');
2426
+
2427
+		$per_page = absint($per_page) ? $per_page : 10;
2428
+		$per_page = $this->request->getRequestParam('perpage', $per_page, 'int');
2429
+
2430
+		$offset = ($current_page - 1) * $per_page;
2431
+		$limit  = [$offset, $per_page];
2432
+
2433
+		$_where = [
2434
+			'TXN_timestamp'          => ['BETWEEN', [$start_date, $end_date]],
2435
+			'Registration.REG_count' => 1,
2436
+		];
2437
+
2438
+		$EVT_ID = $this->request->getRequestParam('EVT_ID', 0, 'int');
2439
+		if ($EVT_ID) {
2440
+			$_where['Registration.EVT_ID'] = $EVT_ID;
2441
+		}
2442
+
2443
+		$search_term = $this->request->getRequestParam('s');
2444
+		if ($search_term) {
2445
+			$search_term = '%' . $search_term . '%';
2446
+			$_where['OR']  = [
2447
+				'Registration.Event.EVT_name'         => ['LIKE', $search_term],
2448
+				'Registration.Event.EVT_desc'         => ['LIKE', $search_term],
2449
+				'Registration.Event.EVT_short_desc'   => ['LIKE', $search_term],
2450
+				'Registration.Attendee.ATT_full_name' => ['LIKE', $search_term],
2451
+				'Registration.Attendee.ATT_fname'     => ['LIKE', $search_term],
2452
+				'Registration.Attendee.ATT_lname'     => ['LIKE', $search_term],
2453
+				'Registration.Attendee.ATT_short_bio' => ['LIKE', $search_term],
2454
+				'Registration.Attendee.ATT_email'     => ['LIKE', $search_term],
2455
+				'Registration.Attendee.ATT_address'   => ['LIKE', $search_term],
2456
+				'Registration.Attendee.ATT_address2'  => ['LIKE', $search_term],
2457
+				'Registration.Attendee.ATT_city'      => ['LIKE', $search_term],
2458
+				'Registration.REG_final_price'        => ['LIKE', $search_term],
2459
+				'Registration.REG_code'               => ['LIKE', $search_term],
2460
+				'Registration.REG_count'              => ['LIKE', $search_term],
2461
+				'Registration.REG_group_size'         => ['LIKE', $search_term],
2462
+				'Registration.Ticket.TKT_name'        => ['LIKE', $search_term],
2463
+				'Registration.Ticket.TKT_description' => ['LIKE', $search_term],
2464
+				'Payment.PAY_source'                  => ['LIKE', $search_term],
2465
+				'Payment.Payment_Method.PMD_name'     => ['LIKE', $search_term],
2466
+				'TXN_session_data'                    => ['LIKE', $search_term],
2467
+				'Payment.PAY_txn_id_chq_nmbr'         => ['LIKE', $search_term],
2468
+			];
2469
+		}
2470
+
2471
+		$status = $this->request->getRequestParam('status');
2472
+		// failed transactions
2473
+		$failed     = (! empty($status) && $status === 'failed' && ! $count) || ($count && $view === 'failed');
2474
+		$abandoned  = (! empty($status) && $status === 'abandoned' && ! $count) || ($count && $view === 'abandoned');
2475
+		$incomplete = (! empty($status) && $status === 'incomplete' && ! $count) || ($count && $view === 'incomplete');
2476
+
2477
+		if ($failed) {
2478
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
2479
+		} elseif ($abandoned) {
2480
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
2481
+		} elseif ($incomplete) {
2482
+			$_where['STS_ID'] = EEM_Transaction::incomplete_status_code;
2483
+		} else {
2484
+			$_where['STS_ID']  = ['!=', EEM_Transaction::failed_status_code];
2485
+			$_where['STS_ID*'] = ['!=', EEM_Transaction::abandoned_status_code];
2486
+		}
2487
+
2488
+		$query_params = apply_filters(
2489
+			'FHEE__Transactions_Admin_Page___get_transactions_query_params',
2490
+			[
2491
+				$_where,
2492
+				'order_by'                 => [$orderby => $sort],
2493
+				'limit'                    => $limit,
2494
+				'default_where_conditions' => EEM_Base::default_where_conditions_this_only,
2495
+			],
2496
+			$this->request->requestParams(),
2497
+			$view,
2498
+			$count
2499
+		);
2500
+
2501
+		return $count
2502
+			? EEM_Transaction::instance()->count([$query_params[0]], 'TXN_ID', true)
2503
+			: EEM_Transaction::instance()->get_all($query_params);
2504
+	}
2505
+
2506
+
2507
+	/**
2508
+	 * @throws EE_Error
2509
+	 * @throws InvalidArgumentException
2510
+	 * @throws InvalidDataTypeException
2511
+	 * @throws InvalidInterfaceException
2512
+	 * @throws ReflectionException
2513
+	 * @throws RuntimeException
2514
+	 * @since 4.9.79.p
2515
+	 */
2516
+	public function recalculateLineItems()
2517
+	{
2518
+		$TXN_ID = $this->request->getRequestParam('TXN_ID', 0, 'int');
2519
+		/** @var EE_Transaction $transaction */
2520
+		$transaction     = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
2521
+		$success         = $transaction->recalculateLineItems();
2522
+		$redirect_to = $this->request->getRequestParam('redirect_to');
2523
+		$query_args = $redirect_to ? ['action' => $redirect_to, 'TXN_ID' => $TXN_ID,] : [];
2524
+		$this->_redirect_after_action(
2525
+			$success,
2526
+			esc_html__('Transaction taxes and totals', 'event_espresso'),
2527
+			esc_html__('recalculated', 'event_espresso'),
2528
+			$query_args,
2529
+			true
2530
+		);
2531
+	}
2532 2532
 }
Please login to merge, or discard this patch.