Completed
Branch BUG-10738-inconsistency-in-ses... (cda363)
by
unknown
13:38 queued 12s
created
core/EE_Maintenance_Mode.core.php 1 patch
Indentation   +317 added lines, -317 removed lines patch added patch discarded remove patch
@@ -17,362 +17,362 @@
 block discarded – undo
17 17
 class EE_Maintenance_Mode implements ResettableInterface
18 18
 {
19 19
 
20
-    /**
21
-     * constants available to client code for interpreting the values of EE_Maintenance_Mode::level().
22
-     * level_0_not_in_maintenance means the site is NOT in maintenance mode (so everything's normal)
23
-     */
24
-    const level_0_not_in_maintenance = 0;
25
-
26
-    /**
27
-     * level_1_frontend_only_maintenance means that the site's frontend EE code should be completely disabled
28
-     * but the admin backend should be running as normal. Maybe an admin can view the frontend though
29
-     */
30
-    const level_1_frontend_only_maintenance = 1;
31
-
32
-    /**
33
-     * level_2_complete_maintenance means the frontend AND EE backend code are disabled. The only system running
34
-     * is the maintenance mode stuff, which will require users to update all addons, and then finish running all
35
-     * migration scripts before taking the site out of maintenance mode
36
-     */
37
-    const level_2_complete_maintenance = 2;
38
-
39
-    /**
40
-     * the name of the option which stores the current level of maintenance mode
41
-     */
42
-    const option_name_maintenance_mode = 'ee_maintenance_mode';
43
-
44
-
45
-    /**
46
-     * @var EE_Maintenance_Mode $_instance
47
-     */
48
-    private static $_instance;
49
-
50
-    /**
51
-     * @var EE_Registry $EE
52
-     */
53
-    protected $EE;
54
-
55
-
56
-
57
-    /**
58
-     * @singleton method used to instantiate class object
59
-     * @return EE_Maintenance_Mode
60
-     */
61
-    public static function instance()
62
-    {
63
-        // check if class object is instantiated
64
-        if (! self::$_instance instanceof EE_Maintenance_Mode) {
65
-            self::$_instance = new self();
66
-        }
67
-        return self::$_instance;
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * Resets maintenance mode (mostly just re-checks whether or not we should be in maintenance mode)
74
-     *
75
-     * @return EE_Maintenance_Mode
76
-     */
77
-    public static function reset()
78
-    {
79
-        self::instance()->set_maintenance_mode_if_db_old();
80
-        return self::instance();
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     *private constructor to prevent direct creation
87
-     */
88
-    private function __construct()
89
-    {
90
-        // if M-Mode level 2 is engaged, we still need basic assets loaded
91
-        add_action('wp_enqueue_scripts', array($this, 'load_assets_required_for_m_mode'));
92
-        // shut 'er down down for maintenance ?
93
-        add_filter('the_content', array($this, 'the_content'), 2);
94
-        // add powered by EE msg
95
-        add_action('shutdown', array($this, 'display_maintenance_mode_notice'), 10);
96
-    }
97
-
98
-
99
-
100
-    /**
101
-     * retrieves the maintenance mode option value from the db
102
-     *
103
-     * @return int
104
-     */
105
-    public function real_level()
106
-    {
107
-        return (int) get_option(self::option_name_maintenance_mode, EE_Maintenance_Mode::level_0_not_in_maintenance);
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Returns whether or not the models reportedly are able to run queries or not
114
-     * (ie, if the system thinks their tables are present and up-to-date).
115
-     *
116
-     * @return boolean
117
-     */
118
-    public function models_can_query()
119
-    {
120
-        return $this->real_level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * Determines whether or not we're in maintenance mode and what level. However, while the site
127
-     * is in level 1 maintenance, and an admin visits the frontend, this function makes it appear
128
-     * to them as if teh site isn't in maintenance mode.
129
-     * EE_Maintenance_Mode::level_0_not_in_maintenance => not in maintenance mode (in normal mode)
130
-     * EE_Maintenance_Mode::level_1_frontend_only_maintenance=> frontend-only maintenance mode
131
-     * EE_Maintenance_Mode::level_2_complete_maintenance => frontend and backend maintenance mode
132
-     *
133
-     * @return int
134
-     */
135
-    public function level()
136
-    {
137
-        $maintenance_mode_level = $this->real_level();
138
-        // if this is an admin request, we'll be honest... except if it's ajax, because that might be from the frontend
139
-        if (
140
-            $maintenance_mode_level === EE_Maintenance_Mode::level_1_frontend_only_maintenance// we're in level 1
141
-            && ((defined('DOING_AJAX') && DOING_AJAX) || ! is_admin()) // on non-ajax frontend requests
142
-            && current_user_can('administrator') // when the user is an admin
143
-        ) {
144
-            $maintenance_mode_level = EE_Maintenance_Mode::level_0_not_in_maintenance;
145
-        }
146
-        return $maintenance_mode_level;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * Determines if we need to put EE in maintenance mode because the database needs updating
153
-     *
154
-     * @return boolean true if DB is old and maintenance mode was triggered; false otherwise
155
-     */
156
-    public function set_maintenance_mode_if_db_old()
157
-    {
158
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
159
-        if (EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
160
-            update_option(self::option_name_maintenance_mode, self::level_2_complete_maintenance);
161
-            return true;
162
-        }
163
-        if ($this->level() === self::level_2_complete_maintenance) {
164
-            //we also want to handle the opposite: if the site is mm2, but there aren't any migrations to run
165
-            //then we shouldn't be in mm2. (Maybe an addon got deactivated?)
166
-            update_option(self::option_name_maintenance_mode, self::level_0_not_in_maintenance);
167
-            return false;
168
-        }
169
-        return false;
170
-    }
171
-
172
-
173
-
174
-    /**
175
-     * Updates the maintenance level on the site
176
-     *
177
-     * @param int $level
178
-     * @return void
179
-     */
180
-    public function set_maintenance_level($level)
181
-    {
182
-        do_action('AHEE__EE_Maintenance_Mode__set_maintenance_level', $level);
183
-        update_option(self::option_name_maintenance_mode, (int)$level);
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * returns TRUE if M-Mode is engaged and the current request is not for the admin
190
-     *
191
-     * @return    string
192
-     */
193
-    public static function disable_frontend_for_maintenance()
194
-    {
195
-        return (! is_admin() && EE_Maintenance_Mode::instance()->level());
196
-    }
197
-
198
-
199
-
200
-    /**
201
-     * @return void
202
-     */
203
-    public function load_assets_required_for_m_mode()
204
-    {
205
-        if (
206
-            $this->real_level() === EE_Maintenance_Mode::level_2_complete_maintenance
207
-            && ! wp_script_is('espresso_core')
208
-        ) {
209
-            wp_register_style(
210
-                'espresso_default',
211
-                EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
212
-                array('dashicons'),
213
-                EVENT_ESPRESSO_VERSION
214
-            );
215
-            wp_enqueue_style('espresso_default');
216
-            wp_register_script(
217
-                'espresso_core',
218
-                EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
219
-                array('jquery'),
220
-                EVENT_ESPRESSO_VERSION,
221
-                true
222
-            );
223
-            wp_enqueue_script('espresso_core');
224
-        }
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * replacement EE CPT template that displays message notifying site visitors
231
-     * that EE has been temporarily placed into maintenance mode
232
-     * does NOT get called on non-EE-CPT requests
233
-     *
234
-     * @return    string
235
-     */
236
-    public static function template_include()
237
-    {
238
-        // shut 'er down down for maintenance ? then don't use any of our templates for our endpoints
239
-        return get_template_directory() . '/index.php';
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * displays message notifying site visitors that EE has been temporarily
246
-     * placed into maintenance mode when post_type != EE CPT
247
-     *
248
-     * @param string $the_content
249
-     * @return string
250
-     */
251
-    public function the_content($the_content)
252
-    {
253
-        // check if M-mode is engaged and for EE shortcode
254
-        if ($this->level() && strpos($the_content, '[ESPRESSO_') !== false) {
255
-            // this can eventually be moved to a template, or edited via admin. But for now...
256
-            $the_content = sprintf(
257
-                esc_html__(
258
-                    '%sMaintenance Mode%sEvent Registration has been temporarily closed while system maintenance is being performed. We\'re sorry for any inconveniences this may have caused. Please try back again later.%s',
259
-                    'event_espresso'
260
-                ),
261
-                '<h3>',
262
-                '</h3><p>',
263
-                '</p>'
264
-            );
265
-        }
266
-        return $the_content;
267
-    }
20
+	/**
21
+	 * constants available to client code for interpreting the values of EE_Maintenance_Mode::level().
22
+	 * level_0_not_in_maintenance means the site is NOT in maintenance mode (so everything's normal)
23
+	 */
24
+	const level_0_not_in_maintenance = 0;
25
+
26
+	/**
27
+	 * level_1_frontend_only_maintenance means that the site's frontend EE code should be completely disabled
28
+	 * but the admin backend should be running as normal. Maybe an admin can view the frontend though
29
+	 */
30
+	const level_1_frontend_only_maintenance = 1;
31
+
32
+	/**
33
+	 * level_2_complete_maintenance means the frontend AND EE backend code are disabled. The only system running
34
+	 * is the maintenance mode stuff, which will require users to update all addons, and then finish running all
35
+	 * migration scripts before taking the site out of maintenance mode
36
+	 */
37
+	const level_2_complete_maintenance = 2;
38
+
39
+	/**
40
+	 * the name of the option which stores the current level of maintenance mode
41
+	 */
42
+	const option_name_maintenance_mode = 'ee_maintenance_mode';
43
+
44
+
45
+	/**
46
+	 * @var EE_Maintenance_Mode $_instance
47
+	 */
48
+	private static $_instance;
49
+
50
+	/**
51
+	 * @var EE_Registry $EE
52
+	 */
53
+	protected $EE;
54
+
55
+
56
+
57
+	/**
58
+	 * @singleton method used to instantiate class object
59
+	 * @return EE_Maintenance_Mode
60
+	 */
61
+	public static function instance()
62
+	{
63
+		// check if class object is instantiated
64
+		if (! self::$_instance instanceof EE_Maintenance_Mode) {
65
+			self::$_instance = new self();
66
+		}
67
+		return self::$_instance;
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * Resets maintenance mode (mostly just re-checks whether or not we should be in maintenance mode)
74
+	 *
75
+	 * @return EE_Maintenance_Mode
76
+	 */
77
+	public static function reset()
78
+	{
79
+		self::instance()->set_maintenance_mode_if_db_old();
80
+		return self::instance();
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 *private constructor to prevent direct creation
87
+	 */
88
+	private function __construct()
89
+	{
90
+		// if M-Mode level 2 is engaged, we still need basic assets loaded
91
+		add_action('wp_enqueue_scripts', array($this, 'load_assets_required_for_m_mode'));
92
+		// shut 'er down down for maintenance ?
93
+		add_filter('the_content', array($this, 'the_content'), 2);
94
+		// add powered by EE msg
95
+		add_action('shutdown', array($this, 'display_maintenance_mode_notice'), 10);
96
+	}
97
+
98
+
99
+
100
+	/**
101
+	 * retrieves the maintenance mode option value from the db
102
+	 *
103
+	 * @return int
104
+	 */
105
+	public function real_level()
106
+	{
107
+		return (int) get_option(self::option_name_maintenance_mode, EE_Maintenance_Mode::level_0_not_in_maintenance);
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Returns whether or not the models reportedly are able to run queries or not
114
+	 * (ie, if the system thinks their tables are present and up-to-date).
115
+	 *
116
+	 * @return boolean
117
+	 */
118
+	public function models_can_query()
119
+	{
120
+		return $this->real_level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * Determines whether or not we're in maintenance mode and what level. However, while the site
127
+	 * is in level 1 maintenance, and an admin visits the frontend, this function makes it appear
128
+	 * to them as if teh site isn't in maintenance mode.
129
+	 * EE_Maintenance_Mode::level_0_not_in_maintenance => not in maintenance mode (in normal mode)
130
+	 * EE_Maintenance_Mode::level_1_frontend_only_maintenance=> frontend-only maintenance mode
131
+	 * EE_Maintenance_Mode::level_2_complete_maintenance => frontend and backend maintenance mode
132
+	 *
133
+	 * @return int
134
+	 */
135
+	public function level()
136
+	{
137
+		$maintenance_mode_level = $this->real_level();
138
+		// if this is an admin request, we'll be honest... except if it's ajax, because that might be from the frontend
139
+		if (
140
+			$maintenance_mode_level === EE_Maintenance_Mode::level_1_frontend_only_maintenance// we're in level 1
141
+			&& ((defined('DOING_AJAX') && DOING_AJAX) || ! is_admin()) // on non-ajax frontend requests
142
+			&& current_user_can('administrator') // when the user is an admin
143
+		) {
144
+			$maintenance_mode_level = EE_Maintenance_Mode::level_0_not_in_maintenance;
145
+		}
146
+		return $maintenance_mode_level;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * Determines if we need to put EE in maintenance mode because the database needs updating
153
+	 *
154
+	 * @return boolean true if DB is old and maintenance mode was triggered; false otherwise
155
+	 */
156
+	public function set_maintenance_mode_if_db_old()
157
+	{
158
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
159
+		if (EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
160
+			update_option(self::option_name_maintenance_mode, self::level_2_complete_maintenance);
161
+			return true;
162
+		}
163
+		if ($this->level() === self::level_2_complete_maintenance) {
164
+			//we also want to handle the opposite: if the site is mm2, but there aren't any migrations to run
165
+			//then we shouldn't be in mm2. (Maybe an addon got deactivated?)
166
+			update_option(self::option_name_maintenance_mode, self::level_0_not_in_maintenance);
167
+			return false;
168
+		}
169
+		return false;
170
+	}
171
+
172
+
173
+
174
+	/**
175
+	 * Updates the maintenance level on the site
176
+	 *
177
+	 * @param int $level
178
+	 * @return void
179
+	 */
180
+	public function set_maintenance_level($level)
181
+	{
182
+		do_action('AHEE__EE_Maintenance_Mode__set_maintenance_level', $level);
183
+		update_option(self::option_name_maintenance_mode, (int)$level);
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * returns TRUE if M-Mode is engaged and the current request is not for the admin
190
+	 *
191
+	 * @return    string
192
+	 */
193
+	public static function disable_frontend_for_maintenance()
194
+	{
195
+		return (! is_admin() && EE_Maintenance_Mode::instance()->level());
196
+	}
197
+
198
+
199
+
200
+	/**
201
+	 * @return void
202
+	 */
203
+	public function load_assets_required_for_m_mode()
204
+	{
205
+		if (
206
+			$this->real_level() === EE_Maintenance_Mode::level_2_complete_maintenance
207
+			&& ! wp_script_is('espresso_core')
208
+		) {
209
+			wp_register_style(
210
+				'espresso_default',
211
+				EE_GLOBAL_ASSETS_URL . 'css/espresso_default.css',
212
+				array('dashicons'),
213
+				EVENT_ESPRESSO_VERSION
214
+			);
215
+			wp_enqueue_style('espresso_default');
216
+			wp_register_script(
217
+				'espresso_core',
218
+				EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
219
+				array('jquery'),
220
+				EVENT_ESPRESSO_VERSION,
221
+				true
222
+			);
223
+			wp_enqueue_script('espresso_core');
224
+		}
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * replacement EE CPT template that displays message notifying site visitors
231
+	 * that EE has been temporarily placed into maintenance mode
232
+	 * does NOT get called on non-EE-CPT requests
233
+	 *
234
+	 * @return    string
235
+	 */
236
+	public static function template_include()
237
+	{
238
+		// shut 'er down down for maintenance ? then don't use any of our templates for our endpoints
239
+		return get_template_directory() . '/index.php';
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * displays message notifying site visitors that EE has been temporarily
246
+	 * placed into maintenance mode when post_type != EE CPT
247
+	 *
248
+	 * @param string $the_content
249
+	 * @return string
250
+	 */
251
+	public function the_content($the_content)
252
+	{
253
+		// check if M-mode is engaged and for EE shortcode
254
+		if ($this->level() && strpos($the_content, '[ESPRESSO_') !== false) {
255
+			// this can eventually be moved to a template, or edited via admin. But for now...
256
+			$the_content = sprintf(
257
+				esc_html__(
258
+					'%sMaintenance Mode%sEvent Registration has been temporarily closed while system maintenance is being performed. We\'re sorry for any inconveniences this may have caused. Please try back again later.%s',
259
+					'event_espresso'
260
+				),
261
+				'<h3>',
262
+				'</h3><p>',
263
+				'</p>'
264
+			);
265
+		}
266
+		return $the_content;
267
+	}
268 268
 
269 269
 
270 270
 
271
-    /**
272
-     * displays message on frontend of site notifying admin that EE has been temporarily placed into maintenance mode
273
-     */
274
-    public function display_maintenance_mode_notice()
275
-    {
276
-        // check if M-mode is engaged and for EE shortcode
277
-        if (
278
-            ! (defined('DOING_AJAX') && DOING_AJAX)
279
-            && $this->real_level()
280
-            && ! is_admin()
281
-            && current_user_can('administrator')
282
-            && EE_Registry::instance()->REQ->is_espresso_page()
283
-        ) {
284
-            printf(
285
-                esc_html__(
286
-                    '%sclose%sEvent Registration is currently disabled because Event Espresso has been placed into Maintenance Mode. To change Maintenance Mode settings, click here %sEE Maintenance Mode Admin Page%s',
287
-                    'event_espresso'
288
-                ),
289
-                '<div id="ee-m-mode-admin-notice-dv" class="ee-really-important-notice-dv"><a class="close-espresso-notice" title="',
290
-                '"><span class="dashicons dashicons-no"></span></a><p>',
291
-                ' &raquo; <a href="' . add_query_arg(
292
-                    array('page' => 'espresso_maintenance_settings'), admin_url('admin.php')
293
-                ) . '">',
294
-                '</a></p></div>'
295
-            );
296
-        }
297
-    }
298
-    // espresso-notices important-notice ee-attention
271
+	/**
272
+	 * displays message on frontend of site notifying admin that EE has been temporarily placed into maintenance mode
273
+	 */
274
+	public function display_maintenance_mode_notice()
275
+	{
276
+		// check if M-mode is engaged and for EE shortcode
277
+		if (
278
+			! (defined('DOING_AJAX') && DOING_AJAX)
279
+			&& $this->real_level()
280
+			&& ! is_admin()
281
+			&& current_user_can('administrator')
282
+			&& EE_Registry::instance()->REQ->is_espresso_page()
283
+		) {
284
+			printf(
285
+				esc_html__(
286
+					'%sclose%sEvent Registration is currently disabled because Event Espresso has been placed into Maintenance Mode. To change Maintenance Mode settings, click here %sEE Maintenance Mode Admin Page%s',
287
+					'event_espresso'
288
+				),
289
+				'<div id="ee-m-mode-admin-notice-dv" class="ee-really-important-notice-dv"><a class="close-espresso-notice" title="',
290
+				'"><span class="dashicons dashicons-no"></span></a><p>',
291
+				' &raquo; <a href="' . add_query_arg(
292
+					array('page' => 'espresso_maintenance_settings'), admin_url('admin.php')
293
+				) . '">',
294
+				'</a></p></div>'
295
+			);
296
+		}
297
+	}
298
+	// espresso-notices important-notice ee-attention
299 299
 
300 300
 
301 301
 
302
-    /**
303
-     * override magic methods
304
-     */
305
-    final public function __destruct()
306
-    {
307
-    }
302
+	/**
303
+	 * override magic methods
304
+	 */
305
+	final public function __destruct()
306
+	{
307
+	}
308 308
 
309 309
 
310 310
 
311
-    final public function __call($a, $b)
312
-    {
313
-    }
311
+	final public function __call($a, $b)
312
+	{
313
+	}
314 314
 
315 315
 
316 316
 
317
-    final public function __get($a)
318
-    {
319
-    }
317
+	final public function __get($a)
318
+	{
319
+	}
320 320
 
321 321
 
322 322
 
323
-    final public function __set($a, $b)
324
-    {
325
-    }
323
+	final public function __set($a, $b)
324
+	{
325
+	}
326 326
 
327 327
 
328 328
 
329
-    final public function __isset($a)
330
-    {
331
-    }
329
+	final public function __isset($a)
330
+	{
331
+	}
332 332
 
333 333
 
334 334
 
335
-    final public function __unset($a)
336
-    {
337
-    }
335
+	final public function __unset($a)
336
+	{
337
+	}
338 338
 
339 339
 
340 340
 
341
-    final public function __sleep()
342
-    {
343
-        return array();
344
-    }
341
+	final public function __sleep()
342
+	{
343
+		return array();
344
+	}
345 345
 
346 346
 
347 347
 
348
-    final public function __wakeup()
349
-    {
350
-    }
348
+	final public function __wakeup()
349
+	{
350
+	}
351 351
 
352 352
 
353 353
 
354
-    final public function __invoke()
355
-    {
356
-    }
354
+	final public function __invoke()
355
+	{
356
+	}
357 357
 
358 358
 
359 359
 
360
-    final public static function __set_state($a = null)
361
-    {
362
-        return EE_Maintenance_Mode::instance();
363
-    }
360
+	final public static function __set_state($a = null)
361
+	{
362
+		return EE_Maintenance_Mode::instance();
363
+	}
364 364
 
365 365
 
366 366
 
367
-    final public function __clone()
368
-    {
369
-    }
367
+	final public function __clone()
368
+	{
369
+	}
370 370
 
371 371
 
372 372
 
373
-    final public static function __callStatic($a, $b)
374
-    {
375
-    }
373
+	final public static function __callStatic($a, $b)
374
+	{
375
+	}
376 376
 
377 377
 }
378 378
 // End of file EE_Maintenance_Mode.core.php
Please login to merge, or discard this patch.
modules/add_new_state/EED_Add_New_State.module.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -698,7 +698,7 @@
 block discarded – undo
698 698
 
699 699
     /**
700 700
      * @param EE_State[] $state_options
701
-     * @return array
701
+     * @return EE_State[]
702 702
      * @throws EE_Error
703 703
      * @throws InvalidArgumentException
704 704
      * @throws InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +724 added lines, -724 removed lines patch added patch discarded remove patch
@@ -19,730 +19,730 @@
 block discarded – undo
19 19
 
20 20
 
21 21
 
22
-    /**
23
-     * @return EED_Module|EED_Add_New_State
24
-     */
25
-    public static function instance()
26
-    {
27
-        return parent::get_instance(__CLASS__);
28
-    }
29
-
30
-
31
-
32
-    /**
33
-     * set_hooks - for hooking into EE Core, other modules, etc
34
-     *
35
-     * @return void
36
-     */
37
-    public static function set_hooks()
38
-    {
39
-        add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
40
-        add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'translate_js_strings'), 0);
41
-        add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'wp_enqueue_scripts'), 10);
42
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
43
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
44
-        add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
45
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
46
-        add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
47
-            array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
48
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
49
-            array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
50
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
51
-            array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
52
-        add_filter('FHEE__EE_State_Select_Input____construct__state_options',
53
-            array('EED_Add_New_State', 'state_options'), 10, 1);
54
-        add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
55
-            array('EED_Add_New_State', 'country_options'), 10, 1);
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
62
-     *
63
-     * @return void
64
-     */
65
-    public static function set_hooks_admin()
66
-    {
67
-        add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
68
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
69
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
70
-        add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
71
-            array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
72
-        add_action('wp_ajax_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
73
-        add_action('wp_ajax_nopriv_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
74
-        add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
75
-            array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
76
-        add_action('AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
77
-            array('EED_Add_New_State', 'update_country_settings'), 10, 3);
78
-        add_action('AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
79
-            array('EED_Add_New_State', 'update_country_settings'), 10, 3);
80
-        add_filter('FHEE__EE_State_Select_Input____construct__state_options',
81
-            array('EED_Add_New_State', 'state_options'), 10, 1);
82
-        add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
83
-            array('EED_Add_New_State', 'country_options'), 10, 1);
84
-        add_filter('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
85
-            array('EED_Add_New_State', 'filter_checkout_request_params'), 10, 1);
86
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
87
-            array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
88
-        add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
89
-            array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
90
-    }
91
-
92
-
93
-
94
-    /**
95
-     * @return void
96
-     */
97
-    public static function set_definitions()
98
-    {
99
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
100
-        define('ANS_TEMPLATES_PATH', str_replace(
101
-                                         '\\',
102
-                                         DS,
103
-                                         plugin_dir_path(__FILE__)) . 'templates' . DS
104
-        );
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @param WP $WP
111
-     * @return void
112
-     */
113
-    public function run($WP)
114
-    {
115
-    }
116
-
117
-
118
-
119
-    /**
120
-     * @return void
121
-     */
122
-    public static function translate_js_strings()
123
-    {
124
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
125
-            'In order to proceed, you need to select the Country that your State/Province belongs to.',
126
-            'event_espresso'
127
-        );
128
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
129
-            'In order to proceed, you need to enter the name of your State/Province.',
130
-            'event_espresso'
131
-        );
132
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
133
-            'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
134
-            'event_espresso'
135
-        );
136
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
137
-            'The new state was successfully saved to the database.',
138
-            'event_espresso'
139
-        );
140
-        EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
141
-            'An unknown error has occurred on the server while saving the new state to the database.',
142
-            'event_espresso'
143
-        );
144
-    }
145
-
146
-
147
-
148
-    /**
149
-     * @return void
150
-     */
151
-    public static function wp_enqueue_scripts()
152
-    {
153
-        if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
154
-            wp_register_script('add_new_state', ANS_ASSETS_URL . 'add_new_state.js',
155
-                array('espresso_core', 'single_page_checkout'), EVENT_ESPRESSO_VERSION, true);
156
-            wp_enqueue_script('add_new_state');
157
-        }
158
-    }
159
-
160
-
161
-
162
-    /**
163
-     * display_add_new_state_micro_form
164
-     *
165
-     * @param EE_Form_Section_Proper $question_group_reg_form
166
-     * @return string
167
-     * @throws EE_Error
168
-     * @throws InvalidArgumentException
169
-     * @throws InvalidDataTypeException
170
-     * @throws InvalidInterfaceException
171
-     */
172
-    //	public static function display_add_new_state_micro_form( $html, EE_Form_Input_With_Options_Base $input ){
173
-    public static function display_add_new_state_micro_form(EE_Form_Section_Proper $question_group_reg_form)
174
-    {
175
-        // only add the 'new_state_micro_form' when displaying reg forms,
176
-        // not during processing since we process the 'new_state_micro_form' in it's own AJAX request
177
-        $action = EE_Registry::instance()->REQ->get('action', '');
178
-        // is the "state" question in this form section?
179
-        $input = $question_group_reg_form->get_subsection('state');
180
-        if ($action === 'process_reg_step' || $action === 'update_reg_step') {
181
-            //ok then all we need to do is make sure the input's HTML name is consistent
182
-            //by forcing it to set it now, like it did while getting the form for display
183
-            if ($input instanceof EE_State_Select_Input) {
184
-                $input->html_name();
185
-            }
186
-            return $question_group_reg_form;
187
-        }
188
-        // we're only doing this for state select inputs
189
-        if ($input instanceof EE_State_Select_Input) {
190
-            // grab any set values from the request
191
-            $country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
192
-            $state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
193
-            $abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
194
-            $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
195
-            $country_options     = array();
196
-            $countries           = EEM_Country::instance()->get_all_countries();
197
-            if (! empty($countries)) {
198
-                foreach ($countries as $country) {
199
-                    if ($country instanceof EE_Country) {
200
-                        $country_options[$country->ID()] = $country->name();
201
-                    }
202
-                }
203
-            }
204
-            $new_state_micro_form = new EE_Form_Section_Proper(
205
-                array(
206
-                    'name'            => 'new_state_micro_form',
207
-                    'html_id'         => 'new_state_micro_form',
208
-                    'layout_strategy' => new EE_Div_Per_Section_Layout(),
209
-                    'subsections'     => array(
210
-                        // add hidden input to indicate that a new state is being added
211
-                        'add_new_state'               => new EE_Hidden_Input(
212
-                            array(
213
-                                'html_name' => str_replace(
214
-                                    'state',
215
-                                    'nsmf_add_new_state',
216
-                                    $input->html_name()
217
-                                ),
218
-                                'html_id'   => str_replace(
219
-                                    'state',
220
-                                    'nsmf_add_new_state',
221
-                                    $input->html_id()
222
-                                ),
223
-                                'default'   => 0,
224
-                            )
225
-                        ),
226
-                        // add link for displaying hidden container
227
-                        'click_here_link'             => new EE_Form_Section_HTML(
228
-                            apply_filters(
229
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
230
-                                EEH_HTML::link(
231
-                                    '',
232
-                                    esc_html__('click here to add a new state/province', 'event_espresso'),
233
-                                    '',
234
-                                    'display-' . $input->html_id(),
235
-                                    'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
236
-                                    '',
237
-                                    'data-target="' . $input->html_id() . '"'
238
-                                )
239
-                            )
240
-                        ),
241
-                        // add initial html for hidden container
242
-                        'add_new_state_micro_form'    => new EE_Form_Section_HTML(
243
-                            apply_filters(
244
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
245
-                                EEH_HTML::div('', $input->html_id() . '-dv', 'ee-form-add-new-state-dv',
246
-                                    'display: none;') .
247
-                                EEH_HTML::h6(
248
-                                    esc_html__(
249
-                                        'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
250
-                                        'event_espresso'
251
-                                    )
252
-                                ) .
253
-                                EEH_HTML::ul() .
254
-                                EEH_HTML::li(
255
-                                    esc_html__(
256
-                                        'first select the Country that your State/Province belongs to',
257
-                                        'event_espresso'
258
-                                    )
259
-                                ) .
260
-                                EEH_HTML::li(
261
-                                    esc_html__('enter the name of your State/Province', 'event_espresso')
262
-                                ) .
263
-                                EEH_HTML::li(
264
-                                    esc_html__(
265
-                                        'enter a two to six letter abbreviation for the name of your State/Province',
266
-                                        'event_espresso'
267
-                                    )
268
-                                ) .
269
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
270
-                                EEH_HTML::ulx()
271
-                            )
272
-                        ),
273
-                        // NEW STATE COUNTRY
274
-                        'new_state_country'           => new EE_Country_Select_Input(
275
-                            $country_options,
276
-                            array(
277
-                                'html_name'       => $country_name,
278
-                                'html_id'         => str_replace(
279
-                                    'state',
280
-                                    'nsmf_new_state_country', $input->html_id()
281
-                                ),
282
-                                'html_class'      => $input->html_class() . ' new-state-country',
283
-                                'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
284
-                                'default'         => EE_Registry::instance()->REQ->get($country_name, ''),
285
-                                'required'        => false,
286
-                            )
287
-                        ),
288
-                        // NEW STATE NAME
289
-                        'new_state_name'              => new EE_Text_Input(
290
-                            array(
291
-                                'html_name'       => $state_name,
292
-                                'html_id'         => str_replace(
293
-                                    'state',
294
-                                    'nsmf_new_state_name', $input->html_id()
295
-                                ),
296
-                                'html_class'      => $input->html_class() . ' new-state-state',
297
-                                'html_label_text' => esc_html__('New State/Province Name',
298
-                                    'event_espresso'),
299
-                                'default'         => EE_Registry::instance()->REQ->get($state_name, ''),
300
-                                'required'        => false,
301
-                            )
302
-                        ),
303
-                        'spacer'                      => new EE_Form_Section_HTML(EEH_HTML::br()),
304
-                        // NEW STATE NAME
305
-                        'new_state_abbrv'             => new EE_Text_Input(
306
-                            array(
307
-                                'html_name'             => $abbrv_name,
308
-                                'html_id'               => str_replace('state', 'nsmf_new_state_abbrv',
309
-                                    $input->html_id()),
310
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
311
-                                'html_label_text'       => esc_html__(
312
-                                                               'New State/Province Abbreviation',
313
-                                                               'event_espresso'
314
-                                                           ) . ' *',
315
-                                'html_other_attributes' => 'size="24"',
316
-                                'default'               => EE_Registry::instance()->REQ->get($abbrv_name, ''),
317
-                                'required'              => false,
318
-                            )
319
-                        ),
320
-                        // "submit" button
321
-                        'add_new_state_submit_button' => new EE_Form_Section_HTML(
322
-                            apply_filters(
323
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
324
-                                EEH_HTML::nbsp(3) .
325
-                                EEH_HTML::link(
326
-                                    '',
327
-                                    esc_html__('ADD', 'event_espresso'),
328
-                                    '',
329
-                                    'submit-' . $new_state_submit_id,
330
-                                    'ee-form-add-new-state-submit button button-secondary',
331
-                                    '',
332
-                                    'data-target="' . $new_state_submit_id . '"'
333
-                                )
334
-                            )
335
-                        ),
336
-                        // extra info
337
-                        'add_new_state_extra'         => new EE_Form_Section_HTML(
338
-                            apply_filters(
339
-                                'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
340
-                                EEH_HTML::br(2)
341
-                                .
342
-                                EEH_HTML::div('', '', 'small-text')
343
-                                .
344
-                                EEH_HTML::strong(
345
-                                    '* ' .
346
-                                    esc_html__(
347
-                                        'Don\'t know your State/Province Abbreviation?',
348
-                                        'event_espresso'
349
-                                    )
350
-                                )
351
-                                .
352
-                                EEH_HTML::br()
353
-                                .
354
-                                sprintf(
355
-                                    esc_html__(
356
-                                        'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
357
-                                        'event_espresso'
358
-                                    ),
359
-                                    EEH_HTML::link(
360
-                                        'http://en.wikipedia.org/wiki/ISO_3166-2',
361
-                                        'http://en.wikipedia.org/wiki/ISO_3166-2',
362
-                                        '',
363
-                                        '',
364
-                                        'ee-form-add-new-state-wiki-lnk',
365
-                                        '',
366
-                                        'target="_blank"'
367
-                                    )
368
-                                )
369
-                                .
370
-                                EEH_HTML::divx()
371
-                                .
372
-                                EEH_HTML::br()
373
-                                .
374
-                                EEH_HTML::link(
375
-                                    '',
376
-                                    esc_html__('cancel new State/Province', 'event_espresso'),
377
-                                    '',
378
-                                    'hide-' . $input->html_id(),
379
-                                    'ee-form-cancel-new-state-lnk smaller-text',
380
-                                    '',
381
-                                    'data-target="' . $input->html_id() . '"'
382
-                                )
383
-                                .
384
-                                EEH_HTML::divx()
385
-                                .
386
-                                EEH_HTML::br()
387
-                            )
388
-                        ),
389
-                    ),
390
-                )
391
-            );
392
-            $question_group_reg_form->add_subsections(
393
-                array('new_state_micro_form' => $new_state_micro_form),
394
-                'state',
395
-                false
396
-            );
397
-        }
398
-        return $question_group_reg_form;
399
-    }
400
-
401
-
402
-
403
-    /**
404
-     * set_new_state_input_width
405
-     *
406
-     * @return int|string
407
-     * @throws EE_Error
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidDataTypeException
410
-     * @throws InvalidInterfaceException
411
-     * @throws ReflectionException
412
-     */
413
-    public static function add_new_state()
414
-    {
415
-        $REQ = EE_Registry::instance()->load_core('Request_Handler');
416
-        if (absint($REQ->get('nsmf_add_new_state')) === 1) {
417
-            EE_Registry::instance()->load_model('State');
418
-            // grab country ISO code, new state name, and new state abbreviation
419
-            $state_country = $REQ->is_set('nsmf_new_state_country')
420
-                ? sanitize_text_field($REQ->get('nsmf_new_state_country'))
421
-                : false;
422
-            $state_name    = $REQ->is_set('nsmf_new_state_name')
423
-                ? sanitize_text_field($REQ->get('nsmf_new_state_name'))
424
-                : false;
425
-            $state_abbr    = $REQ->is_set('nsmf_new_state_abbrv')
426
-                ? sanitize_text_field($REQ->get('nsmf_new_state_abbrv'))
427
-                : false;
428
-            if ($state_country && $state_name && $state_abbr) {
429
-                $new_state = EED_Add_New_State::save_new_state_to_db(array(
430
-                    'CNT_ISO'    => strtoupper($state_country),
431
-                    'STA_abbrev' => strtoupper($state_abbr),
432
-                    'STA_name'   => ucwords($state_name),
433
-                    'STA_active' => false,
434
-                ));
435
-                if ($new_state instanceof EE_State) {
436
-                    // clean house
437
-                    EE_Registry::instance()->REQ->un_set('nsmf_add_new_state');
438
-                    EE_Registry::instance()->REQ->un_set('nsmf_new_state_country');
439
-                    EE_Registry::instance()->REQ->un_set('nsmf_new_state_name');
440
-                    EE_Registry::instance()->REQ->un_set('nsmf_new_state_abbrv');
441
-                    // get any existing new states
442
-                    $new_states                   = EE_Registry::instance()->SSN->get_session_data(
443
-                        'nsmf_new_states'
444
-                    );
445
-                    $new_states[$new_state->ID()] = $new_state;
446
-                    EE_Registry::instance()->SSN->set_session_data(
447
-                        array('nsmf_new_states' => $new_states)
448
-                    );
449
-                    if (EE_Registry::instance()->REQ->ajax) {
450
-                        echo wp_json_encode(array(
451
-                            'success'      => true,
452
-                            'id'           => $new_state->ID(),
453
-                            'name'         => $new_state->name(),
454
-                            'abbrev'       => $new_state->abbrev(),
455
-                            'country_iso'  => $new_state->country_iso(),
456
-                            'country_name' => $new_state->country()->name(),
457
-                        ));
458
-                        exit();
459
-                    }
460
-                    return $new_state->ID();
461
-                }
462
-            } else {
463
-                $error = esc_html__(
464
-                    'A new State/Province could not be added because invalid or missing data was received.',
465
-                    'event_espresso'
466
-                );
467
-                if (EE_Registry::instance()->REQ->ajax) {
468
-                    echo wp_json_encode(array('error' => $error));
469
-                    exit();
470
-                }
471
-                EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
472
-            }
473
-        }
474
-        return false;
475
-    }
476
-
477
-
478
-
479
-    /**
480
-     * recursively drills down through request params to remove any that were added by this module
481
-     *
482
-     * @param array $request_params
483
-     * @return array
484
-     */
485
-    public static function filter_checkout_request_params($request_params)
486
-    {
487
-        foreach ($request_params as $form_section) {
488
-            if (is_array($form_section)) {
489
-                EED_Add_New_State::unset_new_state_request_params($form_section);
490
-                EED_Add_New_State::filter_checkout_request_params($form_section);
491
-            }
492
-        }
493
-        return $request_params;
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * @param array $request_params
500
-     * @return array
501
-     */
502
-    public static function unset_new_state_request_params($request_params)
503
-    {
504
-        unset(
505
-            $request_params['new_state_micro_form'],
506
-            $request_params['new_state_micro_add_new_state'],
507
-            $request_params['new_state_micro_new_state_country'],
508
-            $request_params['new_state_micro_new_state_name'],
509
-            $request_params['new_state_micro_new_state_abbrv']
510
-        );
511
-        return $request_params;
512
-    }
513
-
514
-
515
-
516
-    /**
517
-     * @param array $props_n_values
518
-     * @return bool
519
-     * @throws EE_Error
520
-     * @throws InvalidArgumentException
521
-     * @throws InvalidDataTypeException
522
-     * @throws InvalidInterfaceException
523
-     */
524
-    public static function save_new_state_to_db($props_n_values = array())
525
-    {
526
-        $existing_state = EEM_State::instance()->get_all(array($props_n_values, 'limit' => 1));
527
-        if (! empty($existing_state)) {
528
-            return array_pop($existing_state);
529
-        }
530
-        $new_state = EE_State::new_instance($props_n_values);
531
-        if ($new_state instanceof EE_State) {
532
-            // if not non-ajax admin
533
-            $new_state_key    = 'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev();
534
-            $new_state_notice = sprintf(
535
-                esc_html__(
536
-                    'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
537
-                    'event_espresso'
538
-                ),
539
-                '<b>' . $new_state->name() . '</b>',
540
-                '<b>' . $new_state->abbrev() . '</b>',
541
-                '<b>' . $new_state->country()->name() . '</b>',
542
-                '<a href="' . add_query_arg(array(
543
-                    'page'    => 'espresso_general_settings',
544
-                    'action'  => 'country_settings',
545
-                    'country' => $new_state->country_iso(),
546
-                ), admin_url('admin.php')) . '">' . esc_html__('Event Espresso - General Settings > Countries Tab',
547
-                    'event_espresso') . '</a>',
548
-                '<br />'
549
-            );
550
-            EE_Error::add_persistent_admin_notice($new_state_key, $new_state_notice);
551
-            $new_state->save();
552
-            EEM_State::instance()->reset_cached_states();
553
-            return $new_state;
554
-        }
555
-        return false;
556
-    }
557
-
558
-
559
-
560
-    /**
561
-     * @param string $CNT_ISO
562
-     * @param string $STA_ID
563
-     * @param array  $cols_n_values
564
-     * @return void
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     */
570
-    public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = array())
571
-    {
572
-        if (! $CNT_ISO) {
573
-            EE_Error::add_error(
574
-                esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
575
-                __FILE__,
576
-                __FUNCTION__,
577
-                __LINE__
578
-            );
579
-        }
580
-        $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
581
-            : false;
582
-        if (! $STA_abbrev && ! empty($STA_ID)) {
583
-            $state = EEM_State::instance()->get_one_by_ID($STA_ID);
584
-            if ($state instanceof EE_State) {
585
-                $STA_abbrev = $state->abbrev();
586
-            }
587
-        }
588
-        if (! $STA_abbrev) {
589
-            EE_Error::add_error(
590
-                esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
591
-                __FILE__,
592
-                __FUNCTION__,
593
-                __LINE__
594
-            );
595
-        }
596
-        EE_Error::dismiss_persistent_admin_notice($CNT_ISO . '-' . $STA_abbrev, true, true);
597
-    }
598
-
599
-
600
-
601
-    /**
602
-     * @param EE_State[]                            $state_options
603
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
604
-     * @param EE_Registration                       $registration
605
-     * @param EE_Question                           $question
606
-     * @param                                       $answer
607
-     * @return array
608
-     * @throws EE_Error
609
-     * @throws InvalidArgumentException
610
-     * @throws InvalidDataTypeException
611
-     * @throws InvalidInterfaceException
612
-     */
613
-    public static function inject_new_reg_state_into_options(
614
-        $state_options = array(),
615
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
616
-        EE_Registration $registration,
617
-        EE_Question $question,
618
-        $answer
619
-    ) {
620
-        if ($answer instanceof EE_Answer && $question instanceof EE_Question
621
-            && $question->type() === EEM_Question::QST_type_state
622
-        ) {
623
-            $STA_ID = $answer->value();
624
-            if (! empty($STA_ID)) {
625
-                $state = EEM_State::instance()->get_one_by_ID($STA_ID);
626
-                if ($state instanceof EE_State) {
627
-                    $country = $state->country();
628
-                    if ($country instanceof EE_Country) {
629
-                        if (! isset($state_options[$country->name()])) {
630
-                            $state_options[$country->name()] = array();
631
-                        }
632
-                        if (! isset($state_options[$country->name()][$STA_ID])) {
633
-                            $state_options[$country->name()][$STA_ID] = $state->name();
634
-                        }
635
-                    }
636
-                }
637
-            }
638
-        }
639
-        return $state_options;
640
-    }
641
-
642
-
643
-
644
-    /**
645
-     * @param EE_Country[]                          $country_options
646
-     * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
647
-     * @param EE_Registration                       $registration
648
-     * @param EE_Question                           $question
649
-     * @param                                       $answer
650
-     * @return array
651
-     * @throws EE_Error
652
-     * @throws InvalidArgumentException
653
-     * @throws InvalidDataTypeException
654
-     * @throws InvalidInterfaceException
655
-     */
656
-    public static function inject_new_reg_country_into_options(
657
-        $country_options = array(),
658
-        EE_SPCO_Reg_Step_Attendee_Information $reg_step,
659
-        EE_Registration $registration,
660
-        EE_Question $question,
661
-        $answer
662
-    ) {
663
-        if ($answer instanceof EE_Answer && $question instanceof EE_Question
664
-            && $question->type()
665
-               === EEM_Question::QST_type_country
666
-        ) {
667
-            $CNT_ISO = $answer->value();
668
-            if (! empty($CNT_ISO)) {
669
-                $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
670
-                if ($country instanceof EE_Country) {
671
-                    if (! isset($country_options[$CNT_ISO])) {
672
-                        $country_options[$CNT_ISO] = $country->name();
673
-                    }
674
-                }
675
-            }
676
-        }
677
-        return $country_options;
678
-    }
679
-
680
-
681
-
682
-    /**
683
-     * @param EE_State[] $state_options
684
-     * @return array
685
-     * @throws EE_Error
686
-     * @throws InvalidArgumentException
687
-     * @throws InvalidDataTypeException
688
-     * @throws InvalidInterfaceException
689
-     */
690
-    public static function state_options($state_options = array())
691
-    {
692
-        $new_states = EED_Add_New_State::_get_new_states();
693
-        foreach ($new_states as $new_state) {
694
-            if (
695
-                $new_state instanceof EE_State
696
-                && $new_state->country() instanceof EE_Country
697
-            ) {
698
-                $state_options[$new_state->country()->name()][$new_state->ID()] = $new_state->name();
699
-            }
700
-        }
701
-        return $state_options;
702
-    }
703
-
704
-
705
-
706
-    /**
707
-     * @return array
708
-     * @throws InvalidArgumentException
709
-     * @throws InvalidDataTypeException
710
-     * @throws InvalidInterfaceException
711
-     */
712
-    protected static function _get_new_states()
713
-    {
714
-        $new_states = array();
715
-        if (EE_Registry::instance()->SSN instanceof EE_Session) {
716
-            $new_states = EE_Registry::instance()->SSN->get_session_data(
717
-                'nsmf_new_states'
718
-            );
719
-        }
720
-        return is_array($new_states) ? $new_states : array();
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * @param EE_Country[] $country_options
727
-     * @return array
728
-     * @throws EE_Error
729
-     * @throws InvalidArgumentException
730
-     * @throws InvalidDataTypeException
731
-     * @throws InvalidInterfaceException
732
-     */
733
-    public static function country_options($country_options = array())
734
-    {
735
-        $new_states = EED_Add_New_State::_get_new_states();
736
-        foreach ($new_states as $new_state) {
737
-            if (
738
-                $new_state instanceof EE_State
739
-                && $new_state->country() instanceof EE_Country
740
-            ) {
741
-                $country_options[$new_state->country()->ID()] = $new_state->country()->name();
742
-            }
743
-        }
744
-        return $country_options;
745
-    }
22
+	/**
23
+	 * @return EED_Module|EED_Add_New_State
24
+	 */
25
+	public static function instance()
26
+	{
27
+		return parent::get_instance(__CLASS__);
28
+	}
29
+
30
+
31
+
32
+	/**
33
+	 * set_hooks - for hooking into EE Core, other modules, etc
34
+	 *
35
+	 * @return void
36
+	 */
37
+	public static function set_hooks()
38
+	{
39
+		add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
40
+		add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'translate_js_strings'), 0);
41
+		add_action('wp_enqueue_scripts', array('EED_Add_New_State', 'wp_enqueue_scripts'), 10);
42
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
43
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
44
+		add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
45
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
46
+		add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
47
+			array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
48
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
49
+			array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
50
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
51
+			array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
52
+		add_filter('FHEE__EE_State_Select_Input____construct__state_options',
53
+			array('EED_Add_New_State', 'state_options'), 10, 1);
54
+		add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
55
+			array('EED_Add_New_State', 'country_options'), 10, 1);
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 * set_hooks_admin - for hooking into EE Admin Core, other modules, etc
62
+	 *
63
+	 * @return void
64
+	 */
65
+	public static function set_hooks_admin()
66
+	{
67
+		add_action('wp_loaded', array('EED_Add_New_State', 'set_definitions'), 2);
68
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___question_group_reg_form__question_group_reg_form',
69
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
70
+		add_filter('FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
71
+			array('EED_Add_New_State', 'display_add_new_state_micro_form'), 1, 1);
72
+		add_action('wp_ajax_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
73
+		add_action('wp_ajax_nopriv_espresso_add_new_state', array('EED_Add_New_State', 'add_new_state'));
74
+		add_filter('FHEE__EE_Single_Page_Checkout__process_attendee_information__valid_data_line_item',
75
+			array('EED_Add_New_State', 'unset_new_state_request_params'), 10, 1);
76
+		add_action('AHEE__General_Settings_Admin_Page__update_country_settings__state_saved',
77
+			array('EED_Add_New_State', 'update_country_settings'), 10, 3);
78
+		add_action('AHEE__General_Settings_Admin_Page__delete_state__state_deleted',
79
+			array('EED_Add_New_State', 'update_country_settings'), 10, 3);
80
+		add_filter('FHEE__EE_State_Select_Input____construct__state_options',
81
+			array('EED_Add_New_State', 'state_options'), 10, 1);
82
+		add_filter('FHEE__EE_Country_Select_Input____construct__country_options',
83
+			array('EED_Add_New_State', 'country_options'), 10, 1);
84
+		add_filter('FHEE__EE_Form_Section_Proper__receive_form_submission__request_data',
85
+			array('EED_Add_New_State', 'filter_checkout_request_params'), 10, 1);
86
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__state_options',
87
+			array('EED_Add_New_State', 'inject_new_reg_state_into_options'), 10, 5);
88
+		add_filter('FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__country_options',
89
+			array('EED_Add_New_State', 'inject_new_reg_country_into_options'), 10, 5);
90
+	}
91
+
92
+
93
+
94
+	/**
95
+	 * @return void
96
+	 */
97
+	public static function set_definitions()
98
+	{
99
+		define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
100
+		define('ANS_TEMPLATES_PATH', str_replace(
101
+										 '\\',
102
+										 DS,
103
+										 plugin_dir_path(__FILE__)) . 'templates' . DS
104
+		);
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @param WP $WP
111
+	 * @return void
112
+	 */
113
+	public function run($WP)
114
+	{
115
+	}
116
+
117
+
118
+
119
+	/**
120
+	 * @return void
121
+	 */
122
+	public static function translate_js_strings()
123
+	{
124
+		EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
125
+			'In order to proceed, you need to select the Country that your State/Province belongs to.',
126
+			'event_espresso'
127
+		);
128
+		EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
129
+			'In order to proceed, you need to enter the name of your State/Province.',
130
+			'event_espresso'
131
+		);
132
+		EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
133
+			'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
134
+			'event_espresso'
135
+		);
136
+		EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
137
+			'The new state was successfully saved to the database.',
138
+			'event_espresso'
139
+		);
140
+		EE_Registry::$i18n_js_strings['ans_server_save_error'] = esc_html__(
141
+			'An unknown error has occurred on the server while saving the new state to the database.',
142
+			'event_espresso'
143
+		);
144
+	}
145
+
146
+
147
+
148
+	/**
149
+	 * @return void
150
+	 */
151
+	public static function wp_enqueue_scripts()
152
+	{
153
+		if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
154
+			wp_register_script('add_new_state', ANS_ASSETS_URL . 'add_new_state.js',
155
+				array('espresso_core', 'single_page_checkout'), EVENT_ESPRESSO_VERSION, true);
156
+			wp_enqueue_script('add_new_state');
157
+		}
158
+	}
159
+
160
+
161
+
162
+	/**
163
+	 * display_add_new_state_micro_form
164
+	 *
165
+	 * @param EE_Form_Section_Proper $question_group_reg_form
166
+	 * @return string
167
+	 * @throws EE_Error
168
+	 * @throws InvalidArgumentException
169
+	 * @throws InvalidDataTypeException
170
+	 * @throws InvalidInterfaceException
171
+	 */
172
+	//	public static function display_add_new_state_micro_form( $html, EE_Form_Input_With_Options_Base $input ){
173
+	public static function display_add_new_state_micro_form(EE_Form_Section_Proper $question_group_reg_form)
174
+	{
175
+		// only add the 'new_state_micro_form' when displaying reg forms,
176
+		// not during processing since we process the 'new_state_micro_form' in it's own AJAX request
177
+		$action = EE_Registry::instance()->REQ->get('action', '');
178
+		// is the "state" question in this form section?
179
+		$input = $question_group_reg_form->get_subsection('state');
180
+		if ($action === 'process_reg_step' || $action === 'update_reg_step') {
181
+			//ok then all we need to do is make sure the input's HTML name is consistent
182
+			//by forcing it to set it now, like it did while getting the form for display
183
+			if ($input instanceof EE_State_Select_Input) {
184
+				$input->html_name();
185
+			}
186
+			return $question_group_reg_form;
187
+		}
188
+		// we're only doing this for state select inputs
189
+		if ($input instanceof EE_State_Select_Input) {
190
+			// grab any set values from the request
191
+			$country_name        = str_replace('state', 'nsmf_new_state_country', $input->html_name());
192
+			$state_name          = str_replace('state', 'nsmf_new_state_name', $input->html_name());
193
+			$abbrv_name          = str_replace('state', 'nsmf_new_state_abbrv', $input->html_name());
194
+			$new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
195
+			$country_options     = array();
196
+			$countries           = EEM_Country::instance()->get_all_countries();
197
+			if (! empty($countries)) {
198
+				foreach ($countries as $country) {
199
+					if ($country instanceof EE_Country) {
200
+						$country_options[$country->ID()] = $country->name();
201
+					}
202
+				}
203
+			}
204
+			$new_state_micro_form = new EE_Form_Section_Proper(
205
+				array(
206
+					'name'            => 'new_state_micro_form',
207
+					'html_id'         => 'new_state_micro_form',
208
+					'layout_strategy' => new EE_Div_Per_Section_Layout(),
209
+					'subsections'     => array(
210
+						// add hidden input to indicate that a new state is being added
211
+						'add_new_state'               => new EE_Hidden_Input(
212
+							array(
213
+								'html_name' => str_replace(
214
+									'state',
215
+									'nsmf_add_new_state',
216
+									$input->html_name()
217
+								),
218
+								'html_id'   => str_replace(
219
+									'state',
220
+									'nsmf_add_new_state',
221
+									$input->html_id()
222
+								),
223
+								'default'   => 0,
224
+							)
225
+						),
226
+						// add link for displaying hidden container
227
+						'click_here_link'             => new EE_Form_Section_HTML(
228
+							apply_filters(
229
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__click_here_link',
230
+								EEH_HTML::link(
231
+									'',
232
+									esc_html__('click here to add a new state/province', 'event_espresso'),
233
+									'',
234
+									'display-' . $input->html_id(),
235
+									'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
236
+									'',
237
+									'data-target="' . $input->html_id() . '"'
238
+								)
239
+							)
240
+						),
241
+						// add initial html for hidden container
242
+						'add_new_state_micro_form'    => new EE_Form_Section_HTML(
243
+							apply_filters(
244
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
245
+								EEH_HTML::div('', $input->html_id() . '-dv', 'ee-form-add-new-state-dv',
246
+									'display: none;') .
247
+								EEH_HTML::h6(
248
+									esc_html__(
249
+										'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
250
+										'event_espresso'
251
+									)
252
+								) .
253
+								EEH_HTML::ul() .
254
+								EEH_HTML::li(
255
+									esc_html__(
256
+										'first select the Country that your State/Province belongs to',
257
+										'event_espresso'
258
+									)
259
+								) .
260
+								EEH_HTML::li(
261
+									esc_html__('enter the name of your State/Province', 'event_espresso')
262
+								) .
263
+								EEH_HTML::li(
264
+									esc_html__(
265
+										'enter a two to six letter abbreviation for the name of your State/Province',
266
+										'event_espresso'
267
+									)
268
+								) .
269
+								EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
270
+								EEH_HTML::ulx()
271
+							)
272
+						),
273
+						// NEW STATE COUNTRY
274
+						'new_state_country'           => new EE_Country_Select_Input(
275
+							$country_options,
276
+							array(
277
+								'html_name'       => $country_name,
278
+								'html_id'         => str_replace(
279
+									'state',
280
+									'nsmf_new_state_country', $input->html_id()
281
+								),
282
+								'html_class'      => $input->html_class() . ' new-state-country',
283
+								'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
284
+								'default'         => EE_Registry::instance()->REQ->get($country_name, ''),
285
+								'required'        => false,
286
+							)
287
+						),
288
+						// NEW STATE NAME
289
+						'new_state_name'              => new EE_Text_Input(
290
+							array(
291
+								'html_name'       => $state_name,
292
+								'html_id'         => str_replace(
293
+									'state',
294
+									'nsmf_new_state_name', $input->html_id()
295
+								),
296
+								'html_class'      => $input->html_class() . ' new-state-state',
297
+								'html_label_text' => esc_html__('New State/Province Name',
298
+									'event_espresso'),
299
+								'default'         => EE_Registry::instance()->REQ->get($state_name, ''),
300
+								'required'        => false,
301
+							)
302
+						),
303
+						'spacer'                      => new EE_Form_Section_HTML(EEH_HTML::br()),
304
+						// NEW STATE NAME
305
+						'new_state_abbrv'             => new EE_Text_Input(
306
+							array(
307
+								'html_name'             => $abbrv_name,
308
+								'html_id'               => str_replace('state', 'nsmf_new_state_abbrv',
309
+									$input->html_id()),
310
+								'html_class'            => $input->html_class() . ' new-state-abbrv',
311
+								'html_label_text'       => esc_html__(
312
+															   'New State/Province Abbreviation',
313
+															   'event_espresso'
314
+														   ) . ' *',
315
+								'html_other_attributes' => 'size="24"',
316
+								'default'               => EE_Registry::instance()->REQ->get($abbrv_name, ''),
317
+								'required'              => false,
318
+							)
319
+						),
320
+						// "submit" button
321
+						'add_new_state_submit_button' => new EE_Form_Section_HTML(
322
+							apply_filters(
323
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
324
+								EEH_HTML::nbsp(3) .
325
+								EEH_HTML::link(
326
+									'',
327
+									esc_html__('ADD', 'event_espresso'),
328
+									'',
329
+									'submit-' . $new_state_submit_id,
330
+									'ee-form-add-new-state-submit button button-secondary',
331
+									'',
332
+									'data-target="' . $new_state_submit_id . '"'
333
+								)
334
+							)
335
+						),
336
+						// extra info
337
+						'add_new_state_extra'         => new EE_Form_Section_HTML(
338
+							apply_filters(
339
+								'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_extra',
340
+								EEH_HTML::br(2)
341
+								.
342
+								EEH_HTML::div('', '', 'small-text')
343
+								.
344
+								EEH_HTML::strong(
345
+									'* ' .
346
+									esc_html__(
347
+										'Don\'t know your State/Province Abbreviation?',
348
+										'event_espresso'
349
+									)
350
+								)
351
+								.
352
+								EEH_HTML::br()
353
+								.
354
+								sprintf(
355
+									esc_html__(
356
+										'You can look here: %s, for a list of Countries and links to their State/Province Abbreviations ("Subdivisions assigned codes" column).',
357
+										'event_espresso'
358
+									),
359
+									EEH_HTML::link(
360
+										'http://en.wikipedia.org/wiki/ISO_3166-2',
361
+										'http://en.wikipedia.org/wiki/ISO_3166-2',
362
+										'',
363
+										'',
364
+										'ee-form-add-new-state-wiki-lnk',
365
+										'',
366
+										'target="_blank"'
367
+									)
368
+								)
369
+								.
370
+								EEH_HTML::divx()
371
+								.
372
+								EEH_HTML::br()
373
+								.
374
+								EEH_HTML::link(
375
+									'',
376
+									esc_html__('cancel new State/Province', 'event_espresso'),
377
+									'',
378
+									'hide-' . $input->html_id(),
379
+									'ee-form-cancel-new-state-lnk smaller-text',
380
+									'',
381
+									'data-target="' . $input->html_id() . '"'
382
+								)
383
+								.
384
+								EEH_HTML::divx()
385
+								.
386
+								EEH_HTML::br()
387
+							)
388
+						),
389
+					),
390
+				)
391
+			);
392
+			$question_group_reg_form->add_subsections(
393
+				array('new_state_micro_form' => $new_state_micro_form),
394
+				'state',
395
+				false
396
+			);
397
+		}
398
+		return $question_group_reg_form;
399
+	}
400
+
401
+
402
+
403
+	/**
404
+	 * set_new_state_input_width
405
+	 *
406
+	 * @return int|string
407
+	 * @throws EE_Error
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidDataTypeException
410
+	 * @throws InvalidInterfaceException
411
+	 * @throws ReflectionException
412
+	 */
413
+	public static function add_new_state()
414
+	{
415
+		$REQ = EE_Registry::instance()->load_core('Request_Handler');
416
+		if (absint($REQ->get('nsmf_add_new_state')) === 1) {
417
+			EE_Registry::instance()->load_model('State');
418
+			// grab country ISO code, new state name, and new state abbreviation
419
+			$state_country = $REQ->is_set('nsmf_new_state_country')
420
+				? sanitize_text_field($REQ->get('nsmf_new_state_country'))
421
+				: false;
422
+			$state_name    = $REQ->is_set('nsmf_new_state_name')
423
+				? sanitize_text_field($REQ->get('nsmf_new_state_name'))
424
+				: false;
425
+			$state_abbr    = $REQ->is_set('nsmf_new_state_abbrv')
426
+				? sanitize_text_field($REQ->get('nsmf_new_state_abbrv'))
427
+				: false;
428
+			if ($state_country && $state_name && $state_abbr) {
429
+				$new_state = EED_Add_New_State::save_new_state_to_db(array(
430
+					'CNT_ISO'    => strtoupper($state_country),
431
+					'STA_abbrev' => strtoupper($state_abbr),
432
+					'STA_name'   => ucwords($state_name),
433
+					'STA_active' => false,
434
+				));
435
+				if ($new_state instanceof EE_State) {
436
+					// clean house
437
+					EE_Registry::instance()->REQ->un_set('nsmf_add_new_state');
438
+					EE_Registry::instance()->REQ->un_set('nsmf_new_state_country');
439
+					EE_Registry::instance()->REQ->un_set('nsmf_new_state_name');
440
+					EE_Registry::instance()->REQ->un_set('nsmf_new_state_abbrv');
441
+					// get any existing new states
442
+					$new_states                   = EE_Registry::instance()->SSN->get_session_data(
443
+						'nsmf_new_states'
444
+					);
445
+					$new_states[$new_state->ID()] = $new_state;
446
+					EE_Registry::instance()->SSN->set_session_data(
447
+						array('nsmf_new_states' => $new_states)
448
+					);
449
+					if (EE_Registry::instance()->REQ->ajax) {
450
+						echo wp_json_encode(array(
451
+							'success'      => true,
452
+							'id'           => $new_state->ID(),
453
+							'name'         => $new_state->name(),
454
+							'abbrev'       => $new_state->abbrev(),
455
+							'country_iso'  => $new_state->country_iso(),
456
+							'country_name' => $new_state->country()->name(),
457
+						));
458
+						exit();
459
+					}
460
+					return $new_state->ID();
461
+				}
462
+			} else {
463
+				$error = esc_html__(
464
+					'A new State/Province could not be added because invalid or missing data was received.',
465
+					'event_espresso'
466
+				);
467
+				if (EE_Registry::instance()->REQ->ajax) {
468
+					echo wp_json_encode(array('error' => $error));
469
+					exit();
470
+				}
471
+				EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
472
+			}
473
+		}
474
+		return false;
475
+	}
476
+
477
+
478
+
479
+	/**
480
+	 * recursively drills down through request params to remove any that were added by this module
481
+	 *
482
+	 * @param array $request_params
483
+	 * @return array
484
+	 */
485
+	public static function filter_checkout_request_params($request_params)
486
+	{
487
+		foreach ($request_params as $form_section) {
488
+			if (is_array($form_section)) {
489
+				EED_Add_New_State::unset_new_state_request_params($form_section);
490
+				EED_Add_New_State::filter_checkout_request_params($form_section);
491
+			}
492
+		}
493
+		return $request_params;
494
+	}
495
+
496
+
497
+
498
+	/**
499
+	 * @param array $request_params
500
+	 * @return array
501
+	 */
502
+	public static function unset_new_state_request_params($request_params)
503
+	{
504
+		unset(
505
+			$request_params['new_state_micro_form'],
506
+			$request_params['new_state_micro_add_new_state'],
507
+			$request_params['new_state_micro_new_state_country'],
508
+			$request_params['new_state_micro_new_state_name'],
509
+			$request_params['new_state_micro_new_state_abbrv']
510
+		);
511
+		return $request_params;
512
+	}
513
+
514
+
515
+
516
+	/**
517
+	 * @param array $props_n_values
518
+	 * @return bool
519
+	 * @throws EE_Error
520
+	 * @throws InvalidArgumentException
521
+	 * @throws InvalidDataTypeException
522
+	 * @throws InvalidInterfaceException
523
+	 */
524
+	public static function save_new_state_to_db($props_n_values = array())
525
+	{
526
+		$existing_state = EEM_State::instance()->get_all(array($props_n_values, 'limit' => 1));
527
+		if (! empty($existing_state)) {
528
+			return array_pop($existing_state);
529
+		}
530
+		$new_state = EE_State::new_instance($props_n_values);
531
+		if ($new_state instanceof EE_State) {
532
+			// if not non-ajax admin
533
+			$new_state_key    = 'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev();
534
+			$new_state_notice = sprintf(
535
+				esc_html__(
536
+					'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
537
+					'event_espresso'
538
+				),
539
+				'<b>' . $new_state->name() . '</b>',
540
+				'<b>' . $new_state->abbrev() . '</b>',
541
+				'<b>' . $new_state->country()->name() . '</b>',
542
+				'<a href="' . add_query_arg(array(
543
+					'page'    => 'espresso_general_settings',
544
+					'action'  => 'country_settings',
545
+					'country' => $new_state->country_iso(),
546
+				), admin_url('admin.php')) . '">' . esc_html__('Event Espresso - General Settings > Countries Tab',
547
+					'event_espresso') . '</a>',
548
+				'<br />'
549
+			);
550
+			EE_Error::add_persistent_admin_notice($new_state_key, $new_state_notice);
551
+			$new_state->save();
552
+			EEM_State::instance()->reset_cached_states();
553
+			return $new_state;
554
+		}
555
+		return false;
556
+	}
557
+
558
+
559
+
560
+	/**
561
+	 * @param string $CNT_ISO
562
+	 * @param string $STA_ID
563
+	 * @param array  $cols_n_values
564
+	 * @return void
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 */
570
+	public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = array())
571
+	{
572
+		if (! $CNT_ISO) {
573
+			EE_Error::add_error(
574
+				esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
575
+				__FILE__,
576
+				__FUNCTION__,
577
+				__LINE__
578
+			);
579
+		}
580
+		$STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
581
+			: false;
582
+		if (! $STA_abbrev && ! empty($STA_ID)) {
583
+			$state = EEM_State::instance()->get_one_by_ID($STA_ID);
584
+			if ($state instanceof EE_State) {
585
+				$STA_abbrev = $state->abbrev();
586
+			}
587
+		}
588
+		if (! $STA_abbrev) {
589
+			EE_Error::add_error(
590
+				esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
591
+				__FILE__,
592
+				__FUNCTION__,
593
+				__LINE__
594
+			);
595
+		}
596
+		EE_Error::dismiss_persistent_admin_notice($CNT_ISO . '-' . $STA_abbrev, true, true);
597
+	}
598
+
599
+
600
+
601
+	/**
602
+	 * @param EE_State[]                            $state_options
603
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
604
+	 * @param EE_Registration                       $registration
605
+	 * @param EE_Question                           $question
606
+	 * @param                                       $answer
607
+	 * @return array
608
+	 * @throws EE_Error
609
+	 * @throws InvalidArgumentException
610
+	 * @throws InvalidDataTypeException
611
+	 * @throws InvalidInterfaceException
612
+	 */
613
+	public static function inject_new_reg_state_into_options(
614
+		$state_options = array(),
615
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
616
+		EE_Registration $registration,
617
+		EE_Question $question,
618
+		$answer
619
+	) {
620
+		if ($answer instanceof EE_Answer && $question instanceof EE_Question
621
+			&& $question->type() === EEM_Question::QST_type_state
622
+		) {
623
+			$STA_ID = $answer->value();
624
+			if (! empty($STA_ID)) {
625
+				$state = EEM_State::instance()->get_one_by_ID($STA_ID);
626
+				if ($state instanceof EE_State) {
627
+					$country = $state->country();
628
+					if ($country instanceof EE_Country) {
629
+						if (! isset($state_options[$country->name()])) {
630
+							$state_options[$country->name()] = array();
631
+						}
632
+						if (! isset($state_options[$country->name()][$STA_ID])) {
633
+							$state_options[$country->name()][$STA_ID] = $state->name();
634
+						}
635
+					}
636
+				}
637
+			}
638
+		}
639
+		return $state_options;
640
+	}
641
+
642
+
643
+
644
+	/**
645
+	 * @param EE_Country[]                          $country_options
646
+	 * @param EE_SPCO_Reg_Step_Attendee_Information $reg_step
647
+	 * @param EE_Registration                       $registration
648
+	 * @param EE_Question                           $question
649
+	 * @param                                       $answer
650
+	 * @return array
651
+	 * @throws EE_Error
652
+	 * @throws InvalidArgumentException
653
+	 * @throws InvalidDataTypeException
654
+	 * @throws InvalidInterfaceException
655
+	 */
656
+	public static function inject_new_reg_country_into_options(
657
+		$country_options = array(),
658
+		EE_SPCO_Reg_Step_Attendee_Information $reg_step,
659
+		EE_Registration $registration,
660
+		EE_Question $question,
661
+		$answer
662
+	) {
663
+		if ($answer instanceof EE_Answer && $question instanceof EE_Question
664
+			&& $question->type()
665
+			   === EEM_Question::QST_type_country
666
+		) {
667
+			$CNT_ISO = $answer->value();
668
+			if (! empty($CNT_ISO)) {
669
+				$country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
670
+				if ($country instanceof EE_Country) {
671
+					if (! isset($country_options[$CNT_ISO])) {
672
+						$country_options[$CNT_ISO] = $country->name();
673
+					}
674
+				}
675
+			}
676
+		}
677
+		return $country_options;
678
+	}
679
+
680
+
681
+
682
+	/**
683
+	 * @param EE_State[] $state_options
684
+	 * @return array
685
+	 * @throws EE_Error
686
+	 * @throws InvalidArgumentException
687
+	 * @throws InvalidDataTypeException
688
+	 * @throws InvalidInterfaceException
689
+	 */
690
+	public static function state_options($state_options = array())
691
+	{
692
+		$new_states = EED_Add_New_State::_get_new_states();
693
+		foreach ($new_states as $new_state) {
694
+			if (
695
+				$new_state instanceof EE_State
696
+				&& $new_state->country() instanceof EE_Country
697
+			) {
698
+				$state_options[$new_state->country()->name()][$new_state->ID()] = $new_state->name();
699
+			}
700
+		}
701
+		return $state_options;
702
+	}
703
+
704
+
705
+
706
+	/**
707
+	 * @return array
708
+	 * @throws InvalidArgumentException
709
+	 * @throws InvalidDataTypeException
710
+	 * @throws InvalidInterfaceException
711
+	 */
712
+	protected static function _get_new_states()
713
+	{
714
+		$new_states = array();
715
+		if (EE_Registry::instance()->SSN instanceof EE_Session) {
716
+			$new_states = EE_Registry::instance()->SSN->get_session_data(
717
+				'nsmf_new_states'
718
+			);
719
+		}
720
+		return is_array($new_states) ? $new_states : array();
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * @param EE_Country[] $country_options
727
+	 * @return array
728
+	 * @throws EE_Error
729
+	 * @throws InvalidArgumentException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws InvalidInterfaceException
732
+	 */
733
+	public static function country_options($country_options = array())
734
+	{
735
+		$new_states = EED_Add_New_State::_get_new_states();
736
+		foreach ($new_states as $new_state) {
737
+			if (
738
+				$new_state instanceof EE_State
739
+				&& $new_state->country() instanceof EE_Country
740
+			) {
741
+				$country_options[$new_state->country()->ID()] = $new_state->country()->name();
742
+			}
743
+		}
744
+		return $country_options;
745
+	}
746 746
 
747 747
 
748 748
 
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -96,11 +96,11 @@  discard block
 block discarded – undo
96 96
      */
97 97
     public static function set_definitions()
98 98
     {
99
-        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__) . 'assets' . DS);
99
+        define('ANS_ASSETS_URL', plugin_dir_url(__FILE__).'assets'.DS);
100 100
         define('ANS_TEMPLATES_PATH', str_replace(
101 101
                                          '\\',
102 102
                                          DS,
103
-                                         plugin_dir_path(__FILE__)) . 'templates' . DS
103
+                                         plugin_dir_path(__FILE__)).'templates'.DS
104 104
         );
105 105
     }
106 106
 
@@ -121,19 +121,19 @@  discard block
 block discarded – undo
121 121
      */
122 122
     public static function translate_js_strings()
123 123
     {
124
-        EE_Registry::$i18n_js_strings['ans_no_country']        = esc_html__(
124
+        EE_Registry::$i18n_js_strings['ans_no_country'] = esc_html__(
125 125
             'In order to proceed, you need to select the Country that your State/Province belongs to.',
126 126
             'event_espresso'
127 127
         );
128
-        EE_Registry::$i18n_js_strings['ans_no_name']           = esc_html__(
128
+        EE_Registry::$i18n_js_strings['ans_no_name'] = esc_html__(
129 129
             'In order to proceed, you need to enter the name of your State/Province.',
130 130
             'event_espresso'
131 131
         );
132
-        EE_Registry::$i18n_js_strings['ans_no_abbreviation']   = esc_html__(
132
+        EE_Registry::$i18n_js_strings['ans_no_abbreviation'] = esc_html__(
133 133
             'In order to proceed, you need to enter an abbreviation for the name of your State/Province.',
134 134
             'event_espresso'
135 135
         );
136
-        EE_Registry::$i18n_js_strings['ans_save_success']      = esc_html__(
136
+        EE_Registry::$i18n_js_strings['ans_save_success'] = esc_html__(
137 137
             'The new state was successfully saved to the database.',
138 138
             'event_espresso'
139 139
         );
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
     public static function wp_enqueue_scripts()
152 152
     {
153 153
         if (apply_filters('EED_Single_Page_Checkout__SPCO_active', false)) {
154
-            wp_register_script('add_new_state', ANS_ASSETS_URL . 'add_new_state.js',
154
+            wp_register_script('add_new_state', ANS_ASSETS_URL.'add_new_state.js',
155 155
                 array('espresso_core', 'single_page_checkout'), EVENT_ESPRESSO_VERSION, true);
156 156
             wp_enqueue_script('add_new_state');
157 157
         }
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
             $new_state_submit_id = str_replace('state', 'new_state', $input->html_id());
195 195
             $country_options     = array();
196 196
             $countries           = EEM_Country::instance()->get_all_countries();
197
-            if (! empty($countries)) {
197
+            if ( ! empty($countries)) {
198 198
                 foreach ($countries as $country) {
199 199
                     if ($country instanceof EE_Country) {
200 200
                         $country_options[$country->ID()] = $country->name();
@@ -231,10 +231,10 @@  discard block
 block discarded – undo
231 231
                                     '',
232 232
                                     esc_html__('click here to add a new state/province', 'event_espresso'),
233 233
                                     '',
234
-                                    'display-' . $input->html_id(),
234
+                                    'display-'.$input->html_id(),
235 235
                                     'ee-form-add-new-state-lnk display-the-hidden smaller-text hide-if-no-js',
236 236
                                     '',
237
-                                    'data-target="' . $input->html_id() . '"'
237
+                                    'data-target="'.$input->html_id().'"'
238 238
                                 )
239 239
                             )
240 240
                         ),
@@ -242,31 +242,31 @@  discard block
 block discarded – undo
242 242
                         'add_new_state_micro_form'    => new EE_Form_Section_HTML(
243 243
                             apply_filters(
244 244
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_micro_form',
245
-                                EEH_HTML::div('', $input->html_id() . '-dv', 'ee-form-add-new-state-dv',
246
-                                    'display: none;') .
245
+                                EEH_HTML::div('', $input->html_id().'-dv', 'ee-form-add-new-state-dv',
246
+                                    'display: none;').
247 247
                                 EEH_HTML::h6(
248 248
                                     esc_html__(
249 249
                                         'Is your state/province missing from the dropdown menu above? You can add it by completing the following steps:',
250 250
                                         'event_espresso'
251 251
                                     )
252
-                                ) .
253
-                                EEH_HTML::ul() .
252
+                                ).
253
+                                EEH_HTML::ul().
254 254
                                 EEH_HTML::li(
255 255
                                     esc_html__(
256 256
                                         'first select the Country that your State/Province belongs to',
257 257
                                         'event_espresso'
258 258
                                     )
259
-                                ) .
259
+                                ).
260 260
                                 EEH_HTML::li(
261 261
                                     esc_html__('enter the name of your State/Province', 'event_espresso')
262
-                                ) .
262
+                                ).
263 263
                                 EEH_HTML::li(
264 264
                                     esc_html__(
265 265
                                         'enter a two to six letter abbreviation for the name of your State/Province',
266 266
                                         'event_espresso'
267 267
                                     )
268
-                                ) .
269
-                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')) .
268
+                                ).
269
+                                EEH_HTML::li(esc_html__('click the ADD button', 'event_espresso')).
270 270
                                 EEH_HTML::ulx()
271 271
                             )
272 272
                         ),
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
                                     'state',
280 280
                                     'nsmf_new_state_country', $input->html_id()
281 281
                                 ),
282
-                                'html_class'      => $input->html_class() . ' new-state-country',
282
+                                'html_class'      => $input->html_class().' new-state-country',
283 283
                                 'html_label_text' => esc_html__('New State/Province Country', 'event_espresso'),
284 284
                                 'default'         => EE_Registry::instance()->REQ->get($country_name, ''),
285 285
                                 'required'        => false,
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
                                     'state',
294 294
                                     'nsmf_new_state_name', $input->html_id()
295 295
                                 ),
296
-                                'html_class'      => $input->html_class() . ' new-state-state',
296
+                                'html_class'      => $input->html_class().' new-state-state',
297 297
                                 'html_label_text' => esc_html__('New State/Province Name',
298 298
                                     'event_espresso'),
299 299
                                 'default'         => EE_Registry::instance()->REQ->get($state_name, ''),
@@ -307,11 +307,11 @@  discard block
 block discarded – undo
307 307
                                 'html_name'             => $abbrv_name,
308 308
                                 'html_id'               => str_replace('state', 'nsmf_new_state_abbrv',
309 309
                                     $input->html_id()),
310
-                                'html_class'            => $input->html_class() . ' new-state-abbrv',
310
+                                'html_class'            => $input->html_class().' new-state-abbrv',
311 311
                                 'html_label_text'       => esc_html__(
312 312
                                                                'New State/Province Abbreviation',
313 313
                                                                'event_espresso'
314
-                                                           ) . ' *',
314
+                                                           ).' *',
315 315
                                 'html_other_attributes' => 'size="24"',
316 316
                                 'default'               => EE_Registry::instance()->REQ->get($abbrv_name, ''),
317 317
                                 'required'              => false,
@@ -321,15 +321,15 @@  discard block
 block discarded – undo
321 321
                         'add_new_state_submit_button' => new EE_Form_Section_HTML(
322 322
                             apply_filters(
323 323
                                 'FHEE__EED_Add_New_State__display_add_new_state_micro_form__add_new_state_submit_button',
324
-                                EEH_HTML::nbsp(3) .
324
+                                EEH_HTML::nbsp(3).
325 325
                                 EEH_HTML::link(
326 326
                                     '',
327 327
                                     esc_html__('ADD', 'event_espresso'),
328 328
                                     '',
329
-                                    'submit-' . $new_state_submit_id,
329
+                                    'submit-'.$new_state_submit_id,
330 330
                                     'ee-form-add-new-state-submit button button-secondary',
331 331
                                     '',
332
-                                    'data-target="' . $new_state_submit_id . '"'
332
+                                    'data-target="'.$new_state_submit_id.'"'
333 333
                                 )
334 334
                             )
335 335
                         ),
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
                                 EEH_HTML::div('', '', 'small-text')
343 343
                                 .
344 344
                                 EEH_HTML::strong(
345
-                                    '* ' .
345
+                                    '* '.
346 346
                                     esc_html__(
347 347
                                         'Don\'t know your State/Province Abbreviation?',
348 348
                                         'event_espresso'
@@ -375,10 +375,10 @@  discard block
 block discarded – undo
375 375
                                     '',
376 376
                                     esc_html__('cancel new State/Province', 'event_espresso'),
377 377
                                     '',
378
-                                    'hide-' . $input->html_id(),
378
+                                    'hide-'.$input->html_id(),
379 379
                                     'ee-form-cancel-new-state-lnk smaller-text',
380 380
                                     '',
381
-                                    'data-target="' . $input->html_id() . '"'
381
+                                    'data-target="'.$input->html_id().'"'
382 382
                                 )
383 383
                                 .
384 384
                                 EEH_HTML::divx()
@@ -524,27 +524,27 @@  discard block
 block discarded – undo
524 524
     public static function save_new_state_to_db($props_n_values = array())
525 525
     {
526 526
         $existing_state = EEM_State::instance()->get_all(array($props_n_values, 'limit' => 1));
527
-        if (! empty($existing_state)) {
527
+        if ( ! empty($existing_state)) {
528 528
             return array_pop($existing_state);
529 529
         }
530 530
         $new_state = EE_State::new_instance($props_n_values);
531 531
         if ($new_state instanceof EE_State) {
532 532
             // if not non-ajax admin
533
-            $new_state_key    = 'new-state-added-' . $new_state->country_iso() . '-' . $new_state->abbrev();
533
+            $new_state_key    = 'new-state-added-'.$new_state->country_iso().'-'.$new_state->abbrev();
534 534
             $new_state_notice = sprintf(
535 535
                 esc_html__(
536 536
                     'A new State named "%1$s (%2$s)" was dynamically added from an Event Espresso form for the Country of "%3$s".%5$sTo verify, edit, and/or delete this new State, please go to the %4$s and update the States / Provinces section.%5$sCheck "Yes" to have this new State added to dropdown select lists in forms.',
537 537
                     'event_espresso'
538 538
                 ),
539
-                '<b>' . $new_state->name() . '</b>',
540
-                '<b>' . $new_state->abbrev() . '</b>',
541
-                '<b>' . $new_state->country()->name() . '</b>',
542
-                '<a href="' . add_query_arg(array(
539
+                '<b>'.$new_state->name().'</b>',
540
+                '<b>'.$new_state->abbrev().'</b>',
541
+                '<b>'.$new_state->country()->name().'</b>',
542
+                '<a href="'.add_query_arg(array(
543 543
                     'page'    => 'espresso_general_settings',
544 544
                     'action'  => 'country_settings',
545 545
                     'country' => $new_state->country_iso(),
546
-                ), admin_url('admin.php')) . '">' . esc_html__('Event Espresso - General Settings > Countries Tab',
547
-                    'event_espresso') . '</a>',
546
+                ), admin_url('admin.php')).'">'.esc_html__('Event Espresso - General Settings > Countries Tab',
547
+                    'event_espresso').'</a>',
548 548
                 '<br />'
549 549
             );
550 550
             EE_Error::add_persistent_admin_notice($new_state_key, $new_state_notice);
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
      */
570 570
     public static function update_country_settings($CNT_ISO = '', $STA_ID = '', $cols_n_values = array())
571 571
     {
572
-        if (! $CNT_ISO) {
572
+        if ( ! $CNT_ISO) {
573 573
             EE_Error::add_error(
574 574
                 esc_html__('An invalid or missing Country ISO Code was received.', 'event_espresso'),
575 575
                 __FILE__,
@@ -579,13 +579,13 @@  discard block
 block discarded – undo
579 579
         }
580 580
         $STA_abbrev = is_array($cols_n_values) && isset($cols_n_values['STA_abbrev']) ? $cols_n_values['STA_abbrev']
581 581
             : false;
582
-        if (! $STA_abbrev && ! empty($STA_ID)) {
582
+        if ( ! $STA_abbrev && ! empty($STA_ID)) {
583 583
             $state = EEM_State::instance()->get_one_by_ID($STA_ID);
584 584
             if ($state instanceof EE_State) {
585 585
                 $STA_abbrev = $state->abbrev();
586 586
             }
587 587
         }
588
-        if (! $STA_abbrev) {
588
+        if ( ! $STA_abbrev) {
589 589
             EE_Error::add_error(
590 590
                 esc_html__('An invalid or missing State Abbreviation was received.', 'event_espresso'),
591 591
                 __FILE__,
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
                 __LINE__
594 594
             );
595 595
         }
596
-        EE_Error::dismiss_persistent_admin_notice($CNT_ISO . '-' . $STA_abbrev, true, true);
596
+        EE_Error::dismiss_persistent_admin_notice($CNT_ISO.'-'.$STA_abbrev, true, true);
597 597
     }
598 598
 
599 599
 
@@ -621,15 +621,15 @@  discard block
 block discarded – undo
621 621
             && $question->type() === EEM_Question::QST_type_state
622 622
         ) {
623 623
             $STA_ID = $answer->value();
624
-            if (! empty($STA_ID)) {
624
+            if ( ! empty($STA_ID)) {
625 625
                 $state = EEM_State::instance()->get_one_by_ID($STA_ID);
626 626
                 if ($state instanceof EE_State) {
627 627
                     $country = $state->country();
628 628
                     if ($country instanceof EE_Country) {
629
-                        if (! isset($state_options[$country->name()])) {
629
+                        if ( ! isset($state_options[$country->name()])) {
630 630
                             $state_options[$country->name()] = array();
631 631
                         }
632
-                        if (! isset($state_options[$country->name()][$STA_ID])) {
632
+                        if ( ! isset($state_options[$country->name()][$STA_ID])) {
633 633
                             $state_options[$country->name()][$STA_ID] = $state->name();
634 634
                         }
635 635
                     }
@@ -665,10 +665,10 @@  discard block
 block discarded – undo
665 665
                === EEM_Question::QST_type_country
666 666
         ) {
667 667
             $CNT_ISO = $answer->value();
668
-            if (! empty($CNT_ISO)) {
668
+            if ( ! empty($CNT_ISO)) {
669 669
                 $country = EEM_Country::instance()->get_one_by_ID($CNT_ISO);
670 670
                 if ($country instanceof EE_Country) {
671
-                    if (! isset($country_options[$CNT_ISO])) {
671
+                    if ( ! isset($country_options[$CNT_ISO])) {
672 672
                         $country_options[$CNT_ISO] = $country->name();
673 673
                     }
674 674
                 }
Please login to merge, or discard this patch.
core/libraries/rest_api/calculations/Event.php 2 patches
Indentation   +401 added lines, -401 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
  * @since                 $VID:$
20 20
  */
21 21
 if (! defined('EVENT_ESPRESSO_VERSION')) {
22
-    exit('No direct script access allowed');
22
+	exit('No direct script access allowed');
23 23
 }
24 24
 
25 25
 
@@ -27,404 +27,404 @@  discard block
 block discarded – undo
27 27
 class Event extends Calculations_Base
28 28
 {
29 29
 
30
-    /**
31
-     * Calculates the total spaces on the event (not subtracting sales, but taking
32
-     * sales into account; so this is the optimum sales that CAN still be achieved)
33
-     * See EE_Event::total_available_spaces( true );
34
-     *
35
-     * @param array            $wpdb_row
36
-     * @param \WP_REST_Request $request
37
-     * @param Base             $controller
38
-     * @return int
39
-     * @throws EE_Error
40
-     */
41
-    public static function optimumSalesAtStart($wpdb_row, $request, $controller)
42
-    {
43
-        $event_obj = null;
44
-        if (Event::wpdbRowHasEventId($wpdb_row)) {
45
-            $event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
46
-        }
47
-        if ($event_obj instanceof EE_Event) {
48
-            return $event_obj->total_available_spaces();
49
-        }
50
-        throw new EE_Error(
51
-            sprintf(
52
-                __(
53
-                    // @codingStandardsIgnoreStart
54
-                    'Cannot calculate optimum_sales_at_start because the event with ID %1$s (from database row %2$s) was not found',
55
-                    // @codingStandardsIgnoreEnd
56
-                    'event_espresso'
57
-                ),
58
-                $wpdb_row['Event_CPT.ID'],
59
-                print_r($wpdb_row, true)
60
-            )
61
-        );
62
-    }
63
-
64
-
65
-
66
-    /**
67
-     * Calculates the total spaces on the event (ignoring all sales; so this is the optimum
68
-     * sales that COULD have been achieved)
69
-     * See EE_Event::total_available_spaces( true );
70
-     *
71
-     * @param array            $wpdb_row
72
-     * @param \WP_REST_Request $request
73
-     * @param Base             $controller
74
-     * @return int
75
-     * @throws EE_Error
76
-     */
77
-    public static function optimumSalesNow($wpdb_row, $request, $controller)
78
-    {
79
-        $event_obj = null;
80
-        if (Event::wpdbRowHasEventId($wpdb_row)) {
81
-            $event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
82
-        }
83
-        if ($event_obj instanceof EE_Event) {
84
-            return $event_obj->total_available_spaces(true);
85
-        }
86
-        throw new EE_Error(
87
-            sprintf(
88
-                __(
89
-                    // @codingStandardsIgnoreStart
90
-                    'Cannot calculate optimum_sales_now because the event with ID %1$s (from database row %2$s) was not found',
91
-                    // @codingStandardsIgnoreEnd
92
-                    'event_espresso'
93
-                ),
94
-                $wpdb_row['Event_CPT.ID'],
95
-                print_r($wpdb_row, true)
96
-            )
97
-        );
98
-    }
99
-
100
-
101
-
102
-    /**
103
-     * Like optimum_sales_now, but minus total sales so far.
104
-     * See EE_Event::spaces_remaining_for_sale( true );
105
-     *
106
-     * @param array            $wpdb_row
107
-     * @param \WP_REST_Request $request
108
-     * @param Base             $controller
109
-     * @return int
110
-     * @throws EE_Error
111
-     */
112
-    public static function spacesRemaining($wpdb_row, $request, $controller)
113
-    {
114
-        $event_obj = null;
115
-        if (Event::wpdbRowHasEventId($wpdb_row)) {
116
-            $event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
117
-        }
118
-        if ($event_obj instanceof EE_Event) {
119
-            return $event_obj->spaces_remaining_for_sale();
120
-        }
121
-        throw new EE_Error(
122
-            sprintf(
123
-                __(
124
-                    // @codingStandardsIgnoreStart
125
-                    'Cannot calculate spaces_remaining because the event with ID %1$s (from database row %2$s) was not found',
126
-                    // @codingStandardsIgnoreEnd
127
-                    'event_espresso'
128
-                ),
129
-                $wpdb_row['Event_CPT.ID'],
130
-                print_r($wpdb_row, true)
131
-            )
132
-        );
133
-    }
134
-
135
-
136
-
137
-    /**
138
-     * Counts the number of approved registrations for this event (regardless
139
-     * of how many datetimes each registrations' ticket purchase is for)
140
-     *
141
-     * @param array            $wpdb_row
142
-     * @param \WP_REST_Request $request
143
-     * @param Base             $controller
144
-     * @return int
145
-     * @throws EE_Error
146
-     */
147
-    public static function spotsTaken($wpdb_row, $request, $controller)
148
-    {
149
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
150
-            throw new EE_Error(
151
-                sprintf(
152
-                    __(
153
-                        // @codingStandardsIgnoreStart
154
-                        'Cannot calculate spots_taken because the database row %1$s does not have a valid entry for "Event_CPT.ID"',
155
-                        // @codingStandardsIgnoreEnd
156
-                        'event_espresso'
157
-                    ),
158
-                    print_r($wpdb_row, true)
159
-                )
160
-            );
161
-        }
162
-        return EEM_Registration::instance()->count(
163
-            array(
164
-                array(
165
-                    'EVT_ID' => $wpdb_row['Event_CPT.ID'],
166
-                    'STS_ID' => EEM_Registration::status_id_approved,
167
-                ),
168
-            ),
169
-            'REG_ID',
170
-            true
171
-        );
172
-    }
173
-
174
-
175
-
176
-    /**
177
-     * Counts the number of pending-payment registrations for this event (regardless
178
-     * of how many datetimes each registrations' ticket purchase is for)
179
-     *
180
-     * @param array            $wpdb_row
181
-     * @param \WP_REST_Request $request
182
-     * @param Base             $controller
183
-     * @return int
184
-     * @throws EE_Error
185
-     * @throws RestException
186
-     */
187
-    public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
188
-    {
189
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
190
-            throw new EE_Error(
191
-                sprintf(
192
-                    __(
193
-                        // @codingStandardsIgnoreStart
194
-                        'Cannot calculate spots_taken_pending_payment because the database row %1$s does not have an entry for "Event_CPT.ID"',
195
-                        // @codingStandardsIgnoreEnd
196
-                        'event_espresso'
197
-                    ),
198
-                    print_r($wpdb_row, true)
199
-                )
200
-            );
201
-        }
202
-        self::verifyCurrentUserCan('ee_read_registrations', 'spots_taken_pending_payment');
203
-        return EEM_Registration::instance()->count(
204
-            array(
205
-                array(
206
-                    'EVT_ID' => $wpdb_row['Event_CPT.ID'],
207
-                    'STS_ID' => EEM_Registration::status_id_pending_payment,
208
-                ),
209
-            ),
210
-            'REG_ID',
211
-            true
212
-        );
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * Counts all the registrations who have checked into one of this events' datetimes
219
-     * See EE_Event::total_available_spaces( false );
220
-     *
221
-     * @param array            $wpdb_row
222
-     * @param \WP_REST_Request $request
223
-     * @param Base             $controller
224
-     * @return int|null if permission denied
225
-     * @throws EE_Error
226
-     * @throws RestException
227
-     */
228
-    public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
229
-    {
230
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
231
-            throw new EE_Error(
232
-                sprintf(
233
-                    __(
234
-                        // @codingStandardsIgnoreStart
235
-                        'Cannot calculate registrations_checked_in_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
236
-                        // @codingStandardsIgnoreEnd
237
-                        'event_espresso'
238
-                    ),
239
-                    print_r($wpdb_row, true)
240
-                )
241
-            );
242
-        }
243
-        self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_in_count');
244
-        return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], true);
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * Counts all the registrations who have checked out of one of this events' datetimes
251
-     * See EE_Event::total_available_spaces( false );
252
-     *
253
-     * @param array            $wpdb_row
254
-     * @param \WP_REST_Request $request
255
-     * @param Base             $controller
256
-     * @return int
257
-     * @throws EE_Error
258
-     * @throws RestException
259
-     */
260
-    public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
261
-    {
262
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
263
-            throw new EE_Error(
264
-                sprintf(
265
-                    __(
266
-                        // @codingStandardsIgnoreStart
267
-                        'Cannot calculate registrations_checked_out_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
268
-                        // @codingStandardsIgnoreEnd
269
-                        'event_espresso'
270
-                    ),
271
-                    print_r($wpdb_row, true)
272
-                )
273
-            );
274
-        }
275
-        self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_out_count');
276
-        return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], false);
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * Gets the thumbnail image
283
-     *
284
-     * @param array            $wpdb_row
285
-     * @param \WP_REST_Request $request
286
-     * @param Base             $controller
287
-     * @return array
288
-     * @throws EE_Error
289
-     */
290
-    public static function imageThumbnail($wpdb_row, $request, $controller)
291
-    {
292
-        return self::calculateImageData($wpdb_row, 'thumbnail');
293
-    }
294
-
295
-
296
-
297
-    /**
298
-     * Gets the medium image
299
-     *
300
-     * @param array            $wpdb_row
301
-     * @param \WP_REST_Request $request
302
-     * @param Base             $controller
303
-     * @return array
304
-     * @throws EE_Error
305
-     */
306
-    public static function imageMedium($wpdb_row, $request, $controller)
307
-    {
308
-        return self::calculateImageData($wpdb_row, 'medium');
309
-    }
310
-
311
-
312
-
313
-    /**
314
-     * Gets the medium-large image
315
-     *
316
-     * @param array            $wpdb_row
317
-     * @param \WP_REST_Request $request
318
-     * @param Base             $controller
319
-     * @return array
320
-     * @throws EE_Error
321
-     */
322
-    public static function imageMediumLarge($wpdb_row, $request, $controller)
323
-    {
324
-        return self::calculateImageData($wpdb_row, 'medium_large');
325
-    }
326
-
327
-
328
-
329
-    /**
330
-     * Gets the large image
331
-     *
332
-     * @param array            $wpdb_row
333
-     * @param \WP_REST_Request $request
334
-     * @param Base             $controller
335
-     * @return array
336
-     * @throws EE_Error
337
-     */
338
-    public static function imageLarge($wpdb_row, $request, $controller)
339
-    {
340
-        return self::calculateImageData($wpdb_row, 'large');
341
-    }
342
-
343
-
344
-
345
-    /**
346
-     * Gets the post-thumbnail image
347
-     *
348
-     * @param array            $wpdb_row
349
-     * @param \WP_REST_Request $request
350
-     * @param Base             $controller
351
-     * @return array
352
-     * @throws EE_Error
353
-     */
354
-    public static function imagePostThumbnail($wpdb_row, $request, $controller)
355
-    {
356
-        return self::calculateImageData($wpdb_row, 'post-thumbnail');
357
-    }
358
-
359
-
360
-
361
-    /**
362
-     * Gets the full size image
363
-     *
364
-     * @param array            $wpdb_row
365
-     * @param \WP_REST_Request $request
366
-     * @param Base             $controller
367
-     * @return array
368
-     * @throws EE_Error
369
-     */
370
-    public static function imageFull($wpdb_row, $request, $controller)
371
-    {
372
-        return self::calculateImageData($wpdb_row, 'full');
373
-    }
374
-
375
-
376
-
377
-    /**
378
-     * Gets image specs and formats them for the display in the API,
379
-     * according to the image size requested
380
-     *
381
-     * @param array    $wpdb_row
382
-     * @param string $image_size one of these: thumbnail, medium, medium_large, large, post-thumbnail, full
383
-     * @return array|false if no such image exists. If array it will have keys 'url', 'width', 'height' and 'original'
384
-     * @throws EE_Error
385
-     */
386
-    protected static function calculateImageData($wpdb_row, $image_size)
387
-    {
388
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
389
-            throw new EE_Error(
390
-                sprintf(
391
-                    __(
392
-                    // @codingStandardsIgnoreStart
393
-                        'Cannot calculate image because the database row %1$s does not have an entry for "Event_CPT.ID"',
394
-                        // @codingStandardsIgnoreEnd
395
-                        'event_espresso'
396
-                    ),
397
-                    print_r($wpdb_row, true)
398
-                )
399
-            );
400
-        }
401
-        $EVT_ID = $wpdb_row['Event_CPT.ID'];
402
-        $attachment_id = get_post_thumbnail_id($EVT_ID);
403
-        $data = wp_get_attachment_image_src($attachment_id, $image_size);
404
-        if (! $data) {
405
-            return null;
406
-        }
407
-        $generated = true;
408
-        if (isset($data[3])) {
409
-            $generated = $data[3];
410
-        }
411
-        return array(
412
-            'url'       => $data[0],
413
-            'width'     => $data[1],
414
-            'height'    => $data[2],
415
-            'generated' => $generated,
416
-        );
417
-    }
418
-
419
-
420
-
421
-    /**
422
-     * Returns true if the array of data contains 'Event_CPT.ID'. False otherwise
423
-     * @param array $wpdb_row
424
-     * @return bool
425
-     */
426
-    protected static function wpdbRowHasEventId($wpdb_row)
427
-    {
428
-        return (is_array($wpdb_row) && isset($wpdb_row['Event_CPT.ID']) && absint($wpdb_row['Event_CPT.ID']));
429
-    }
30
+	/**
31
+	 * Calculates the total spaces on the event (not subtracting sales, but taking
32
+	 * sales into account; so this is the optimum sales that CAN still be achieved)
33
+	 * See EE_Event::total_available_spaces( true );
34
+	 *
35
+	 * @param array            $wpdb_row
36
+	 * @param \WP_REST_Request $request
37
+	 * @param Base             $controller
38
+	 * @return int
39
+	 * @throws EE_Error
40
+	 */
41
+	public static function optimumSalesAtStart($wpdb_row, $request, $controller)
42
+	{
43
+		$event_obj = null;
44
+		if (Event::wpdbRowHasEventId($wpdb_row)) {
45
+			$event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
46
+		}
47
+		if ($event_obj instanceof EE_Event) {
48
+			return $event_obj->total_available_spaces();
49
+		}
50
+		throw new EE_Error(
51
+			sprintf(
52
+				__(
53
+					// @codingStandardsIgnoreStart
54
+					'Cannot calculate optimum_sales_at_start because the event with ID %1$s (from database row %2$s) was not found',
55
+					// @codingStandardsIgnoreEnd
56
+					'event_espresso'
57
+				),
58
+				$wpdb_row['Event_CPT.ID'],
59
+				print_r($wpdb_row, true)
60
+			)
61
+		);
62
+	}
63
+
64
+
65
+
66
+	/**
67
+	 * Calculates the total spaces on the event (ignoring all sales; so this is the optimum
68
+	 * sales that COULD have been achieved)
69
+	 * See EE_Event::total_available_spaces( true );
70
+	 *
71
+	 * @param array            $wpdb_row
72
+	 * @param \WP_REST_Request $request
73
+	 * @param Base             $controller
74
+	 * @return int
75
+	 * @throws EE_Error
76
+	 */
77
+	public static function optimumSalesNow($wpdb_row, $request, $controller)
78
+	{
79
+		$event_obj = null;
80
+		if (Event::wpdbRowHasEventId($wpdb_row)) {
81
+			$event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
82
+		}
83
+		if ($event_obj instanceof EE_Event) {
84
+			return $event_obj->total_available_spaces(true);
85
+		}
86
+		throw new EE_Error(
87
+			sprintf(
88
+				__(
89
+					// @codingStandardsIgnoreStart
90
+					'Cannot calculate optimum_sales_now because the event with ID %1$s (from database row %2$s) was not found',
91
+					// @codingStandardsIgnoreEnd
92
+					'event_espresso'
93
+				),
94
+				$wpdb_row['Event_CPT.ID'],
95
+				print_r($wpdb_row, true)
96
+			)
97
+		);
98
+	}
99
+
100
+
101
+
102
+	/**
103
+	 * Like optimum_sales_now, but minus total sales so far.
104
+	 * See EE_Event::spaces_remaining_for_sale( true );
105
+	 *
106
+	 * @param array            $wpdb_row
107
+	 * @param \WP_REST_Request $request
108
+	 * @param Base             $controller
109
+	 * @return int
110
+	 * @throws EE_Error
111
+	 */
112
+	public static function spacesRemaining($wpdb_row, $request, $controller)
113
+	{
114
+		$event_obj = null;
115
+		if (Event::wpdbRowHasEventId($wpdb_row)) {
116
+			$event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
117
+		}
118
+		if ($event_obj instanceof EE_Event) {
119
+			return $event_obj->spaces_remaining_for_sale();
120
+		}
121
+		throw new EE_Error(
122
+			sprintf(
123
+				__(
124
+					// @codingStandardsIgnoreStart
125
+					'Cannot calculate spaces_remaining because the event with ID %1$s (from database row %2$s) was not found',
126
+					// @codingStandardsIgnoreEnd
127
+					'event_espresso'
128
+				),
129
+				$wpdb_row['Event_CPT.ID'],
130
+				print_r($wpdb_row, true)
131
+			)
132
+		);
133
+	}
134
+
135
+
136
+
137
+	/**
138
+	 * Counts the number of approved registrations for this event (regardless
139
+	 * of how many datetimes each registrations' ticket purchase is for)
140
+	 *
141
+	 * @param array            $wpdb_row
142
+	 * @param \WP_REST_Request $request
143
+	 * @param Base             $controller
144
+	 * @return int
145
+	 * @throws EE_Error
146
+	 */
147
+	public static function spotsTaken($wpdb_row, $request, $controller)
148
+	{
149
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
150
+			throw new EE_Error(
151
+				sprintf(
152
+					__(
153
+						// @codingStandardsIgnoreStart
154
+						'Cannot calculate spots_taken because the database row %1$s does not have a valid entry for "Event_CPT.ID"',
155
+						// @codingStandardsIgnoreEnd
156
+						'event_espresso'
157
+					),
158
+					print_r($wpdb_row, true)
159
+				)
160
+			);
161
+		}
162
+		return EEM_Registration::instance()->count(
163
+			array(
164
+				array(
165
+					'EVT_ID' => $wpdb_row['Event_CPT.ID'],
166
+					'STS_ID' => EEM_Registration::status_id_approved,
167
+				),
168
+			),
169
+			'REG_ID',
170
+			true
171
+		);
172
+	}
173
+
174
+
175
+
176
+	/**
177
+	 * Counts the number of pending-payment registrations for this event (regardless
178
+	 * of how many datetimes each registrations' ticket purchase is for)
179
+	 *
180
+	 * @param array            $wpdb_row
181
+	 * @param \WP_REST_Request $request
182
+	 * @param Base             $controller
183
+	 * @return int
184
+	 * @throws EE_Error
185
+	 * @throws RestException
186
+	 */
187
+	public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
188
+	{
189
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
190
+			throw new EE_Error(
191
+				sprintf(
192
+					__(
193
+						// @codingStandardsIgnoreStart
194
+						'Cannot calculate spots_taken_pending_payment because the database row %1$s does not have an entry for "Event_CPT.ID"',
195
+						// @codingStandardsIgnoreEnd
196
+						'event_espresso'
197
+					),
198
+					print_r($wpdb_row, true)
199
+				)
200
+			);
201
+		}
202
+		self::verifyCurrentUserCan('ee_read_registrations', 'spots_taken_pending_payment');
203
+		return EEM_Registration::instance()->count(
204
+			array(
205
+				array(
206
+					'EVT_ID' => $wpdb_row['Event_CPT.ID'],
207
+					'STS_ID' => EEM_Registration::status_id_pending_payment,
208
+				),
209
+			),
210
+			'REG_ID',
211
+			true
212
+		);
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * Counts all the registrations who have checked into one of this events' datetimes
219
+	 * See EE_Event::total_available_spaces( false );
220
+	 *
221
+	 * @param array            $wpdb_row
222
+	 * @param \WP_REST_Request $request
223
+	 * @param Base             $controller
224
+	 * @return int|null if permission denied
225
+	 * @throws EE_Error
226
+	 * @throws RestException
227
+	 */
228
+	public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
229
+	{
230
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
231
+			throw new EE_Error(
232
+				sprintf(
233
+					__(
234
+						// @codingStandardsIgnoreStart
235
+						'Cannot calculate registrations_checked_in_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
236
+						// @codingStandardsIgnoreEnd
237
+						'event_espresso'
238
+					),
239
+					print_r($wpdb_row, true)
240
+				)
241
+			);
242
+		}
243
+		self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_in_count');
244
+		return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], true);
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * Counts all the registrations who have checked out of one of this events' datetimes
251
+	 * See EE_Event::total_available_spaces( false );
252
+	 *
253
+	 * @param array            $wpdb_row
254
+	 * @param \WP_REST_Request $request
255
+	 * @param Base             $controller
256
+	 * @return int
257
+	 * @throws EE_Error
258
+	 * @throws RestException
259
+	 */
260
+	public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
261
+	{
262
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
263
+			throw new EE_Error(
264
+				sprintf(
265
+					__(
266
+						// @codingStandardsIgnoreStart
267
+						'Cannot calculate registrations_checked_out_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
268
+						// @codingStandardsIgnoreEnd
269
+						'event_espresso'
270
+					),
271
+					print_r($wpdb_row, true)
272
+				)
273
+			);
274
+		}
275
+		self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_out_count');
276
+		return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], false);
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * Gets the thumbnail image
283
+	 *
284
+	 * @param array            $wpdb_row
285
+	 * @param \WP_REST_Request $request
286
+	 * @param Base             $controller
287
+	 * @return array
288
+	 * @throws EE_Error
289
+	 */
290
+	public static function imageThumbnail($wpdb_row, $request, $controller)
291
+	{
292
+		return self::calculateImageData($wpdb_row, 'thumbnail');
293
+	}
294
+
295
+
296
+
297
+	/**
298
+	 * Gets the medium image
299
+	 *
300
+	 * @param array            $wpdb_row
301
+	 * @param \WP_REST_Request $request
302
+	 * @param Base             $controller
303
+	 * @return array
304
+	 * @throws EE_Error
305
+	 */
306
+	public static function imageMedium($wpdb_row, $request, $controller)
307
+	{
308
+		return self::calculateImageData($wpdb_row, 'medium');
309
+	}
310
+
311
+
312
+
313
+	/**
314
+	 * Gets the medium-large image
315
+	 *
316
+	 * @param array            $wpdb_row
317
+	 * @param \WP_REST_Request $request
318
+	 * @param Base             $controller
319
+	 * @return array
320
+	 * @throws EE_Error
321
+	 */
322
+	public static function imageMediumLarge($wpdb_row, $request, $controller)
323
+	{
324
+		return self::calculateImageData($wpdb_row, 'medium_large');
325
+	}
326
+
327
+
328
+
329
+	/**
330
+	 * Gets the large image
331
+	 *
332
+	 * @param array            $wpdb_row
333
+	 * @param \WP_REST_Request $request
334
+	 * @param Base             $controller
335
+	 * @return array
336
+	 * @throws EE_Error
337
+	 */
338
+	public static function imageLarge($wpdb_row, $request, $controller)
339
+	{
340
+		return self::calculateImageData($wpdb_row, 'large');
341
+	}
342
+
343
+
344
+
345
+	/**
346
+	 * Gets the post-thumbnail image
347
+	 *
348
+	 * @param array            $wpdb_row
349
+	 * @param \WP_REST_Request $request
350
+	 * @param Base             $controller
351
+	 * @return array
352
+	 * @throws EE_Error
353
+	 */
354
+	public static function imagePostThumbnail($wpdb_row, $request, $controller)
355
+	{
356
+		return self::calculateImageData($wpdb_row, 'post-thumbnail');
357
+	}
358
+
359
+
360
+
361
+	/**
362
+	 * Gets the full size image
363
+	 *
364
+	 * @param array            $wpdb_row
365
+	 * @param \WP_REST_Request $request
366
+	 * @param Base             $controller
367
+	 * @return array
368
+	 * @throws EE_Error
369
+	 */
370
+	public static function imageFull($wpdb_row, $request, $controller)
371
+	{
372
+		return self::calculateImageData($wpdb_row, 'full');
373
+	}
374
+
375
+
376
+
377
+	/**
378
+	 * Gets image specs and formats them for the display in the API,
379
+	 * according to the image size requested
380
+	 *
381
+	 * @param array    $wpdb_row
382
+	 * @param string $image_size one of these: thumbnail, medium, medium_large, large, post-thumbnail, full
383
+	 * @return array|false if no such image exists. If array it will have keys 'url', 'width', 'height' and 'original'
384
+	 * @throws EE_Error
385
+	 */
386
+	protected static function calculateImageData($wpdb_row, $image_size)
387
+	{
388
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
389
+			throw new EE_Error(
390
+				sprintf(
391
+					__(
392
+					// @codingStandardsIgnoreStart
393
+						'Cannot calculate image because the database row %1$s does not have an entry for "Event_CPT.ID"',
394
+						// @codingStandardsIgnoreEnd
395
+						'event_espresso'
396
+					),
397
+					print_r($wpdb_row, true)
398
+				)
399
+			);
400
+		}
401
+		$EVT_ID = $wpdb_row['Event_CPT.ID'];
402
+		$attachment_id = get_post_thumbnail_id($EVT_ID);
403
+		$data = wp_get_attachment_image_src($attachment_id, $image_size);
404
+		if (! $data) {
405
+			return null;
406
+		}
407
+		$generated = true;
408
+		if (isset($data[3])) {
409
+			$generated = $data[3];
410
+		}
411
+		return array(
412
+			'url'       => $data[0],
413
+			'width'     => $data[1],
414
+			'height'    => $data[2],
415
+			'generated' => $generated,
416
+		);
417
+	}
418
+
419
+
420
+
421
+	/**
422
+	 * Returns true if the array of data contains 'Event_CPT.ID'. False otherwise
423
+	 * @param array $wpdb_row
424
+	 * @return bool
425
+	 */
426
+	protected static function wpdbRowHasEventId($wpdb_row)
427
+	{
428
+		return (is_array($wpdb_row) && isset($wpdb_row['Event_CPT.ID']) && absint($wpdb_row['Event_CPT.ID']));
429
+	}
430 430
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
  * @author                Mike Nelson
19 19
  * @since                 $VID:$
20 20
  */
21
-if (! defined('EVENT_ESPRESSO_VERSION')) {
21
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
22 22
     exit('No direct script access allowed');
23 23
 }
24 24
 
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
      */
147 147
     public static function spotsTaken($wpdb_row, $request, $controller)
148 148
     {
149
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
149
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
150 150
             throw new EE_Error(
151 151
                 sprintf(
152 152
                     __(
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
      */
187 187
     public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
188 188
     {
189
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
189
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
190 190
             throw new EE_Error(
191 191
                 sprintf(
192 192
                     __(
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
      */
228 228
     public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
229 229
     {
230
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
230
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
231 231
             throw new EE_Error(
232 232
                 sprintf(
233 233
                     __(
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
      */
260 260
     public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
261 261
     {
262
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
262
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
263 263
             throw new EE_Error(
264 264
                 sprintf(
265 265
                     __(
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
      */
386 386
     protected static function calculateImageData($wpdb_row, $image_size)
387 387
     {
388
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
388
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
389 389
             throw new EE_Error(
390 390
                 sprintf(
391 391
                     __(
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
         $EVT_ID = $wpdb_row['Event_CPT.ID'];
402 402
         $attachment_id = get_post_thumbnail_id($EVT_ID);
403 403
         $data = wp_get_attachment_image_src($attachment_id, $image_size);
404
-        if (! $data) {
404
+        if ( ! $data) {
405 405
             return null;
406 406
         }
407 407
         $generated = true;
Please login to merge, or discard this patch.
core/EE_Addon.core.php 2 patches
Indentation   +760 added lines, -760 removed lines patch added patch discarded remove patch
@@ -14,732 +14,732 @@  discard block
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    /**
18
-     * prefix to be added onto an addon's plugin slug to make a wp option name
19
-     * which will be used to store the plugin's activation history
20
-     */
21
-    const ee_addon_version_history_option_prefix = 'ee_version_history_';
22
-
23
-    /**
24
-     * @var $_version
25
-     * @type string
26
-     */
27
-    protected $_version = '';
28
-
29
-    /**
30
-     * @var $_min_core_version
31
-     * @type string
32
-     */
33
-    protected $_min_core_version = '';
34
-
35
-    /**
36
-     * derived from plugin 'main_file_path using plugin_basename()
37
-     *
38
-     * @type string $_plugin_basename
39
-     */
40
-    protected $_plugin_basename = '';
41
-
42
-    /**
43
-     * A non-internationalized name to identify this addon for use in URLs, etc
44
-     *
45
-     * @type string $_plugin_slug
46
-     */
47
-    protected $_plugin_slug = '';
48
-
49
-    /**
50
-     * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
51
-     *
52
-     * @type string _addon_name
53
-     */
54
-    protected $_addon_name = '';
55
-
56
-    /**
57
-     * one of the EE_System::req_type_* constants
58
-     *
59
-     * @type int $_req_type
60
-     */
61
-    protected $_req_type;
62
-
63
-    /**
64
-     * page slug to be used when generating the "Settings" link on the WP plugin page
65
-     *
66
-     * @type string $_plugin_action_slug
67
-     */
68
-    protected $_plugin_action_slug = '';
69
-
70
-    /**
71
-     * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
72
-     * that can be used for adding upgrading/marketing info
73
-     *
74
-     * @type array $_plugins_page_row
75
-     */
76
-    protected $_plugins_page_row = array();
77
-
78
-
79
-
80
-    /**
81
-     *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
82
-     *
83
-     * @type string
84
-     */
85
-    protected $_main_plugin_file;
86
-
87
-
88
-    /**
89
-     *    class constructor
90
-     */
91
-    public function __construct()
92
-    {
93
-        add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
94
-    }
95
-
96
-
97
-    /**
98
-     * @param mixed $version
99
-     */
100
-    public function set_version($version = null)
101
-    {
102
-        $this->_version = $version;
103
-    }
104
-
105
-
106
-    /**
107
-     * get__version
108
-     *
109
-     * @return string
110
-     */
111
-    public function version()
112
-    {
113
-        return $this->_version;
114
-    }
115
-
116
-
117
-    /**
118
-     * @param mixed $min_core_version
119
-     */
120
-    public function set_min_core_version($min_core_version = null)
121
-    {
122
-        $this->_min_core_version = $min_core_version;
123
-    }
124
-
125
-
126
-    /**
127
-     * get__min_core_version
128
-     *
129
-     * @return string
130
-     */
131
-    public function min_core_version()
132
-    {
133
-        return $this->_min_core_version;
134
-    }
135
-
136
-
137
-    /**
138
-     * Sets addon_name
139
-     *
140
-     * @param string $addon_name
141
-     * @return boolean
142
-     */
143
-    public function set_name($addon_name)
144
-    {
145
-        return $this->_addon_name = $addon_name;
146
-    }
147
-
148
-
149
-    /**
150
-     * Gets addon_name
151
-     *
152
-     * @return string
153
-     */
154
-    public function name()
155
-    {
156
-        return $this->_addon_name;
157
-    }
158
-
159
-
160
-    /**
161
-     * @return string
162
-     */
163
-    public function plugin_basename()
164
-    {
165
-
166
-        return $this->_plugin_basename;
167
-    }
168
-
169
-
170
-    /**
171
-     * @param string $plugin_basename
172
-     */
173
-    public function set_plugin_basename($plugin_basename)
174
-    {
175
-
176
-        $this->_plugin_basename = $plugin_basename;
177
-    }
178
-
179
-
180
-    /**
181
-     * @return string
182
-     */
183
-    public function plugin_slug()
184
-    {
185
-
186
-        return $this->_plugin_slug;
187
-    }
188
-
189
-
190
-    /**
191
-     * @param string $plugin_slug
192
-     */
193
-    public function set_plugin_slug($plugin_slug)
194
-    {
195
-
196
-        $this->_plugin_slug = $plugin_slug;
197
-    }
198
-
199
-
200
-    /**
201
-     * @return string
202
-     */
203
-    public function plugin_action_slug()
204
-    {
205
-
206
-        return $this->_plugin_action_slug;
207
-    }
208
-
209
-
210
-    /**
211
-     * @param string $plugin_action_slug
212
-     */
213
-    public function set_plugin_action_slug($plugin_action_slug)
214
-    {
215
-
216
-        $this->_plugin_action_slug = $plugin_action_slug;
217
-    }
218
-
219
-
220
-    /**
221
-     * @return array
222
-     */
223
-    public function get_plugins_page_row()
224
-    {
225
-
226
-        return $this->_plugins_page_row;
227
-    }
228
-
229
-
230
-    /**
231
-     * @param array $plugins_page_row
232
-     */
233
-    public function set_plugins_page_row($plugins_page_row = array())
234
-    {
235
-        // sigh.... check for example content that I stupidly merged to master and remove it if found
236
-        if (! is_array($plugins_page_row)
237
-            && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
238
-        ) {
239
-            $plugins_page_row = array();
240
-        }
241
-        $this->_plugins_page_row = (array) $plugins_page_row;
242
-    }
243
-
244
-
245
-    /**
246
-     * Called when EE core detects this addon has been activated for the first time.
247
-     * If the site isn't in maintenance mode, should setup the addon's database
248
-     *
249
-     * @return void
250
-     */
251
-    public function new_install()
252
-    {
253
-        $classname = get_class($this);
254
-        do_action("AHEE__{$classname}__new_install");
255
-        do_action('AHEE__EE_Addon__new_install', $this);
256
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
257
-        add_action(
258
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
259
-            array($this, 'initialize_db_if_no_migrations_required')
260
-        );
261
-    }
262
-
263
-
264
-    /**
265
-     * Called when EE core detects this addon has been reactivated. When this happens,
266
-     * it's good to just check that your data is still intact
267
-     *
268
-     * @return void
269
-     */
270
-    public function reactivation()
271
-    {
272
-        $classname = get_class($this);
273
-        do_action("AHEE__{$classname}__reactivation");
274
-        do_action('AHEE__EE_Addon__reactivation', $this);
275
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
276
-        add_action(
277
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
278
-            array($this, 'initialize_db_if_no_migrations_required')
279
-        );
280
-    }
281
-
282
-
283
-    /**
284
-     * Called when the registered deactivation hook for this addon fires.
285
-     * @throws EE_Error
286
-     */
287
-    public function deactivation()
288
-    {
289
-        $classname = get_class($this);
290
-        do_action("AHEE__{$classname}__deactivation");
291
-        do_action('AHEE__EE_Addon__deactivation', $this);
292
-        //check if the site no longer needs to be in maintenance mode
293
-        EE_Register_Addon::deregister($this->name());
294
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
295
-    }
296
-
297
-
298
-    /**
299
-     * Takes care of double-checking that we're not in maintenance mode, and then
300
-     * initializing this addon's necessary initial data. This is called by default on new activations
301
-     * and reactivations.
302
-     *
303
-     * @param boolean $verify_schema whether to verify the database's schema for this addon, or just its data.
304
-     *                               This is a resource-intensive job so we prefer to only do it when necessary
305
-     * @return void
306
-     * @throws \EE_Error
307
-     */
308
-    public function initialize_db_if_no_migrations_required($verify_schema = true)
309
-    {
310
-        if ($verify_schema === '') {
311
-            //wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
312
-            //(ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
313
-            //calls them with an argument of an empty string (ie ""), which evaluates to false
314
-            //so we need to treat the empty string as if nothing had been passed, and should instead use the default
315
-            $verify_schema = true;
316
-        }
317
-        if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
318
-            if ($verify_schema) {
319
-                $this->initialize_db();
320
-            }
321
-            $this->initialize_default_data();
322
-            //@todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
323
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to(
324
-                array(
325
-                    'slug'    => $this->name(),
326
-                    'version' => $this->version(),
327
-                )
328
-            );
329
-            /* make sure core's data is a-ok
17
+	/**
18
+	 * prefix to be added onto an addon's plugin slug to make a wp option name
19
+	 * which will be used to store the plugin's activation history
20
+	 */
21
+	const ee_addon_version_history_option_prefix = 'ee_version_history_';
22
+
23
+	/**
24
+	 * @var $_version
25
+	 * @type string
26
+	 */
27
+	protected $_version = '';
28
+
29
+	/**
30
+	 * @var $_min_core_version
31
+	 * @type string
32
+	 */
33
+	protected $_min_core_version = '';
34
+
35
+	/**
36
+	 * derived from plugin 'main_file_path using plugin_basename()
37
+	 *
38
+	 * @type string $_plugin_basename
39
+	 */
40
+	protected $_plugin_basename = '';
41
+
42
+	/**
43
+	 * A non-internationalized name to identify this addon for use in URLs, etc
44
+	 *
45
+	 * @type string $_plugin_slug
46
+	 */
47
+	protected $_plugin_slug = '';
48
+
49
+	/**
50
+	 * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
51
+	 *
52
+	 * @type string _addon_name
53
+	 */
54
+	protected $_addon_name = '';
55
+
56
+	/**
57
+	 * one of the EE_System::req_type_* constants
58
+	 *
59
+	 * @type int $_req_type
60
+	 */
61
+	protected $_req_type;
62
+
63
+	/**
64
+	 * page slug to be used when generating the "Settings" link on the WP plugin page
65
+	 *
66
+	 * @type string $_plugin_action_slug
67
+	 */
68
+	protected $_plugin_action_slug = '';
69
+
70
+	/**
71
+	 * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
72
+	 * that can be used for adding upgrading/marketing info
73
+	 *
74
+	 * @type array $_plugins_page_row
75
+	 */
76
+	protected $_plugins_page_row = array();
77
+
78
+
79
+
80
+	/**
81
+	 *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
82
+	 *
83
+	 * @type string
84
+	 */
85
+	protected $_main_plugin_file;
86
+
87
+
88
+	/**
89
+	 *    class constructor
90
+	 */
91
+	public function __construct()
92
+	{
93
+		add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
94
+	}
95
+
96
+
97
+	/**
98
+	 * @param mixed $version
99
+	 */
100
+	public function set_version($version = null)
101
+	{
102
+		$this->_version = $version;
103
+	}
104
+
105
+
106
+	/**
107
+	 * get__version
108
+	 *
109
+	 * @return string
110
+	 */
111
+	public function version()
112
+	{
113
+		return $this->_version;
114
+	}
115
+
116
+
117
+	/**
118
+	 * @param mixed $min_core_version
119
+	 */
120
+	public function set_min_core_version($min_core_version = null)
121
+	{
122
+		$this->_min_core_version = $min_core_version;
123
+	}
124
+
125
+
126
+	/**
127
+	 * get__min_core_version
128
+	 *
129
+	 * @return string
130
+	 */
131
+	public function min_core_version()
132
+	{
133
+		return $this->_min_core_version;
134
+	}
135
+
136
+
137
+	/**
138
+	 * Sets addon_name
139
+	 *
140
+	 * @param string $addon_name
141
+	 * @return boolean
142
+	 */
143
+	public function set_name($addon_name)
144
+	{
145
+		return $this->_addon_name = $addon_name;
146
+	}
147
+
148
+
149
+	/**
150
+	 * Gets addon_name
151
+	 *
152
+	 * @return string
153
+	 */
154
+	public function name()
155
+	{
156
+		return $this->_addon_name;
157
+	}
158
+
159
+
160
+	/**
161
+	 * @return string
162
+	 */
163
+	public function plugin_basename()
164
+	{
165
+
166
+		return $this->_plugin_basename;
167
+	}
168
+
169
+
170
+	/**
171
+	 * @param string $plugin_basename
172
+	 */
173
+	public function set_plugin_basename($plugin_basename)
174
+	{
175
+
176
+		$this->_plugin_basename = $plugin_basename;
177
+	}
178
+
179
+
180
+	/**
181
+	 * @return string
182
+	 */
183
+	public function plugin_slug()
184
+	{
185
+
186
+		return $this->_plugin_slug;
187
+	}
188
+
189
+
190
+	/**
191
+	 * @param string $plugin_slug
192
+	 */
193
+	public function set_plugin_slug($plugin_slug)
194
+	{
195
+
196
+		$this->_plugin_slug = $plugin_slug;
197
+	}
198
+
199
+
200
+	/**
201
+	 * @return string
202
+	 */
203
+	public function plugin_action_slug()
204
+	{
205
+
206
+		return $this->_plugin_action_slug;
207
+	}
208
+
209
+
210
+	/**
211
+	 * @param string $plugin_action_slug
212
+	 */
213
+	public function set_plugin_action_slug($plugin_action_slug)
214
+	{
215
+
216
+		$this->_plugin_action_slug = $plugin_action_slug;
217
+	}
218
+
219
+
220
+	/**
221
+	 * @return array
222
+	 */
223
+	public function get_plugins_page_row()
224
+	{
225
+
226
+		return $this->_plugins_page_row;
227
+	}
228
+
229
+
230
+	/**
231
+	 * @param array $plugins_page_row
232
+	 */
233
+	public function set_plugins_page_row($plugins_page_row = array())
234
+	{
235
+		// sigh.... check for example content that I stupidly merged to master and remove it if found
236
+		if (! is_array($plugins_page_row)
237
+			&& strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
238
+		) {
239
+			$plugins_page_row = array();
240
+		}
241
+		$this->_plugins_page_row = (array) $plugins_page_row;
242
+	}
243
+
244
+
245
+	/**
246
+	 * Called when EE core detects this addon has been activated for the first time.
247
+	 * If the site isn't in maintenance mode, should setup the addon's database
248
+	 *
249
+	 * @return void
250
+	 */
251
+	public function new_install()
252
+	{
253
+		$classname = get_class($this);
254
+		do_action("AHEE__{$classname}__new_install");
255
+		do_action('AHEE__EE_Addon__new_install', $this);
256
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
257
+		add_action(
258
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
259
+			array($this, 'initialize_db_if_no_migrations_required')
260
+		);
261
+	}
262
+
263
+
264
+	/**
265
+	 * Called when EE core detects this addon has been reactivated. When this happens,
266
+	 * it's good to just check that your data is still intact
267
+	 *
268
+	 * @return void
269
+	 */
270
+	public function reactivation()
271
+	{
272
+		$classname = get_class($this);
273
+		do_action("AHEE__{$classname}__reactivation");
274
+		do_action('AHEE__EE_Addon__reactivation', $this);
275
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
276
+		add_action(
277
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
278
+			array($this, 'initialize_db_if_no_migrations_required')
279
+		);
280
+	}
281
+
282
+
283
+	/**
284
+	 * Called when the registered deactivation hook for this addon fires.
285
+	 * @throws EE_Error
286
+	 */
287
+	public function deactivation()
288
+	{
289
+		$classname = get_class($this);
290
+		do_action("AHEE__{$classname}__deactivation");
291
+		do_action('AHEE__EE_Addon__deactivation', $this);
292
+		//check if the site no longer needs to be in maintenance mode
293
+		EE_Register_Addon::deregister($this->name());
294
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
295
+	}
296
+
297
+
298
+	/**
299
+	 * Takes care of double-checking that we're not in maintenance mode, and then
300
+	 * initializing this addon's necessary initial data. This is called by default on new activations
301
+	 * and reactivations.
302
+	 *
303
+	 * @param boolean $verify_schema whether to verify the database's schema for this addon, or just its data.
304
+	 *                               This is a resource-intensive job so we prefer to only do it when necessary
305
+	 * @return void
306
+	 * @throws \EE_Error
307
+	 */
308
+	public function initialize_db_if_no_migrations_required($verify_schema = true)
309
+	{
310
+		if ($verify_schema === '') {
311
+			//wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
312
+			//(ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
313
+			//calls them with an argument of an empty string (ie ""), which evaluates to false
314
+			//so we need to treat the empty string as if nothing had been passed, and should instead use the default
315
+			$verify_schema = true;
316
+		}
317
+		if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
318
+			if ($verify_schema) {
319
+				$this->initialize_db();
320
+			}
321
+			$this->initialize_default_data();
322
+			//@todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
323
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to(
324
+				array(
325
+					'slug'    => $this->name(),
326
+					'version' => $this->version(),
327
+				)
328
+			);
329
+			/* make sure core's data is a-ok
330 330
              * (at the time of writing, we especially want to verify all the caps are present
331 331
              * because payment method type capabilities are added dynamically, and it's
332 332
              * possible this addon added a payment method. But it's also possible
333 333
              * other data needs to be verified)
334 334
              */
335
-            EEH_Activation::initialize_db_content();
336
-            update_option('ee_flush_rewrite_rules', true);
337
-            //in case there are lots of addons being activated at once, let's force garbage collection
338
-            //to help avoid memory limit errors
339
-            //EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
340
-            gc_collect_cycles();
341
-        } else {
342
-            //ask the data migration manager to init this addon's data
343
-            //when migrations are finished because we can't do it now
344
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
345
-        }
346
-    }
347
-
348
-
349
-    /**
350
-     * Used to setup this addon's database tables, but not necessarily any default
351
-     * data in them. The default is to actually use the most up-to-date data migration script
352
-     * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
353
-     * methods to setup the db.
354
-     */
355
-    public function initialize_db()
356
-    {
357
-        //find the migration script that sets the database to be compatible with the code
358
-        $current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
359
-        if ($current_dms_name) {
360
-            $current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
361
-            $current_data_migration_script->set_migrating(false);
362
-            $current_data_migration_script->schema_changes_before_migration();
363
-            $current_data_migration_script->schema_changes_after_migration();
364
-            if ($current_data_migration_script->get_errors()) {
365
-                foreach ($current_data_migration_script->get_errors() as $error) {
366
-                    EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
367
-                }
368
-            }
369
-        }
370
-        //if not DMS was found that should be ok. This addon just doesn't require any database changes
371
-        EE_Data_Migration_Manager::instance()->update_current_database_state_to(
372
-            array(
373
-                'slug'    => $this->name(),
374
-                'version' => $this->version(),
375
-            )
376
-        );
377
-    }
378
-
379
-
380
-    /**
381
-     * If you want to setup default data for the addon, override this method, and call
382
-     * parent::initialize_default_data() from within it. This is normally called
383
-     * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
384
-     * and should verify default data is present (but this is also called
385
-     * on reactivations and just after migrations, so please verify you actually want
386
-     * to ADD default data, because it may already be present).
387
-     * However, please call this parent (currently it just fires a hook which other
388
-     * addons may be depending on)
389
-     */
390
-    public function initialize_default_data()
391
-    {
392
-        /**
393
-         * Called when an addon is ensuring its default data is set (possibly called
394
-         * on a reactivation, so first check for the absence of other data before setting
395
-         * default data)
396
-         *
397
-         * @param EE_Addon $addon the addon that called this
398
-         */
399
-        do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
400
-        //override to insert default data. It is safe to use the models here
401
-        //because the site should not be in maintenance mode
402
-    }
403
-
404
-
405
-    /**
406
-     * EE Core detected that this addon has been upgraded. We should check if there
407
-     * are any new migration scripts, and if so put the site into maintenance mode until
408
-     * they're ran
409
-     *
410
-     * @return void
411
-     */
412
-    public function upgrade()
413
-    {
414
-        $classname = get_class($this);
415
-        do_action("AHEE__{$classname}__upgrade");
416
-        do_action('AHEE__EE_Addon__upgrade', $this);
417
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
418
-        //also it's possible there is new default data that needs to be added
419
-        add_action(
420
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
421
-            array($this, 'initialize_db_if_no_migrations_required')
422
-        );
423
-    }
424
-
425
-
426
-    /**
427
-     * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
428
-     */
429
-    public function downgrade()
430
-    {
431
-        $classname = get_class($this);
432
-        do_action("AHEE__{$classname}__downgrade");
433
-        do_action('AHEE__EE_Addon__downgrade', $this);
434
-        //it's possible there's old default data that needs to be double-checked
435
-        add_action(
436
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
437
-            array($this, 'initialize_db_if_no_migrations_required')
438
-        );
439
-    }
440
-
441
-
442
-    /**
443
-     * set_db_update_option_name
444
-     * Until we do something better, we'll just check for migration scripts upon
445
-     * plugin activation only. In the future, we'll want to do it on plugin updates too
446
-     *
447
-     * @return bool
448
-     */
449
-    public function set_db_update_option_name()
450
-    {
451
-        EE_Error::doing_it_wrong(
452
-            __FUNCTION__,
453
-            esc_html__(
454
-                'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
455
-                'event_espresso'
456
-            ),
457
-            '4.3.0.alpha.016'
458
-        );
459
-        //let's just handle this on the next request, ok? right now we're just not really ready
460
-        return $this->set_activation_indicator_option();
461
-    }
462
-
463
-
464
-    /**
465
-     * Returns the name of the activation indicator option
466
-     * (an option which is set temporarily to indicate that this addon was just activated)
467
-     *
468
-     * @deprecated since version 4.3.0.alpha.016
469
-     * @return string
470
-     */
471
-    public function get_db_update_option_name()
472
-    {
473
-        EE_Error::doing_it_wrong(
474
-            __FUNCTION__,
475
-            esc_html__(
476
-                'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
477
-                'event_espresso'
478
-            ),
479
-            '4.3.0.alpha.016'
480
-        );
481
-        return $this->get_activation_indicator_option_name();
482
-    }
483
-
484
-
485
-    /**
486
-     * When the addon is activated, this should be called to set a wordpress option that
487
-     * indicates it was activated. This is especially useful for detecting reactivations.
488
-     *
489
-     * @return bool
490
-     */
491
-    public function set_activation_indicator_option()
492
-    {
493
-        // let's just handle this on the next request, ok? right now we're just not really ready
494
-        return update_option($this->get_activation_indicator_option_name(), true);
495
-    }
496
-
497
-
498
-    /**
499
-     * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
500
-     *
501
-     * @return string
502
-     */
503
-    public function get_activation_indicator_option_name()
504
-    {
505
-        return 'ee_activation_' . $this->name();
506
-    }
507
-
508
-
509
-    /**
510
-     * Used by EE_System to set the request type of this addon. Should not be used by addon developers
511
-     *
512
-     * @param int $req_type
513
-     */
514
-    public function set_req_type($req_type)
515
-    {
516
-        $this->_req_type = $req_type;
517
-    }
518
-
519
-
520
-    /**
521
-     * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
522
-     * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
523
-     * EE_System when it is checking for new install or upgrades of addons
524
-     */
525
-    public function detect_req_type()
526
-    {
527
-        if (! $this->_req_type) {
528
-            $this->detect_activation_or_upgrade();
529
-        }
530
-        return $this->_req_type;
531
-    }
532
-
533
-
534
-    /**
535
-     * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
536
-     * Should only be called once per request
537
-     *
538
-     * @return void
539
-     */
540
-    public function detect_activation_or_upgrade()
541
-    {
542
-        $activation_history_for_addon = $this->get_activation_history();
335
+			EEH_Activation::initialize_db_content();
336
+			update_option('ee_flush_rewrite_rules', true);
337
+			//in case there are lots of addons being activated at once, let's force garbage collection
338
+			//to help avoid memory limit errors
339
+			//EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
340
+			gc_collect_cycles();
341
+		} else {
342
+			//ask the data migration manager to init this addon's data
343
+			//when migrations are finished because we can't do it now
344
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
345
+		}
346
+	}
347
+
348
+
349
+	/**
350
+	 * Used to setup this addon's database tables, but not necessarily any default
351
+	 * data in them. The default is to actually use the most up-to-date data migration script
352
+	 * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
353
+	 * methods to setup the db.
354
+	 */
355
+	public function initialize_db()
356
+	{
357
+		//find the migration script that sets the database to be compatible with the code
358
+		$current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
359
+		if ($current_dms_name) {
360
+			$current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
361
+			$current_data_migration_script->set_migrating(false);
362
+			$current_data_migration_script->schema_changes_before_migration();
363
+			$current_data_migration_script->schema_changes_after_migration();
364
+			if ($current_data_migration_script->get_errors()) {
365
+				foreach ($current_data_migration_script->get_errors() as $error) {
366
+					EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
367
+				}
368
+			}
369
+		}
370
+		//if not DMS was found that should be ok. This addon just doesn't require any database changes
371
+		EE_Data_Migration_Manager::instance()->update_current_database_state_to(
372
+			array(
373
+				'slug'    => $this->name(),
374
+				'version' => $this->version(),
375
+			)
376
+		);
377
+	}
378
+
379
+
380
+	/**
381
+	 * If you want to setup default data for the addon, override this method, and call
382
+	 * parent::initialize_default_data() from within it. This is normally called
383
+	 * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
384
+	 * and should verify default data is present (but this is also called
385
+	 * on reactivations and just after migrations, so please verify you actually want
386
+	 * to ADD default data, because it may already be present).
387
+	 * However, please call this parent (currently it just fires a hook which other
388
+	 * addons may be depending on)
389
+	 */
390
+	public function initialize_default_data()
391
+	{
392
+		/**
393
+		 * Called when an addon is ensuring its default data is set (possibly called
394
+		 * on a reactivation, so first check for the absence of other data before setting
395
+		 * default data)
396
+		 *
397
+		 * @param EE_Addon $addon the addon that called this
398
+		 */
399
+		do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
400
+		//override to insert default data. It is safe to use the models here
401
+		//because the site should not be in maintenance mode
402
+	}
403
+
404
+
405
+	/**
406
+	 * EE Core detected that this addon has been upgraded. We should check if there
407
+	 * are any new migration scripts, and if so put the site into maintenance mode until
408
+	 * they're ran
409
+	 *
410
+	 * @return void
411
+	 */
412
+	public function upgrade()
413
+	{
414
+		$classname = get_class($this);
415
+		do_action("AHEE__{$classname}__upgrade");
416
+		do_action('AHEE__EE_Addon__upgrade', $this);
417
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
418
+		//also it's possible there is new default data that needs to be added
419
+		add_action(
420
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
421
+			array($this, 'initialize_db_if_no_migrations_required')
422
+		);
423
+	}
424
+
425
+
426
+	/**
427
+	 * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
428
+	 */
429
+	public function downgrade()
430
+	{
431
+		$classname = get_class($this);
432
+		do_action("AHEE__{$classname}__downgrade");
433
+		do_action('AHEE__EE_Addon__downgrade', $this);
434
+		//it's possible there's old default data that needs to be double-checked
435
+		add_action(
436
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
437
+			array($this, 'initialize_db_if_no_migrations_required')
438
+		);
439
+	}
440
+
441
+
442
+	/**
443
+	 * set_db_update_option_name
444
+	 * Until we do something better, we'll just check for migration scripts upon
445
+	 * plugin activation only. In the future, we'll want to do it on plugin updates too
446
+	 *
447
+	 * @return bool
448
+	 */
449
+	public function set_db_update_option_name()
450
+	{
451
+		EE_Error::doing_it_wrong(
452
+			__FUNCTION__,
453
+			esc_html__(
454
+				'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
455
+				'event_espresso'
456
+			),
457
+			'4.3.0.alpha.016'
458
+		);
459
+		//let's just handle this on the next request, ok? right now we're just not really ready
460
+		return $this->set_activation_indicator_option();
461
+	}
462
+
463
+
464
+	/**
465
+	 * Returns the name of the activation indicator option
466
+	 * (an option which is set temporarily to indicate that this addon was just activated)
467
+	 *
468
+	 * @deprecated since version 4.3.0.alpha.016
469
+	 * @return string
470
+	 */
471
+	public function get_db_update_option_name()
472
+	{
473
+		EE_Error::doing_it_wrong(
474
+			__FUNCTION__,
475
+			esc_html__(
476
+				'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
477
+				'event_espresso'
478
+			),
479
+			'4.3.0.alpha.016'
480
+		);
481
+		return $this->get_activation_indicator_option_name();
482
+	}
483
+
484
+
485
+	/**
486
+	 * When the addon is activated, this should be called to set a wordpress option that
487
+	 * indicates it was activated. This is especially useful for detecting reactivations.
488
+	 *
489
+	 * @return bool
490
+	 */
491
+	public function set_activation_indicator_option()
492
+	{
493
+		// let's just handle this on the next request, ok? right now we're just not really ready
494
+		return update_option($this->get_activation_indicator_option_name(), true);
495
+	}
496
+
497
+
498
+	/**
499
+	 * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
500
+	 *
501
+	 * @return string
502
+	 */
503
+	public function get_activation_indicator_option_name()
504
+	{
505
+		return 'ee_activation_' . $this->name();
506
+	}
507
+
508
+
509
+	/**
510
+	 * Used by EE_System to set the request type of this addon. Should not be used by addon developers
511
+	 *
512
+	 * @param int $req_type
513
+	 */
514
+	public function set_req_type($req_type)
515
+	{
516
+		$this->_req_type = $req_type;
517
+	}
518
+
519
+
520
+	/**
521
+	 * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
522
+	 * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
523
+	 * EE_System when it is checking for new install or upgrades of addons
524
+	 */
525
+	public function detect_req_type()
526
+	{
527
+		if (! $this->_req_type) {
528
+			$this->detect_activation_or_upgrade();
529
+		}
530
+		return $this->_req_type;
531
+	}
532
+
533
+
534
+	/**
535
+	 * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
536
+	 * Should only be called once per request
537
+	 *
538
+	 * @return void
539
+	 */
540
+	public function detect_activation_or_upgrade()
541
+	{
542
+		$activation_history_for_addon = $this->get_activation_history();
543 543
 //		d($activation_history_for_addon);
544
-        $request_type = EE_System::detect_req_type_given_activation_history(
545
-            $activation_history_for_addon,
546
-            $this->get_activation_indicator_option_name(),
547
-            $this->version()
548
-        );
549
-        $this->set_req_type($request_type);
550
-        $classname = get_class($this);
551
-        switch ($request_type) {
552
-            case EE_System::req_type_new_activation:
553
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
554
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
555
-                $this->new_install();
556
-                $this->update_list_of_installed_versions($activation_history_for_addon);
557
-                break;
558
-            case EE_System::req_type_reactivation:
559
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
560
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
561
-                $this->reactivation();
562
-                $this->update_list_of_installed_versions($activation_history_for_addon);
563
-                break;
564
-            case EE_System::req_type_upgrade:
565
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
566
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
567
-                $this->upgrade();
568
-                $this->update_list_of_installed_versions($activation_history_for_addon);
569
-                break;
570
-            case EE_System::req_type_downgrade:
571
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
572
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
573
-                $this->downgrade();
574
-                $this->update_list_of_installed_versions($activation_history_for_addon);
575
-                break;
576
-            case EE_System::req_type_normal:
577
-            default:
544
+		$request_type = EE_System::detect_req_type_given_activation_history(
545
+			$activation_history_for_addon,
546
+			$this->get_activation_indicator_option_name(),
547
+			$this->version()
548
+		);
549
+		$this->set_req_type($request_type);
550
+		$classname = get_class($this);
551
+		switch ($request_type) {
552
+			case EE_System::req_type_new_activation:
553
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
554
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
555
+				$this->new_install();
556
+				$this->update_list_of_installed_versions($activation_history_for_addon);
557
+				break;
558
+			case EE_System::req_type_reactivation:
559
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
560
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
561
+				$this->reactivation();
562
+				$this->update_list_of_installed_versions($activation_history_for_addon);
563
+				break;
564
+			case EE_System::req_type_upgrade:
565
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
566
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
567
+				$this->upgrade();
568
+				$this->update_list_of_installed_versions($activation_history_for_addon);
569
+				break;
570
+			case EE_System::req_type_downgrade:
571
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
572
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
573
+				$this->downgrade();
574
+				$this->update_list_of_installed_versions($activation_history_for_addon);
575
+				break;
576
+			case EE_System::req_type_normal:
577
+			default:
578 578
 //				$this->_maybe_redirect_to_ee_about();
579
-                break;
580
-        }
581
-
582
-        do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
583
-    }
584
-
585
-    /**
586
-     * Updates the version history for this addon
587
-     *
588
-     * @param array  $version_history
589
-     * @param string $current_version_to_add
590
-     * @return boolean success
591
-     */
592
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
593
-    {
594
-        if (! $version_history) {
595
-            $version_history = $this->get_activation_history();
596
-        }
597
-        if ($current_version_to_add === null) {
598
-            $current_version_to_add = $this->version();
599
-        }
600
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
601
-        // resave
579
+				break;
580
+		}
581
+
582
+		do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
583
+	}
584
+
585
+	/**
586
+	 * Updates the version history for this addon
587
+	 *
588
+	 * @param array  $version_history
589
+	 * @param string $current_version_to_add
590
+	 * @return boolean success
591
+	 */
592
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
593
+	{
594
+		if (! $version_history) {
595
+			$version_history = $this->get_activation_history();
596
+		}
597
+		if ($current_version_to_add === null) {
598
+			$current_version_to_add = $this->version();
599
+		}
600
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
601
+		// resave
602 602
 //		echo "updating list of installed versions:".$this->get_activation_history_option_name();d($version_history);
603
-        return update_option($this->get_activation_history_option_name(), $version_history);
604
-    }
605
-
606
-    /**
607
-     * Gets the name of the wp option that stores the activation history
608
-     * of this addon
609
-     *
610
-     * @return string
611
-     */
612
-    public function get_activation_history_option_name()
613
-    {
614
-        return self::ee_addon_version_history_option_prefix . $this->name();
615
-    }
616
-
617
-
618
-    /**
619
-     * Gets the wp option which stores the activation history for this addon
620
-     *
621
-     * @return array
622
-     */
623
-    public function get_activation_history()
624
-    {
625
-        return get_option($this->get_activation_history_option_name(), null);
626
-    }
627
-
628
-
629
-    /**
630
-     * @param string $config_section
631
-     */
632
-    public function set_config_section($config_section = '')
633
-    {
634
-        $this->_config_section = ! empty($config_section) ? $config_section : 'addons';
635
-    }
636
-
637
-    /**
638
-     * Sets the filepath to the main plugin file
639
-     *
640
-     * @param string $filepath
641
-     */
642
-    public function set_main_plugin_file($filepath)
643
-    {
644
-        $this->_main_plugin_file = $filepath;
645
-    }
646
-
647
-    /**
648
-     * gets the filepath to teh main file
649
-     *
650
-     * @return string
651
-     */
652
-    public function get_main_plugin_file()
653
-    {
654
-        return $this->_main_plugin_file;
655
-    }
656
-
657
-    /**
658
-     * Gets the filename (no path) of the main file (the main file loaded
659
-     * by WP)
660
-     *
661
-     * @return string
662
-     */
663
-    public function get_main_plugin_file_basename()
664
-    {
665
-        return plugin_basename($this->get_main_plugin_file());
666
-    }
667
-
668
-    /**
669
-     * Gets the folder name which contains the main plugin file
670
-     *
671
-     * @return string
672
-     */
673
-    public function get_main_plugin_file_dirname()
674
-    {
675
-        return dirname($this->get_main_plugin_file());
676
-    }
677
-
678
-
679
-    /**
680
-     * sets hooks used in the admin
681
-     *
682
-     * @return void
683
-     */
684
-    public function admin_init()
685
-    {
686
-        // is admin and not in M-Mode ?
687
-        if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
688
-            add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
689
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
690
-        }
691
-    }
692
-
693
-
694
-    /**
695
-     * plugin_actions
696
-     * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
697
-     *
698
-     * @param $links
699
-     * @param $file
700
-     * @return array
701
-     */
702
-    public function plugin_action_links($links, $file)
703
-    {
704
-        if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
705
-            // before other links
706
-            array_unshift(
707
-                $links,
708
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
709
-                . esc_html__('Settings', 'event_espresso')
710
-                . '</a>'
711
-            );
712
-        }
713
-        return $links;
714
-    }
715
-
716
-
717
-    /**
718
-     * after_plugin_row
719
-     * Add additional content to the plugins page plugin row
720
-     * Inserts another row
721
-     *
722
-     * @param $plugin_file
723
-     * @param $plugin_data
724
-     * @param $status
725
-     * @return void
726
-     */
727
-    public function after_plugin_row($plugin_file, $plugin_data, $status)
728
-    {
729
-        $after_plugin_row = '';
730
-        $plugins_page_row = $this->get_plugins_page_row();
731
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
732
-            $class            = $status ? 'active' : 'inactive';
733
-            $link_text        = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
734
-            $link_url         = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
735
-            $description      = isset($plugins_page_row['description'])
736
-                ? $plugins_page_row['description']
737
-                : '';
738
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
739
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
740
-                $after_plugin_row .= '<th class="check-column" scope="row"></th>';
741
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
742
-                $after_plugin_row .= '<style>
603
+		return update_option($this->get_activation_history_option_name(), $version_history);
604
+	}
605
+
606
+	/**
607
+	 * Gets the name of the wp option that stores the activation history
608
+	 * of this addon
609
+	 *
610
+	 * @return string
611
+	 */
612
+	public function get_activation_history_option_name()
613
+	{
614
+		return self::ee_addon_version_history_option_prefix . $this->name();
615
+	}
616
+
617
+
618
+	/**
619
+	 * Gets the wp option which stores the activation history for this addon
620
+	 *
621
+	 * @return array
622
+	 */
623
+	public function get_activation_history()
624
+	{
625
+		return get_option($this->get_activation_history_option_name(), null);
626
+	}
627
+
628
+
629
+	/**
630
+	 * @param string $config_section
631
+	 */
632
+	public function set_config_section($config_section = '')
633
+	{
634
+		$this->_config_section = ! empty($config_section) ? $config_section : 'addons';
635
+	}
636
+
637
+	/**
638
+	 * Sets the filepath to the main plugin file
639
+	 *
640
+	 * @param string $filepath
641
+	 */
642
+	public function set_main_plugin_file($filepath)
643
+	{
644
+		$this->_main_plugin_file = $filepath;
645
+	}
646
+
647
+	/**
648
+	 * gets the filepath to teh main file
649
+	 *
650
+	 * @return string
651
+	 */
652
+	public function get_main_plugin_file()
653
+	{
654
+		return $this->_main_plugin_file;
655
+	}
656
+
657
+	/**
658
+	 * Gets the filename (no path) of the main file (the main file loaded
659
+	 * by WP)
660
+	 *
661
+	 * @return string
662
+	 */
663
+	public function get_main_plugin_file_basename()
664
+	{
665
+		return plugin_basename($this->get_main_plugin_file());
666
+	}
667
+
668
+	/**
669
+	 * Gets the folder name which contains the main plugin file
670
+	 *
671
+	 * @return string
672
+	 */
673
+	public function get_main_plugin_file_dirname()
674
+	{
675
+		return dirname($this->get_main_plugin_file());
676
+	}
677
+
678
+
679
+	/**
680
+	 * sets hooks used in the admin
681
+	 *
682
+	 * @return void
683
+	 */
684
+	public function admin_init()
685
+	{
686
+		// is admin and not in M-Mode ?
687
+		if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
688
+			add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
689
+			add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
690
+		}
691
+	}
692
+
693
+
694
+	/**
695
+	 * plugin_actions
696
+	 * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
697
+	 *
698
+	 * @param $links
699
+	 * @param $file
700
+	 * @return array
701
+	 */
702
+	public function plugin_action_links($links, $file)
703
+	{
704
+		if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
705
+			// before other links
706
+			array_unshift(
707
+				$links,
708
+				'<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
709
+				. esc_html__('Settings', 'event_espresso')
710
+				. '</a>'
711
+			);
712
+		}
713
+		return $links;
714
+	}
715
+
716
+
717
+	/**
718
+	 * after_plugin_row
719
+	 * Add additional content to the plugins page plugin row
720
+	 * Inserts another row
721
+	 *
722
+	 * @param $plugin_file
723
+	 * @param $plugin_data
724
+	 * @param $status
725
+	 * @return void
726
+	 */
727
+	public function after_plugin_row($plugin_file, $plugin_data, $status)
728
+	{
729
+		$after_plugin_row = '';
730
+		$plugins_page_row = $this->get_plugins_page_row();
731
+		if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
732
+			$class            = $status ? 'active' : 'inactive';
733
+			$link_text        = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
734
+			$link_url         = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
735
+			$description      = isset($plugins_page_row['description'])
736
+				? $plugins_page_row['description']
737
+				: '';
738
+			if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
739
+				$after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
740
+				$after_plugin_row .= '<th class="check-column" scope="row"></th>';
741
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
742
+				$after_plugin_row .= '<style>
743 743
 .ee-button,
744 744
 .ee-button:active,
745 745
 .ee-button:visited {
@@ -776,49 +776,49 @@  discard block
 block discarded – undo
776 776
 }
777 777
 .ee-button:active { top:0; }
778 778
 </style>';
779
-                $after_plugin_row .= '
779
+				$after_plugin_row .= '
780 780
 <p class="ee-addon-upsell-info-dv">
781 781
 	<a class="ee-button" href="' . $link_url . '">'
782
-                . $link_text
783
-                . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
784
-                . '</a>
782
+				. $link_text
783
+				. ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
784
+				. '</a>
785 785
 </p>';
786
-                $after_plugin_row .= '</td>';
787
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
788
-                $after_plugin_row .= $description;
789
-                $after_plugin_row .= '</td>';
790
-                $after_plugin_row .= '</tr>';
791
-            } else {
792
-                $after_plugin_row .= $description;
793
-            }
794
-        }
795
-
796
-        echo $after_plugin_row;
797
-    }
798
-
799
-
800
-    /**
801
-     * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
802
-     * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
803
-     * for back compat reasons.
804
-     *
805
-     * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
806
-     *
807
-     * It is recommended, if client code is `de-registering` an add-on, then do it on the
808
-     * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
809
-     * callback does not get run/set in that request.
810
-     *
811
-     * Also, keep in mind that if a registered add-on happens to be deactivated via
812
-     * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
813
-     * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
814
-     * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
815
-     * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
816
-     * to call `parent::deactivation`.
817
-     *
818
-     * @since 4.9.26
819
-     */
820
-    public function after_registration()
821
-    {
822
-        // cricket chirp... cricket chirp...
823
-    }
786
+				$after_plugin_row .= '</td>';
787
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
788
+				$after_plugin_row .= $description;
789
+				$after_plugin_row .= '</td>';
790
+				$after_plugin_row .= '</tr>';
791
+			} else {
792
+				$after_plugin_row .= $description;
793
+			}
794
+		}
795
+
796
+		echo $after_plugin_row;
797
+	}
798
+
799
+
800
+	/**
801
+	 * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
802
+	 * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
803
+	 * for back compat reasons.
804
+	 *
805
+	 * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
806
+	 *
807
+	 * It is recommended, if client code is `de-registering` an add-on, then do it on the
808
+	 * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
809
+	 * callback does not get run/set in that request.
810
+	 *
811
+	 * Also, keep in mind that if a registered add-on happens to be deactivated via
812
+	 * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
813
+	 * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
814
+	 * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
815
+	 * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
816
+	 * to call `parent::deactivation`.
817
+	 *
818
+	 * @since 4.9.26
819
+	 */
820
+	public function after_registration()
821
+	{
822
+		// cricket chirp... cricket chirp...
823
+	}
824 824
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
     public function set_plugins_page_row($plugins_page_row = array())
234 234
     {
235 235
         // sigh.... check for example content that I stupidly merged to master and remove it if found
236
-        if (! is_array($plugins_page_row)
236
+        if ( ! is_array($plugins_page_row)
237 237
             && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
238 238
         ) {
239 239
             $plugins_page_row = array();
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
      */
503 503
     public function get_activation_indicator_option_name()
504 504
     {
505
-        return 'ee_activation_' . $this->name();
505
+        return 'ee_activation_'.$this->name();
506 506
     }
507 507
 
508 508
 
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
      */
525 525
     public function detect_req_type()
526 526
     {
527
-        if (! $this->_req_type) {
527
+        if ( ! $this->_req_type) {
528 528
             $this->detect_activation_or_upgrade();
529 529
         }
530 530
         return $this->_req_type;
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
      */
592 592
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
593 593
     {
594
-        if (! $version_history) {
594
+        if ( ! $version_history) {
595 595
             $version_history = $this->get_activation_history();
596 596
         }
597 597
         if ($current_version_to_add === null) {
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
      */
612 612
     public function get_activation_history_option_name()
613 613
     {
614
-        return self::ee_addon_version_history_option_prefix . $this->name();
614
+        return self::ee_addon_version_history_option_prefix.$this->name();
615 615
     }
616 616
 
617 617
 
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
         // is admin and not in M-Mode ?
687 687
         if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
688 688
             add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
689
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
689
+            add_filter('after_plugin_row_'.$this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
690 690
         }
691 691
     }
692 692
 
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
             // before other links
706 706
             array_unshift(
707 707
                 $links,
708
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
708
+                '<a href="admin.php?page='.$this->plugin_action_slug().'">'
709 709
                 . esc_html__('Settings', 'event_espresso')
710 710
                 . '</a>'
711 711
             );
@@ -728,15 +728,15 @@  discard block
 block discarded – undo
728 728
     {
729 729
         $after_plugin_row = '';
730 730
         $plugins_page_row = $this->get_plugins_page_row();
731
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
731
+        if ( ! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
732 732
             $class            = $status ? 'active' : 'inactive';
733 733
             $link_text        = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
734 734
             $link_url         = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
735 735
             $description      = isset($plugins_page_row['description'])
736 736
                 ? $plugins_page_row['description']
737 737
                 : '';
738
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
739
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
738
+            if ( ! empty($link_text) && ! empty($link_url) && ! empty($description)) {
739
+                $after_plugin_row .= '<tr id="'.sanitize_title($plugin_file).'-ee-addon" class="'.$class.'">';
740 740
                 $after_plugin_row .= '<th class="check-column" scope="row"></th>';
741 741
                 $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
742 742
                 $after_plugin_row .= '<style>
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 </style>';
779 779
                 $after_plugin_row .= '
780 780
 <p class="ee-addon-upsell-info-dv">
781
-	<a class="ee-button" href="' . $link_url . '">'
781
+	<a class="ee-button" href="' . $link_url.'">'
782 782
                 . $link_text
783 783
                 . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
784 784
                 . '</a>
Please login to merge, or discard this patch.
core/domain/entities/Context.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -18,64 +18,64 @@
 block discarded – undo
18 18
 class Context
19 19
 {
20 20
 
21
-    /**
22
-     * @var string $slug
23
-     */
24
-    private $slug;
25
-
26
-    /**
27
-     * @var string $description
28
-     */
29
-    private $description;
30
-
31
-
32
-    /**
33
-     * Context constructor.
34
-     *
35
-     * @param string $slug
36
-     * @param string $description
37
-     */
38
-    public function __construct($slug, $description)
39
-    {
40
-        $this->setSlug($slug);
41
-        $this->setDescription($description);
42
-    }
43
-
44
-
45
-    /**
46
-     * @return string
47
-     */
48
-    public function slug()
49
-    {
50
-        return $this->slug;
51
-    }
52
-
53
-
54
-    /**
55
-     * @param string $slug
56
-     */
57
-    private function setSlug($slug)
58
-    {
59
-        $this->slug = sanitize_key($slug);
60
-    }
61
-
62
-
63
-    /**
64
-     * @return string
65
-     */
66
-    public function description()
67
-    {
68
-        return $this->description;
69
-    }
70
-
71
-
72
-    /**
73
-     * @param string $description
74
-     */
75
-    private function setDescription($description)
76
-    {
77
-        $this->description = sanitize_text_field($description);
78
-    }
21
+	/**
22
+	 * @var string $slug
23
+	 */
24
+	private $slug;
25
+
26
+	/**
27
+	 * @var string $description
28
+	 */
29
+	private $description;
30
+
31
+
32
+	/**
33
+	 * Context constructor.
34
+	 *
35
+	 * @param string $slug
36
+	 * @param string $description
37
+	 */
38
+	public function __construct($slug, $description)
39
+	{
40
+		$this->setSlug($slug);
41
+		$this->setDescription($description);
42
+	}
43
+
44
+
45
+	/**
46
+	 * @return string
47
+	 */
48
+	public function slug()
49
+	{
50
+		return $this->slug;
51
+	}
52
+
53
+
54
+	/**
55
+	 * @param string $slug
56
+	 */
57
+	private function setSlug($slug)
58
+	{
59
+		$this->slug = sanitize_key($slug);
60
+	}
61
+
62
+
63
+	/**
64
+	 * @return string
65
+	 */
66
+	public function description()
67
+	{
68
+		return $this->description;
69
+	}
70
+
71
+
72
+	/**
73
+	 * @param string $description
74
+	 */
75
+	private function setDescription($description)
76
+	{
77
+		$this->description = sanitize_text_field($description);
78
+	}
79 79
 
80 80
 }
81 81
 // Location: Context.php
Please login to merge, or discard this patch.
admin_pages/transactions/Transactions_Admin_Page.core.php 1 patch
Indentation   +1972 added lines, -1972 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 /**
@@ -27,1980 +27,1980 @@  discard block
 block discarded – undo
27 27
 class Transactions_Admin_Page extends EE_Admin_Page
28 28
 {
29 29
 
30
-    /**
31
-     * @var EE_Transaction
32
-     */
33
-    private $_transaction;
34
-
35
-    /**
36
-     * @var EE_Session
37
-     */
38
-    private $_session;
39
-
40
-    /**
41
-     * @var array $_txn_status
42
-     */
43
-    private static $_txn_status;
44
-
45
-    /**
46
-     * @var array $_pay_status
47
-     */
48
-    private static $_pay_status;
49
-
50
-    /**
51
-     * @var array $_existing_reg_payment_REG_IDs
52
-     */
53
-    protected $_existing_reg_payment_REG_IDs = null;
54
-
55
-
56
-    /**
57
-     * @Constructor
58
-     * @access public
59
-     *
60
-     * @param bool $routing
61
-     *
62
-     * @return Transactions_Admin_Page
63
-     */
64
-    public function __construct($routing = true)
65
-    {
66
-        parent::__construct($routing);
67
-    }
68
-
69
-
70
-    /**
71
-     *    _init_page_props
72
-     * @return void
73
-     */
74
-    protected function _init_page_props()
75
-    {
76
-        $this->page_slug        = TXN_PG_SLUG;
77
-        $this->page_label       = esc_html__('Transactions', 'event_espresso');
78
-        $this->_admin_base_url  = TXN_ADMIN_URL;
79
-        $this->_admin_base_path = TXN_ADMIN;
80
-    }
81
-
82
-
83
-    /**
84
-     *    _ajax_hooks
85
-     * @return void
86
-     */
87
-    protected function _ajax_hooks()
88
-    {
89
-        add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
90
-        add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
91
-        add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
92
-    }
93
-
94
-
95
-    /**
96
-     *    _define_page_props
97
-     * @return void
98
-     */
99
-    protected function _define_page_props()
100
-    {
101
-        $this->_admin_page_title = $this->page_label;
102
-        $this->_labels           = array(
103
-            'buttons' => array(
104
-                'add'    => esc_html__('Add New Transaction', 'event_espresso'),
105
-                'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
106
-                'delete' => esc_html__('Delete Transaction', 'event_espresso'),
107
-            )
108
-        );
109
-    }
110
-
111
-
112
-    /**
113
-     *        grab url requests and route them
114
-     * @access private
115
-     * @return void
116
-     */
117
-    public function _set_page_routes()
118
-    {
119
-
120
-        $this->_set_transaction_status_array();
121
-
122
-        $txn_id = ! empty($this->_req_data['TXN_ID']) && ! is_array($this->_req_data['TXN_ID']) ? $this->_req_data['TXN_ID'] : 0;
123
-
124
-        $this->_page_routes = array(
125
-
126
-            'default' => array(
127
-                'func'       => '_transactions_overview_list_table',
128
-                'capability' => 'ee_read_transactions'
129
-            ),
130
-
131
-            'view_transaction' => array(
132
-                'func'       => '_transaction_details',
133
-                'capability' => 'ee_read_transaction',
134
-                'obj_id'     => $txn_id
135
-            ),
136
-
137
-            'send_payment_reminder' => array(
138
-                'func'       => '_send_payment_reminder',
139
-                'noheader'   => true,
140
-                'capability' => 'ee_send_message'
141
-            ),
142
-
143
-            'espresso_apply_payment' => array(
144
-                'func'       => 'apply_payments_or_refunds',
145
-                'noheader'   => true,
146
-                'capability' => 'ee_edit_payments'
147
-            ),
148
-
149
-            'espresso_apply_refund' => array(
150
-                'func'       => 'apply_payments_or_refunds',
151
-                'noheader'   => true,
152
-                'capability' => 'ee_edit_payments'
153
-            ),
154
-
155
-            'espresso_delete_payment' => array(
156
-                'func'       => 'delete_payment',
157
-                'noheader'   => true,
158
-                'capability' => 'ee_delete_payments'
159
-            ),
160
-
161
-        );
162
-
163
-    }
164
-
165
-
166
-    protected function _set_page_config()
167
-    {
168
-        $this->_page_config = array(
169
-            'default'          => array(
170
-                'nav'           => array(
171
-                    'label' => esc_html__('Overview', 'event_espresso'),
172
-                    'order' => 10
173
-                ),
174
-                'list_table'    => 'EE_Admin_Transactions_List_Table',
175
-                'help_tabs'     => array(
176
-                    'transactions_overview_help_tab'                       => array(
177
-                        'title'    => esc_html__('Transactions Overview', 'event_espresso'),
178
-                        'filename' => 'transactions_overview'
179
-                    ),
180
-                    'transactions_overview_table_column_headings_help_tab' => array(
181
-                        'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
182
-                        'filename' => 'transactions_overview_table_column_headings'
183
-                    ),
184
-                    'transactions_overview_views_filters_help_tab'         => array(
185
-                        'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
186
-                        'filename' => 'transactions_overview_views_filters_search'
187
-                    ),
188
-                ),
189
-                'help_tour'     => array('Transactions_Overview_Help_Tour'),
190
-                /**
191
-                 * commented out because currently we are not displaying tips for transaction list table status but this
192
-                 * may change in a later iteration so want to keep the code for then.
193
-                 */
194
-                //'qtips' => array( 'Transactions_List_Table_Tips' ),
195
-                'require_nonce' => false
196
-            ),
197
-            'view_transaction' => array(
198
-                'nav'       => array(
199
-                    'label'      => esc_html__('View Transaction', 'event_espresso'),
200
-                    'order'      => 5,
201
-                    'url'        => isset($this->_req_data['TXN_ID']) ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']),
202
-                        $this->_current_page_view_url) : $this->_admin_base_url,
203
-                    'persistent' => false
204
-                ),
205
-                'help_tabs' => array(
206
-                    'transactions_view_transaction_help_tab'                                              => array(
207
-                        'title'    => esc_html__('View Transaction', 'event_espresso'),
208
-                        'filename' => 'transactions_view_transaction'
209
-                    ),
210
-                    'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
-                        'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
-                        'filename' => 'transactions_view_transaction_transaction_details_table'
213
-                    ),
214
-                    'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
-                        'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
-                        'filename' => 'transactions_view_transaction_attendees_registered'
217
-                    ),
218
-                    'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
-                        'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
-                        'filename' => 'transactions_view_transaction_primary_registrant_billing_information'
221
-                    ),
222
-                ),
223
-                'qtips'     => array('Transaction_Details_Tips'),
224
-                'help_tour' => array('Transaction_Details_Help_Tour'),
225
-                'metaboxes' => array('_transaction_details_metaboxes'),
226
-
227
-                'require_nonce' => false
228
-            )
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * The below methods aren't used by this class currently
235
-     */
236
-    protected function _add_screen_options()
237
-    {
238
-    }
239
-
240
-    protected function _add_feature_pointers()
241
-    {
242
-    }
243
-
244
-    public function admin_init()
245
-    {
246
-        // IF a registration was JUST added via the admin...
247
-        if (
248
-        isset(
249
-            $this->_req_data['redirect_from'],
250
-            $this->_req_data['EVT_ID'],
251
-            $this->_req_data['event_name']
252
-        )
253
-        ) {
254
-            // then set a cookie so that we can block any attempts to use
255
-            // the back button as a way to enter another registration.
256
-            setcookie('ee_registration_added', $this->_req_data['EVT_ID'], time() + WEEK_IN_SECONDS, '/');
257
-            // and update the global
258
-            $_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
259
-        }
260
-        EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__('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.',
261
-            'event_espresso');
262
-        EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__('An error occurred! Please refresh the page and try again.',
263
-            'event_espresso');
264
-        EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
265
-        EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
266
-        EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
267
-        EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__('This transaction has been overpaid ! Payments Total',
268
-            'event_espresso');
269
-    }
270
-
271
-    public function admin_notices()
272
-    {
273
-    }
274
-
275
-    public function admin_footer_scripts()
276
-    {
277
-    }
278
-
279
-
280
-    /**
281
-     * _set_transaction_status_array
282
-     * sets list of transaction statuses
283
-     *
284
-     * @access private
285
-     * @return void
286
-     */
287
-    private function _set_transaction_status_array()
288
-    {
289
-        self::$_txn_status = EEM_Transaction::instance()->status_array(true);
290
-    }
291
-
292
-
293
-    /**
294
-     * get_transaction_status_array
295
-     * return the transaction status array for wp_list_table
296
-     *
297
-     * @access public
298
-     * @return array
299
-     */
300
-    public function get_transaction_status_array()
301
-    {
302
-        return self::$_txn_status;
303
-    }
304
-
305
-
306
-    /**
307
-     *    get list of payment statuses
308
-     *
309
-     * @access private
310
-     * @return void
311
-     */
312
-    private function _get_payment_status_array()
313
-    {
314
-        self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
315
-        $this->_template_args['payment_status'] = self::$_pay_status;
316
-
317
-    }
318
-
319
-
320
-    /**
321
-     *    _add_screen_options_default
322
-     *
323
-     * @access protected
324
-     * @return void
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('espresso_txn', TXN_ASSETS_URL . 'espresso_transactions_admin.css', array(),
342
-            EVENT_ESPRESSO_VERSION);
343
-        wp_enqueue_style('espresso_txn');
344
-        //scripts
345
-        wp_register_script('espresso_txn', TXN_ASSETS_URL . 'espresso_transactions_admin.js', array(
346
-            'ee_admin_js',
347
-            'ee-datepicker',
348
-            'jquery-ui-datepicker',
349
-            'jquery-ui-draggable',
350
-            'ee-dialog',
351
-            'ee-accounting',
352
-            'ee-serialize-full-array'
353
-        ), EVENT_ESPRESSO_VERSION, true);
354
-        wp_enqueue_script('espresso_txn');
355
-
356
-    }
357
-
358
-
359
-    /**
360
-     *    load_scripts_styles_view_transaction
361
-     *
362
-     * @access public
363
-     * @return void
364
-     */
365
-    public function load_scripts_styles_view_transaction()
366
-    {
367
-        //styles
368
-        wp_enqueue_style('espresso-ui-theme');
369
-    }
370
-
371
-
372
-    /**
373
-     *    load_scripts_styles_default
374
-     *
375
-     * @access public
376
-     * @return void
377
-     */
378
-    public function load_scripts_styles_default()
379
-    {
380
-        //styles
381
-        wp_enqueue_style('espresso-ui-theme');
382
-    }
383
-
384
-
385
-    /**
386
-     *    _set_list_table_views_default
387
-     *
388
-     * @access protected
389
-     * @return void
390
-     */
391
-    protected function _set_list_table_views_default()
392
-    {
393
-        $this->_views = array(
394
-            'all'       => array(
395
-                'slug'  => 'all',
396
-                'label' => esc_html__('View All Transactions', 'event_espresso'),
397
-                'count' => 0
398
-            ),
399
-            'abandoned' => array(
400
-                'slug'  => 'abandoned',
401
-                'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
402
-                'count' => 0
403
-            ),
404
-            'failed'    => array(
405
-                'slug'  => 'failed',
406
-                'label' => esc_html__('Failed Transactions', 'event_espresso'),
407
-                'count' => 0
408
-            )
409
-        );
410
-    }
411
-
412
-
413
-    /**
414
-     * _set_transaction_object
415
-     * This sets the _transaction property for the transaction details screen
416
-     *
417
-     * @access private
418
-     * @return void
419
-     */
420
-    private function _set_transaction_object()
421
-    {
422
-        if (is_object($this->_transaction)) {
423
-            return;
424
-        } //get out we've already set the object
425
-
426
-        $TXN = EEM_Transaction::instance();
427
-
428
-        $TXN_ID = ( ! empty($this->_req_data['TXN_ID'])) ? absint($this->_req_data['TXN_ID']) : false;
429
-
430
-        //get transaction object
431
-        $this->_transaction = $TXN->get_one_by_ID($TXN_ID);
432
-        $this->_session     = ! empty($this->_transaction) ? $this->_transaction->get('TXN_session_data') : null;
433
-        $this->_transaction->verify_abandoned_transaction_status();
434
-
435
-        if (empty($this->_transaction)) {
436
-            $error_msg = esc_html__('An error occurred and the details for Transaction ID #',
437
-                    'event_espresso') . $TXN_ID . esc_html__(' could not be retrieved.', 'event_espresso');
438
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
439
-        }
440
-    }
441
-
442
-
443
-    /**
444
-     *    _transaction_legend_items
445
-     *
446
-     * @access protected
447
-     * @return array
448
-     */
449
-    protected function _transaction_legend_items()
450
-    {
451
-        EE_Registry::instance()->load_helper('MSG_Template');
452
-        $items = array();
453
-
454
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
455
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
456
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
457
-                $items['view_related_messages'] = array(
458
-                    'class' => $related_for_icon['css_class'],
459
-                    'desc'  => $related_for_icon['label'],
460
-                );
461
-            }
462
-        }
463
-
464
-        $items = apply_filters(
465
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
466
-            array_merge($items,
467
-                array(
468
-                    'view_details'      => array(
469
-                        'class' => 'dashicons dashicons-cart',
470
-                        'desc'  => esc_html__('View Transaction Details', 'event_espresso')
471
-                    ),
472
-                    'view_invoice'      => array(
473
-                        'class' => 'dashicons dashicons-media-spreadsheet',
474
-                        'desc'  => esc_html__('View Transaction Invoice', 'event_espresso')
475
-                    ),
476
-                    'view_receipt'      => array(
477
-                        'class' => 'dashicons dashicons-media-default',
478
-                        'desc'  => esc_html__('View Transaction Receipt', 'event_espresso')
479
-                    ),
480
-                    'view_registration' => array(
481
-                        'class' => 'dashicons dashicons-clipboard',
482
-                        'desc'  => esc_html__('View Registration Details', 'event_espresso')
483
-                    ),
484
-                    'payment_overview_link' => array(
485
-                        'class' => 'dashicons dashicons-money',
486
-                        'desc' => esc_html__('Make Payment on Frontend', 'event_espresso')
487
-                    )
488
-                )
489
-            )
490
-        );
491
-
492
-        if (EE_Registry::instance()->CAP->current_user_can('ee_send_message',
493
-            'espresso_transactions_send_payment_reminder')
494
-        ) {
495
-            if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
496
-                $items['send_payment_reminder'] = array(
497
-                    'class' => 'dashicons dashicons-email-alt',
498
-                    'desc'  => esc_html__('Send Payment Reminder', 'event_espresso')
499
-                );
500
-            } else {
501
-                $items['blank*'] = array(
502
-                    'class' => '',
503
-                    'desc'  => ''
504
-                );
505
-            }
506
-        } else {
507
-            $items['blank*'] = array(
508
-                'class' => '',
509
-                'desc'  => ''
510
-            );
511
-        }
512
-        $more_items = apply_filters(
513
-            'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
514
-            array(
515
-                'overpaid'   => array(
516
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
517
-                    'desc'  => EEH_Template::pretty_status(EEM_Transaction::overpaid_status_code, false, 'sentence')
518
-                ),
519
-                'complete'   => array(
520
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
521
-                    'desc'  => EEH_Template::pretty_status(EEM_Transaction::complete_status_code, false, 'sentence')
522
-                ),
523
-                'incomplete' => array(
524
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
525
-                    'desc'  => EEH_Template::pretty_status(EEM_Transaction::incomplete_status_code, false, 'sentence')
526
-                ),
527
-                'abandoned'  => array(
528
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
529
-                    'desc'  => EEH_Template::pretty_status(EEM_Transaction::abandoned_status_code, false, 'sentence')
530
-                ),
531
-                'failed'     => array(
532
-                    'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
533
-                    'desc'  => EEH_Template::pretty_status(EEM_Transaction::failed_status_code, false, 'sentence')
534
-                )
535
-            )
536
-        );
537
-
538
-        return array_merge($items, $more_items);
539
-    }
540
-
541
-
542
-    /**
543
-     *    _transactions_overview_list_table
544
-     *
545
-     * @access protected
546
-     * @return void
547
-     */
548
-    protected function _transactions_overview_list_table()
549
-    {
550
-        $this->_admin_page_title                   = esc_html__('Transactions', 'event_espresso');
551
-        $event                                     = isset($this->_req_data['EVT_ID']) ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']) : null;
552
-        $this->_template_args['admin_page_header'] = $event instanceof EE_Event ? sprintf(esc_html__('%sViewing Transactions for the Event: %s%s',
553
-            'event_espresso'), '<h3>',
554
-            '<a href="' . EE_Admin_Page::add_query_args_and_nonce(array('action' => 'edit', 'post' => $event->ID()),
555
-                EVENTS_ADMIN_URL) . '" title="' . esc_attr__('Click to Edit event',
556
-                'event_espresso') . '">' . $event->get('EVT_name') . '</a>', '</h3>') : '';
557
-        $this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
558
-        $this->display_admin_list_table_page_with_no_sidebar();
559
-    }
560
-
561
-
562
-    /**
563
-     *    _transaction_details
564
-     * generates HTML for the View Transaction Details Admin page
565
-     *
566
-     * @access protected
567
-     * @return void
568
-     */
569
-    protected function _transaction_details()
570
-    {
571
-        do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
572
-
573
-        $this->_set_transaction_status_array();
574
-
575
-        $this->_template_args                      = array();
576
-        $this->_template_args['transactions_page'] = $this->_wp_page_slug;
577
-
578
-        $this->_set_transaction_object();
579
-
580
-        $primary_registration = $this->_transaction->primary_registration();
581
-        $attendee             = $primary_registration instanceof EE_Registration ? $primary_registration->attendee() : null;
582
-
583
-        $this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
584
-        $this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
585
-
586
-        $this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
587
-        $this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
588
-
589
-        $this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->get('STS_ID')];
590
-        $this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
591
-        $this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
592
-
593
-        $this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
594
-        $this->_template_args['total_paid']  = $this->_transaction->get('TXN_paid');
595
-
596
-        if (
597
-            $attendee instanceof EE_Attendee
598
-            && EE_Registry::instance()->CAP->current_user_can(
599
-                'ee_send_message',
600
-                'espresso_transactions_send_payment_reminder'
601
-            )
602
-        ) {
603
-            $this->_template_args['send_payment_reminder_button'] =
604
-                EEH_MSG_Template::is_mt_active('payment_reminder')
605
-                && $this->_transaction->get('STS_ID') != EEM_Transaction::complete_status_code
606
-                && $this->_transaction->get('STS_ID') != EEM_Transaction::overpaid_status_code
607
-                    ? EEH_Template::get_button_or_link(
608
-                    EE_Admin_Page::add_query_args_and_nonce(
609
-                        array(
610
-                            'action'      => 'send_payment_reminder',
611
-                            'TXN_ID'      => $this->_transaction->ID(),
612
-                            'redirect_to' => 'view_transaction'
613
-                        ),
614
-                        TXN_ADMIN_URL
615
-                    ),
616
-                    __(' Send Payment Reminder', 'event_espresso'),
617
-                    'button secondary-button right',
618
-                    'dashicons dashicons-email-alt'
619
-                )
620
-                    : '';
621
-        } else {
622
-            $this->_template_args['send_payment_reminder_button'] = '';
623
-        }
624
-
625
-        $amount_due                         = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
626
-        $this->_template_args['amount_due'] = EEH_Template::format_currency($amount_due, true);
627
-        if (EE_Registry::instance()->CFG->currency->sign_b4) {
628
-            $this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign . $this->_template_args['amount_due'];
629
-        } else {
630
-            $this->_template_args['amount_due'] = $this->_template_args['amount_due'] . EE_Registry::instance()->CFG->currency->sign;
631
-        }
632
-        $this->_template_args['amount_due_class'] = '';
633
-
634
-        if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
635
-            // paid in full
636
-            $this->_template_args['amount_due'] = false;
637
-        } elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
638
-            // overpaid
639
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
640
-        } elseif (($this->_transaction->get('TXN_total') > 0) && ($this->_transaction->get('TXN_paid') > 0)) {
641
-            // monies owing
642
-            $this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
643
-        } elseif (($this->_transaction->get('TXN_total') > 0) && ($this->_transaction->get('TXN_paid') == 0)) {
644
-            // no payments made yet
645
-            $this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
646
-        } elseif ($this->_transaction->get('TXN_total') == 0) {
647
-            // free event
648
-            $this->_template_args['amount_due'] = false;
649
-        }
650
-
651
-        $payment_method = $this->_transaction->payment_method();
652
-
653
-        $this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
654
-            ? $payment_method->admin_name()
655
-            : esc_html__('Unknown', 'event_espresso');
656
-
657
-        $this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
658
-        // link back to overview
659
-        $this->_template_args['txn_overview_url'] = ! empty ($_SERVER['HTTP_REFERER'])
660
-            ? $_SERVER['HTTP_REFERER']
661
-            : TXN_ADMIN_URL;
662
-
663
-
664
-        // next link
665
-        $next_txn                                 = $this->_transaction->next(
666
-            null,
667
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
668
-            'TXN_ID'
669
-        );
670
-        $this->_template_args['next_transaction'] = $next_txn
671
-            ? $this->_next_link(
672
-                EE_Admin_Page::add_query_args_and_nonce(
673
-                    array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
674
-                    TXN_ADMIN_URL
675
-                ),
676
-                'dashicons dashicons-arrow-right ee-icon-size-22'
677
-            )
678
-            : '';
679
-        // previous link
680
-        $previous_txn                                 = $this->_transaction->previous(
681
-            null,
682
-            array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
683
-            'TXN_ID'
684
-        );
685
-        $this->_template_args['previous_transaction'] = $previous_txn
686
-            ? $this->_previous_link(
687
-                EE_Admin_Page::add_query_args_and_nonce(
688
-                    array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
689
-                    TXN_ADMIN_URL
690
-                ),
691
-                'dashicons dashicons-arrow-left ee-icon-size-22'
692
-            )
693
-            : '';
694
-
695
-        // were we just redirected here after adding a new registration ???
696
-        if (
697
-        isset(
698
-            $this->_req_data['redirect_from'],
699
-            $this->_req_data['EVT_ID'],
700
-            $this->_req_data['event_name']
701
-        )
702
-        ) {
703
-            if (
704
-            EE_Registry::instance()->CAP->current_user_can(
705
-                'ee_edit_registrations',
706
-                'espresso_registrations_new_registration',
707
-                $this->_req_data['EVT_ID']
708
-            )
709
-            ) {
710
-                $this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
711
-                $this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
712
-                    array(
713
-                        'page'     => 'espresso_registrations',
714
-                        'action'   => 'new_registration',
715
-                        'return'   => 'default',
716
-                        'TXN_ID'   => $this->_transaction->ID(),
717
-                        'event_id' => $this->_req_data['EVT_ID'],
718
-                    ),
719
-                    REG_ADMIN_URL
720
-                );
721
-                $this->_admin_page_title .= '">';
722
-
723
-                $this->_admin_page_title .= sprintf(
724
-                    esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
725
-                    htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
726
-                );
727
-                $this->_admin_page_title .= '</a>';
728
-            }
729
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
730
-        }
731
-        // grab messages at the last second
732
-        $this->_template_args['notices'] = EE_Error::get_notices();
733
-        // path to template
734
-        $template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
735
-        $this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
736
-            $this->_template_args, true);
737
-
738
-        // the details template wrapper
739
-        $this->display_admin_page_with_sidebar();
740
-
741
-    }
742
-
743
-
744
-    /**
745
-     *        _transaction_details_metaboxes
746
-     *
747
-     * @access protected
748
-     * @return void
749
-     */
750
-    protected function _transaction_details_metaboxes()
751
-    {
752
-
753
-        $this->_set_transaction_object();
754
-
755
-        add_meta_box('edit-txn-details-mbox', esc_html__('Transaction Details', 'event_espresso'),
756
-            array($this, 'txn_details_meta_box'), $this->_wp_page_slug, 'normal', 'high');
757
-        add_meta_box(
758
-            'edit-txn-attendees-mbox',
759
-            esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
760
-            array($this, 'txn_attendees_meta_box'),
761
-            $this->_wp_page_slug,
762
-            'normal',
763
-            'high',
764
-            array('TXN_ID' => $this->_transaction->ID())
765
-        );
766
-        add_meta_box('edit-txn-registrant-mbox', esc_html__('Primary Contact', 'event_espresso'),
767
-            array($this, 'txn_registrant_side_meta_box'), $this->_wp_page_slug, 'side', 'high');
768
-        add_meta_box('edit-txn-billing-info-mbox', esc_html__('Billing Information', 'event_espresso'),
769
-            array($this, 'txn_billing_info_side_meta_box'), $this->_wp_page_slug, 'side', 'high');
770
-
771
-    }
772
-
773
-
774
-    /**
775
-     * txn_details_meta_box
776
-     * generates HTML for the Transaction main meta box
777
-     *
778
-     * @access public
779
-     * @return void
780
-     */
781
-    public function txn_details_meta_box()
782
-    {
783
-
784
-        $this->_set_transaction_object();
785
-        $this->_template_args['TXN_ID']   = $this->_transaction->ID();
786
-        $this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration ? $this->_transaction->primary_registration()->attendee() : null;
787
-
788
-        //get line table
789
-        EEH_Autoloader::register_line_item_display_autoloaders();
790
-        $Line_Item_Display                       = new EE_Line_Item_Display('admin_table',
791
-            'EE_Admin_Table_Line_Item_Display_Strategy');
792
-        $this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item($this->_transaction->total_line_item());
793
-        $this->_template_args['REG_code']        = $this->_transaction->get_first_related('Registration')->get('REG_code');
794
-
795
-        // process taxes
796
-        $taxes                         = $this->_transaction->get_many_related('Line_Item',
797
-            array(array('LIN_type' => EEM_Line_Item::type_tax)));
798
-        $this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
799
-
800
-        $this->_template_args['grand_total']     = EEH_Template::format_currency($this->_transaction->get('TXN_total'),
801
-            false, false);
802
-        $this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
803
-        $this->_template_args['TXN_status']      = $this->_transaction->get('STS_ID');
30
+	/**
31
+	 * @var EE_Transaction
32
+	 */
33
+	private $_transaction;
34
+
35
+	/**
36
+	 * @var EE_Session
37
+	 */
38
+	private $_session;
39
+
40
+	/**
41
+	 * @var array $_txn_status
42
+	 */
43
+	private static $_txn_status;
44
+
45
+	/**
46
+	 * @var array $_pay_status
47
+	 */
48
+	private static $_pay_status;
49
+
50
+	/**
51
+	 * @var array $_existing_reg_payment_REG_IDs
52
+	 */
53
+	protected $_existing_reg_payment_REG_IDs = null;
54
+
55
+
56
+	/**
57
+	 * @Constructor
58
+	 * @access public
59
+	 *
60
+	 * @param bool $routing
61
+	 *
62
+	 * @return Transactions_Admin_Page
63
+	 */
64
+	public function __construct($routing = true)
65
+	{
66
+		parent::__construct($routing);
67
+	}
68
+
69
+
70
+	/**
71
+	 *    _init_page_props
72
+	 * @return void
73
+	 */
74
+	protected function _init_page_props()
75
+	{
76
+		$this->page_slug        = TXN_PG_SLUG;
77
+		$this->page_label       = esc_html__('Transactions', 'event_espresso');
78
+		$this->_admin_base_url  = TXN_ADMIN_URL;
79
+		$this->_admin_base_path = TXN_ADMIN;
80
+	}
81
+
82
+
83
+	/**
84
+	 *    _ajax_hooks
85
+	 * @return void
86
+	 */
87
+	protected function _ajax_hooks()
88
+	{
89
+		add_action('wp_ajax_espresso_apply_payment', array($this, 'apply_payments_or_refunds'));
90
+		add_action('wp_ajax_espresso_apply_refund', array($this, 'apply_payments_or_refunds'));
91
+		add_action('wp_ajax_espresso_delete_payment', array($this, 'delete_payment'));
92
+	}
93
+
94
+
95
+	/**
96
+	 *    _define_page_props
97
+	 * @return void
98
+	 */
99
+	protected function _define_page_props()
100
+	{
101
+		$this->_admin_page_title = $this->page_label;
102
+		$this->_labels           = array(
103
+			'buttons' => array(
104
+				'add'    => esc_html__('Add New Transaction', 'event_espresso'),
105
+				'edit'   => esc_html__('Edit Transaction', 'event_espresso'),
106
+				'delete' => esc_html__('Delete Transaction', 'event_espresso'),
107
+			)
108
+		);
109
+	}
110
+
111
+
112
+	/**
113
+	 *        grab url requests and route them
114
+	 * @access private
115
+	 * @return void
116
+	 */
117
+	public function _set_page_routes()
118
+	{
119
+
120
+		$this->_set_transaction_status_array();
121
+
122
+		$txn_id = ! empty($this->_req_data['TXN_ID']) && ! is_array($this->_req_data['TXN_ID']) ? $this->_req_data['TXN_ID'] : 0;
123
+
124
+		$this->_page_routes = array(
125
+
126
+			'default' => array(
127
+				'func'       => '_transactions_overview_list_table',
128
+				'capability' => 'ee_read_transactions'
129
+			),
130
+
131
+			'view_transaction' => array(
132
+				'func'       => '_transaction_details',
133
+				'capability' => 'ee_read_transaction',
134
+				'obj_id'     => $txn_id
135
+			),
136
+
137
+			'send_payment_reminder' => array(
138
+				'func'       => '_send_payment_reminder',
139
+				'noheader'   => true,
140
+				'capability' => 'ee_send_message'
141
+			),
142
+
143
+			'espresso_apply_payment' => array(
144
+				'func'       => 'apply_payments_or_refunds',
145
+				'noheader'   => true,
146
+				'capability' => 'ee_edit_payments'
147
+			),
148
+
149
+			'espresso_apply_refund' => array(
150
+				'func'       => 'apply_payments_or_refunds',
151
+				'noheader'   => true,
152
+				'capability' => 'ee_edit_payments'
153
+			),
154
+
155
+			'espresso_delete_payment' => array(
156
+				'func'       => 'delete_payment',
157
+				'noheader'   => true,
158
+				'capability' => 'ee_delete_payments'
159
+			),
160
+
161
+		);
162
+
163
+	}
164
+
165
+
166
+	protected function _set_page_config()
167
+	{
168
+		$this->_page_config = array(
169
+			'default'          => array(
170
+				'nav'           => array(
171
+					'label' => esc_html__('Overview', 'event_espresso'),
172
+					'order' => 10
173
+				),
174
+				'list_table'    => 'EE_Admin_Transactions_List_Table',
175
+				'help_tabs'     => array(
176
+					'transactions_overview_help_tab'                       => array(
177
+						'title'    => esc_html__('Transactions Overview', 'event_espresso'),
178
+						'filename' => 'transactions_overview'
179
+					),
180
+					'transactions_overview_table_column_headings_help_tab' => array(
181
+						'title'    => esc_html__('Transactions Table Column Headings', 'event_espresso'),
182
+						'filename' => 'transactions_overview_table_column_headings'
183
+					),
184
+					'transactions_overview_views_filters_help_tab'         => array(
185
+						'title'    => esc_html__('Transaction Views & Filters & Search', 'event_espresso'),
186
+						'filename' => 'transactions_overview_views_filters_search'
187
+					),
188
+				),
189
+				'help_tour'     => array('Transactions_Overview_Help_Tour'),
190
+				/**
191
+				 * commented out because currently we are not displaying tips for transaction list table status but this
192
+				 * may change in a later iteration so want to keep the code for then.
193
+				 */
194
+				//'qtips' => array( 'Transactions_List_Table_Tips' ),
195
+				'require_nonce' => false
196
+			),
197
+			'view_transaction' => array(
198
+				'nav'       => array(
199
+					'label'      => esc_html__('View Transaction', 'event_espresso'),
200
+					'order'      => 5,
201
+					'url'        => isset($this->_req_data['TXN_ID']) ? add_query_arg(array('TXN_ID' => $this->_req_data['TXN_ID']),
202
+						$this->_current_page_view_url) : $this->_admin_base_url,
203
+					'persistent' => false
204
+				),
205
+				'help_tabs' => array(
206
+					'transactions_view_transaction_help_tab'                                              => array(
207
+						'title'    => esc_html__('View Transaction', 'event_espresso'),
208
+						'filename' => 'transactions_view_transaction'
209
+					),
210
+					'transactions_view_transaction_transaction_details_table_help_tab'                    => array(
211
+						'title'    => esc_html__('Transaction Details Table', 'event_espresso'),
212
+						'filename' => 'transactions_view_transaction_transaction_details_table'
213
+					),
214
+					'transactions_view_transaction_attendees_registered_help_tab'                         => array(
215
+						'title'    => esc_html__('Attendees Registered', 'event_espresso'),
216
+						'filename' => 'transactions_view_transaction_attendees_registered'
217
+					),
218
+					'transactions_view_transaction_views_primary_registrant_billing_information_help_tab' => array(
219
+						'title'    => esc_html__('Primary Registrant & Billing Information', 'event_espresso'),
220
+						'filename' => 'transactions_view_transaction_primary_registrant_billing_information'
221
+					),
222
+				),
223
+				'qtips'     => array('Transaction_Details_Tips'),
224
+				'help_tour' => array('Transaction_Details_Help_Tour'),
225
+				'metaboxes' => array('_transaction_details_metaboxes'),
226
+
227
+				'require_nonce' => false
228
+			)
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * The below methods aren't used by this class currently
235
+	 */
236
+	protected function _add_screen_options()
237
+	{
238
+	}
239
+
240
+	protected function _add_feature_pointers()
241
+	{
242
+	}
243
+
244
+	public function admin_init()
245
+	{
246
+		// IF a registration was JUST added via the admin...
247
+		if (
248
+		isset(
249
+			$this->_req_data['redirect_from'],
250
+			$this->_req_data['EVT_ID'],
251
+			$this->_req_data['event_name']
252
+		)
253
+		) {
254
+			// then set a cookie so that we can block any attempts to use
255
+			// the back button as a way to enter another registration.
256
+			setcookie('ee_registration_added', $this->_req_data['EVT_ID'], time() + WEEK_IN_SECONDS, '/');
257
+			// and update the global
258
+			$_COOKIE['ee_registration_added'] = $this->_req_data['EVT_ID'];
259
+		}
260
+		EE_Registry::$i18n_js_strings['invalid_server_response'] = esc_html__('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.',
261
+			'event_espresso');
262
+		EE_Registry::$i18n_js_strings['error_occurred']          = esc_html__('An error occurred! Please refresh the page and try again.',
263
+			'event_espresso');
264
+		EE_Registry::$i18n_js_strings['txn_status_array']        = self::$_txn_status;
265
+		EE_Registry::$i18n_js_strings['pay_status_array']        = self::$_pay_status;
266
+		EE_Registry::$i18n_js_strings['payments_total']          = esc_html__('Payments Total', 'event_espresso');
267
+		EE_Registry::$i18n_js_strings['transaction_overpaid']    = esc_html__('This transaction has been overpaid ! Payments Total',
268
+			'event_espresso');
269
+	}
270
+
271
+	public function admin_notices()
272
+	{
273
+	}
274
+
275
+	public function admin_footer_scripts()
276
+	{
277
+	}
278
+
279
+
280
+	/**
281
+	 * _set_transaction_status_array
282
+	 * sets list of transaction statuses
283
+	 *
284
+	 * @access private
285
+	 * @return void
286
+	 */
287
+	private function _set_transaction_status_array()
288
+	{
289
+		self::$_txn_status = EEM_Transaction::instance()->status_array(true);
290
+	}
291
+
292
+
293
+	/**
294
+	 * get_transaction_status_array
295
+	 * return the transaction status array for wp_list_table
296
+	 *
297
+	 * @access public
298
+	 * @return array
299
+	 */
300
+	public function get_transaction_status_array()
301
+	{
302
+		return self::$_txn_status;
303
+	}
304
+
305
+
306
+	/**
307
+	 *    get list of payment statuses
308
+	 *
309
+	 * @access private
310
+	 * @return void
311
+	 */
312
+	private function _get_payment_status_array()
313
+	{
314
+		self::$_pay_status                      = EEM_Payment::instance()->status_array(true);
315
+		$this->_template_args['payment_status'] = self::$_pay_status;
316
+
317
+	}
318
+
319
+
320
+	/**
321
+	 *    _add_screen_options_default
322
+	 *
323
+	 * @access protected
324
+	 * @return void
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('espresso_txn', TXN_ASSETS_URL . 'espresso_transactions_admin.css', array(),
342
+			EVENT_ESPRESSO_VERSION);
343
+		wp_enqueue_style('espresso_txn');
344
+		//scripts
345
+		wp_register_script('espresso_txn', TXN_ASSETS_URL . 'espresso_transactions_admin.js', array(
346
+			'ee_admin_js',
347
+			'ee-datepicker',
348
+			'jquery-ui-datepicker',
349
+			'jquery-ui-draggable',
350
+			'ee-dialog',
351
+			'ee-accounting',
352
+			'ee-serialize-full-array'
353
+		), EVENT_ESPRESSO_VERSION, true);
354
+		wp_enqueue_script('espresso_txn');
355
+
356
+	}
357
+
358
+
359
+	/**
360
+	 *    load_scripts_styles_view_transaction
361
+	 *
362
+	 * @access public
363
+	 * @return void
364
+	 */
365
+	public function load_scripts_styles_view_transaction()
366
+	{
367
+		//styles
368
+		wp_enqueue_style('espresso-ui-theme');
369
+	}
370
+
371
+
372
+	/**
373
+	 *    load_scripts_styles_default
374
+	 *
375
+	 * @access public
376
+	 * @return void
377
+	 */
378
+	public function load_scripts_styles_default()
379
+	{
380
+		//styles
381
+		wp_enqueue_style('espresso-ui-theme');
382
+	}
383
+
384
+
385
+	/**
386
+	 *    _set_list_table_views_default
387
+	 *
388
+	 * @access protected
389
+	 * @return void
390
+	 */
391
+	protected function _set_list_table_views_default()
392
+	{
393
+		$this->_views = array(
394
+			'all'       => array(
395
+				'slug'  => 'all',
396
+				'label' => esc_html__('View All Transactions', 'event_espresso'),
397
+				'count' => 0
398
+			),
399
+			'abandoned' => array(
400
+				'slug'  => 'abandoned',
401
+				'label' => esc_html__('Abandoned Transactions', 'event_espresso'),
402
+				'count' => 0
403
+			),
404
+			'failed'    => array(
405
+				'slug'  => 'failed',
406
+				'label' => esc_html__('Failed Transactions', 'event_espresso'),
407
+				'count' => 0
408
+			)
409
+		);
410
+	}
411
+
412
+
413
+	/**
414
+	 * _set_transaction_object
415
+	 * This sets the _transaction property for the transaction details screen
416
+	 *
417
+	 * @access private
418
+	 * @return void
419
+	 */
420
+	private function _set_transaction_object()
421
+	{
422
+		if (is_object($this->_transaction)) {
423
+			return;
424
+		} //get out we've already set the object
425
+
426
+		$TXN = EEM_Transaction::instance();
427
+
428
+		$TXN_ID = ( ! empty($this->_req_data['TXN_ID'])) ? absint($this->_req_data['TXN_ID']) : false;
429
+
430
+		//get transaction object
431
+		$this->_transaction = $TXN->get_one_by_ID($TXN_ID);
432
+		$this->_session     = ! empty($this->_transaction) ? $this->_transaction->get('TXN_session_data') : null;
433
+		$this->_transaction->verify_abandoned_transaction_status();
434
+
435
+		if (empty($this->_transaction)) {
436
+			$error_msg = esc_html__('An error occurred and the details for Transaction ID #',
437
+					'event_espresso') . $TXN_ID . esc_html__(' could not be retrieved.', 'event_espresso');
438
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
439
+		}
440
+	}
441
+
442
+
443
+	/**
444
+	 *    _transaction_legend_items
445
+	 *
446
+	 * @access protected
447
+	 * @return array
448
+	 */
449
+	protected function _transaction_legend_items()
450
+	{
451
+		EE_Registry::instance()->load_helper('MSG_Template');
452
+		$items = array();
453
+
454
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
455
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
456
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
457
+				$items['view_related_messages'] = array(
458
+					'class' => $related_for_icon['css_class'],
459
+					'desc'  => $related_for_icon['label'],
460
+				);
461
+			}
462
+		}
463
+
464
+		$items = apply_filters(
465
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__items',
466
+			array_merge($items,
467
+				array(
468
+					'view_details'      => array(
469
+						'class' => 'dashicons dashicons-cart',
470
+						'desc'  => esc_html__('View Transaction Details', 'event_espresso')
471
+					),
472
+					'view_invoice'      => array(
473
+						'class' => 'dashicons dashicons-media-spreadsheet',
474
+						'desc'  => esc_html__('View Transaction Invoice', 'event_espresso')
475
+					),
476
+					'view_receipt'      => array(
477
+						'class' => 'dashicons dashicons-media-default',
478
+						'desc'  => esc_html__('View Transaction Receipt', 'event_espresso')
479
+					),
480
+					'view_registration' => array(
481
+						'class' => 'dashicons dashicons-clipboard',
482
+						'desc'  => esc_html__('View Registration Details', 'event_espresso')
483
+					),
484
+					'payment_overview_link' => array(
485
+						'class' => 'dashicons dashicons-money',
486
+						'desc' => esc_html__('Make Payment on Frontend', 'event_espresso')
487
+					)
488
+				)
489
+			)
490
+		);
491
+
492
+		if (EE_Registry::instance()->CAP->current_user_can('ee_send_message',
493
+			'espresso_transactions_send_payment_reminder')
494
+		) {
495
+			if (EEH_MSG_Template::is_mt_active('payment_reminder')) {
496
+				$items['send_payment_reminder'] = array(
497
+					'class' => 'dashicons dashicons-email-alt',
498
+					'desc'  => esc_html__('Send Payment Reminder', 'event_espresso')
499
+				);
500
+			} else {
501
+				$items['blank*'] = array(
502
+					'class' => '',
503
+					'desc'  => ''
504
+				);
505
+			}
506
+		} else {
507
+			$items['blank*'] = array(
508
+				'class' => '',
509
+				'desc'  => ''
510
+			);
511
+		}
512
+		$more_items = apply_filters(
513
+			'FHEE__Transactions_Admin_Page___transaction_legend_items__more_items',
514
+			array(
515
+				'overpaid'   => array(
516
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::overpaid_status_code,
517
+					'desc'  => EEH_Template::pretty_status(EEM_Transaction::overpaid_status_code, false, 'sentence')
518
+				),
519
+				'complete'   => array(
520
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::complete_status_code,
521
+					'desc'  => EEH_Template::pretty_status(EEM_Transaction::complete_status_code, false, 'sentence')
522
+				),
523
+				'incomplete' => array(
524
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::incomplete_status_code,
525
+					'desc'  => EEH_Template::pretty_status(EEM_Transaction::incomplete_status_code, false, 'sentence')
526
+				),
527
+				'abandoned'  => array(
528
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::abandoned_status_code,
529
+					'desc'  => EEH_Template::pretty_status(EEM_Transaction::abandoned_status_code, false, 'sentence')
530
+				),
531
+				'failed'     => array(
532
+					'class' => 'ee-status-legend ee-status-legend-' . EEM_Transaction::failed_status_code,
533
+					'desc'  => EEH_Template::pretty_status(EEM_Transaction::failed_status_code, false, 'sentence')
534
+				)
535
+			)
536
+		);
537
+
538
+		return array_merge($items, $more_items);
539
+	}
540
+
541
+
542
+	/**
543
+	 *    _transactions_overview_list_table
544
+	 *
545
+	 * @access protected
546
+	 * @return void
547
+	 */
548
+	protected function _transactions_overview_list_table()
549
+	{
550
+		$this->_admin_page_title                   = esc_html__('Transactions', 'event_espresso');
551
+		$event                                     = isset($this->_req_data['EVT_ID']) ? EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']) : null;
552
+		$this->_template_args['admin_page_header'] = $event instanceof EE_Event ? sprintf(esc_html__('%sViewing Transactions for the Event: %s%s',
553
+			'event_espresso'), '<h3>',
554
+			'<a href="' . EE_Admin_Page::add_query_args_and_nonce(array('action' => 'edit', 'post' => $event->ID()),
555
+				EVENTS_ADMIN_URL) . '" title="' . esc_attr__('Click to Edit event',
556
+				'event_espresso') . '">' . $event->get('EVT_name') . '</a>', '</h3>') : '';
557
+		$this->_template_args['after_list_table']  = $this->_display_legend($this->_transaction_legend_items());
558
+		$this->display_admin_list_table_page_with_no_sidebar();
559
+	}
560
+
561
+
562
+	/**
563
+	 *    _transaction_details
564
+	 * generates HTML for the View Transaction Details Admin page
565
+	 *
566
+	 * @access protected
567
+	 * @return void
568
+	 */
569
+	protected function _transaction_details()
570
+	{
571
+		do_action('AHEE__Transactions_Admin_Page__transaction_details__start', $this->_transaction);
572
+
573
+		$this->_set_transaction_status_array();
574
+
575
+		$this->_template_args                      = array();
576
+		$this->_template_args['transactions_page'] = $this->_wp_page_slug;
577
+
578
+		$this->_set_transaction_object();
579
+
580
+		$primary_registration = $this->_transaction->primary_registration();
581
+		$attendee             = $primary_registration instanceof EE_Registration ? $primary_registration->attendee() : null;
582
+
583
+		$this->_template_args['txn_nmbr']['value'] = $this->_transaction->ID();
584
+		$this->_template_args['txn_nmbr']['label'] = esc_html__('Transaction Number', 'event_espresso');
585
+
586
+		$this->_template_args['txn_datetime']['value'] = $this->_transaction->get_i18n_datetime('TXN_timestamp');
587
+		$this->_template_args['txn_datetime']['label'] = esc_html__('Date', 'event_espresso');
588
+
589
+		$this->_template_args['txn_status']['value'] = self::$_txn_status[$this->_transaction->get('STS_ID')];
590
+		$this->_template_args['txn_status']['label'] = esc_html__('Transaction Status', 'event_espresso');
591
+		$this->_template_args['txn_status']['class'] = 'status-' . $this->_transaction->get('STS_ID');
592
+
593
+		$this->_template_args['grand_total'] = $this->_transaction->get('TXN_total');
594
+		$this->_template_args['total_paid']  = $this->_transaction->get('TXN_paid');
595
+
596
+		if (
597
+			$attendee instanceof EE_Attendee
598
+			&& EE_Registry::instance()->CAP->current_user_can(
599
+				'ee_send_message',
600
+				'espresso_transactions_send_payment_reminder'
601
+			)
602
+		) {
603
+			$this->_template_args['send_payment_reminder_button'] =
604
+				EEH_MSG_Template::is_mt_active('payment_reminder')
605
+				&& $this->_transaction->get('STS_ID') != EEM_Transaction::complete_status_code
606
+				&& $this->_transaction->get('STS_ID') != EEM_Transaction::overpaid_status_code
607
+					? EEH_Template::get_button_or_link(
608
+					EE_Admin_Page::add_query_args_and_nonce(
609
+						array(
610
+							'action'      => 'send_payment_reminder',
611
+							'TXN_ID'      => $this->_transaction->ID(),
612
+							'redirect_to' => 'view_transaction'
613
+						),
614
+						TXN_ADMIN_URL
615
+					),
616
+					__(' Send Payment Reminder', 'event_espresso'),
617
+					'button secondary-button right',
618
+					'dashicons dashicons-email-alt'
619
+				)
620
+					: '';
621
+		} else {
622
+			$this->_template_args['send_payment_reminder_button'] = '';
623
+		}
624
+
625
+		$amount_due                         = $this->_transaction->get('TXN_total') - $this->_transaction->get('TXN_paid');
626
+		$this->_template_args['amount_due'] = EEH_Template::format_currency($amount_due, true);
627
+		if (EE_Registry::instance()->CFG->currency->sign_b4) {
628
+			$this->_template_args['amount_due'] = EE_Registry::instance()->CFG->currency->sign . $this->_template_args['amount_due'];
629
+		} else {
630
+			$this->_template_args['amount_due'] = $this->_template_args['amount_due'] . EE_Registry::instance()->CFG->currency->sign;
631
+		}
632
+		$this->_template_args['amount_due_class'] = '';
633
+
634
+		if ($this->_transaction->get('TXN_paid') == $this->_transaction->get('TXN_total')) {
635
+			// paid in full
636
+			$this->_template_args['amount_due'] = false;
637
+		} elseif ($this->_transaction->get('TXN_paid') > $this->_transaction->get('TXN_total')) {
638
+			// overpaid
639
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
640
+		} elseif (($this->_transaction->get('TXN_total') > 0) && ($this->_transaction->get('TXN_paid') > 0)) {
641
+			// monies owing
642
+			$this->_template_args['amount_due_class'] = 'txn-overview-part-payment-spn';
643
+		} elseif (($this->_transaction->get('TXN_total') > 0) && ($this->_transaction->get('TXN_paid') == 0)) {
644
+			// no payments made yet
645
+			$this->_template_args['amount_due_class'] = 'txn-overview-no-payment-spn';
646
+		} elseif ($this->_transaction->get('TXN_total') == 0) {
647
+			// free event
648
+			$this->_template_args['amount_due'] = false;
649
+		}
650
+
651
+		$payment_method = $this->_transaction->payment_method();
652
+
653
+		$this->_template_args['method_of_payment_name'] = $payment_method instanceof EE_Payment_Method
654
+			? $payment_method->admin_name()
655
+			: esc_html__('Unknown', 'event_espresso');
656
+
657
+		$this->_template_args['currency_sign'] = EE_Registry::instance()->CFG->currency->sign;
658
+		// link back to overview
659
+		$this->_template_args['txn_overview_url'] = ! empty ($_SERVER['HTTP_REFERER'])
660
+			? $_SERVER['HTTP_REFERER']
661
+			: TXN_ADMIN_URL;
662
+
663
+
664
+		// next link
665
+		$next_txn                                 = $this->_transaction->next(
666
+			null,
667
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
668
+			'TXN_ID'
669
+		);
670
+		$this->_template_args['next_transaction'] = $next_txn
671
+			? $this->_next_link(
672
+				EE_Admin_Page::add_query_args_and_nonce(
673
+					array('action' => 'view_transaction', 'TXN_ID' => $next_txn['TXN_ID']),
674
+					TXN_ADMIN_URL
675
+				),
676
+				'dashicons dashicons-arrow-right ee-icon-size-22'
677
+			)
678
+			: '';
679
+		// previous link
680
+		$previous_txn                                 = $this->_transaction->previous(
681
+			null,
682
+			array(array('STS_ID' => array('!=', EEM_Transaction::failed_status_code))),
683
+			'TXN_ID'
684
+		);
685
+		$this->_template_args['previous_transaction'] = $previous_txn
686
+			? $this->_previous_link(
687
+				EE_Admin_Page::add_query_args_and_nonce(
688
+					array('action' => 'view_transaction', 'TXN_ID' => $previous_txn['TXN_ID']),
689
+					TXN_ADMIN_URL
690
+				),
691
+				'dashicons dashicons-arrow-left ee-icon-size-22'
692
+			)
693
+			: '';
694
+
695
+		// were we just redirected here after adding a new registration ???
696
+		if (
697
+		isset(
698
+			$this->_req_data['redirect_from'],
699
+			$this->_req_data['EVT_ID'],
700
+			$this->_req_data['event_name']
701
+		)
702
+		) {
703
+			if (
704
+			EE_Registry::instance()->CAP->current_user_can(
705
+				'ee_edit_registrations',
706
+				'espresso_registrations_new_registration',
707
+				$this->_req_data['EVT_ID']
708
+			)
709
+			) {
710
+				$this->_admin_page_title .= '<a id="add-new-registration" class="add-new-h2 button-primary" href="';
711
+				$this->_admin_page_title .= EE_Admin_Page::add_query_args_and_nonce(
712
+					array(
713
+						'page'     => 'espresso_registrations',
714
+						'action'   => 'new_registration',
715
+						'return'   => 'default',
716
+						'TXN_ID'   => $this->_transaction->ID(),
717
+						'event_id' => $this->_req_data['EVT_ID'],
718
+					),
719
+					REG_ADMIN_URL
720
+				);
721
+				$this->_admin_page_title .= '">';
722
+
723
+				$this->_admin_page_title .= sprintf(
724
+					esc_html__('Add Another New Registration to Event: "%1$s" ?', 'event_espresso'),
725
+					htmlentities(urldecode($this->_req_data['event_name']), ENT_QUOTES, 'UTF-8')
726
+				);
727
+				$this->_admin_page_title .= '</a>';
728
+			}
729
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
730
+		}
731
+		// grab messages at the last second
732
+		$this->_template_args['notices'] = EE_Error::get_notices();
733
+		// path to template
734
+		$template_path                             = TXN_TEMPLATE_PATH . 'txn_admin_details_header.template.php';
735
+		$this->_template_args['admin_page_header'] = EEH_Template::display_template($template_path,
736
+			$this->_template_args, true);
737
+
738
+		// the details template wrapper
739
+		$this->display_admin_page_with_sidebar();
740
+
741
+	}
742
+
743
+
744
+	/**
745
+	 *        _transaction_details_metaboxes
746
+	 *
747
+	 * @access protected
748
+	 * @return void
749
+	 */
750
+	protected function _transaction_details_metaboxes()
751
+	{
752
+
753
+		$this->_set_transaction_object();
754
+
755
+		add_meta_box('edit-txn-details-mbox', esc_html__('Transaction Details', 'event_espresso'),
756
+			array($this, 'txn_details_meta_box'), $this->_wp_page_slug, 'normal', 'high');
757
+		add_meta_box(
758
+			'edit-txn-attendees-mbox',
759
+			esc_html__('Attendees Registered in this Transaction', 'event_espresso'),
760
+			array($this, 'txn_attendees_meta_box'),
761
+			$this->_wp_page_slug,
762
+			'normal',
763
+			'high',
764
+			array('TXN_ID' => $this->_transaction->ID())
765
+		);
766
+		add_meta_box('edit-txn-registrant-mbox', esc_html__('Primary Contact', 'event_espresso'),
767
+			array($this, 'txn_registrant_side_meta_box'), $this->_wp_page_slug, 'side', 'high');
768
+		add_meta_box('edit-txn-billing-info-mbox', esc_html__('Billing Information', 'event_espresso'),
769
+			array($this, 'txn_billing_info_side_meta_box'), $this->_wp_page_slug, 'side', 'high');
770
+
771
+	}
772
+
773
+
774
+	/**
775
+	 * txn_details_meta_box
776
+	 * generates HTML for the Transaction main meta box
777
+	 *
778
+	 * @access public
779
+	 * @return void
780
+	 */
781
+	public function txn_details_meta_box()
782
+	{
783
+
784
+		$this->_set_transaction_object();
785
+		$this->_template_args['TXN_ID']   = $this->_transaction->ID();
786
+		$this->_template_args['attendee'] = $this->_transaction->primary_registration() instanceof EE_Registration ? $this->_transaction->primary_registration()->attendee() : null;
787
+
788
+		//get line table
789
+		EEH_Autoloader::register_line_item_display_autoloaders();
790
+		$Line_Item_Display                       = new EE_Line_Item_Display('admin_table',
791
+			'EE_Admin_Table_Line_Item_Display_Strategy');
792
+		$this->_template_args['line_item_table'] = $Line_Item_Display->display_line_item($this->_transaction->total_line_item());
793
+		$this->_template_args['REG_code']        = $this->_transaction->get_first_related('Registration')->get('REG_code');
794
+
795
+		// process taxes
796
+		$taxes                         = $this->_transaction->get_many_related('Line_Item',
797
+			array(array('LIN_type' => EEM_Line_Item::type_tax)));
798
+		$this->_template_args['taxes'] = ! empty($taxes) ? $taxes : false;
799
+
800
+		$this->_template_args['grand_total']     = EEH_Template::format_currency($this->_transaction->get('TXN_total'),
801
+			false, false);
802
+		$this->_template_args['grand_raw_total'] = $this->_transaction->get('TXN_total');
803
+		$this->_template_args['TXN_status']      = $this->_transaction->get('STS_ID');
804 804
 
805 805
 //		$txn_status_class = 'status-' . $this->_transaction->get('STS_ID');
806 806
 
807
-        // process payment details
808
-        $payments = $this->_transaction->get_many_related('Payment');
809
-        if ( ! empty($payments)) {
810
-            $this->_template_args['payments']              = $payments;
811
-            $this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
812
-        } else {
813
-            $this->_template_args['payments']              = false;
814
-            $this->_template_args['existing_reg_payments'] = array();
815
-        }
816
-
817
-        $this->_template_args['edit_payment_url']   = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
818
-        $this->_template_args['delete_payment_url'] = add_query_arg(array('action' => 'espresso_delete_payment'),
819
-            TXN_ADMIN_URL);
820
-
821
-        if (isset($txn_details['invoice_number'])) {
822
-            $this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
823
-            $this->_template_args['txn_details']['invoice_number']['label'] = esc_html__('Invoice Number',
824
-                'event_espresso');
825
-        }
826
-
827
-        $this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction->get_first_related('Registration')->get('REG_session');
828
-        $this->_template_args['txn_details']['registration_session']['label'] = esc_html__('Registration Session',
829
-            'event_espresso');
830
-
831
-        $this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '';
832
-        $this->_template_args['txn_details']['ip_address']['label'] = esc_html__('Transaction placed from IP',
833
-            'event_espresso');
834
-
835
-        $this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '';
836
-        $this->_template_args['txn_details']['user_agent']['label'] = esc_html__('Registrant User Agent',
837
-            'event_espresso');
838
-
839
-        $reg_steps = '<ul>';
840
-        foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
841
-            if ($reg_step_status === true) {
842
-                $reg_steps .= '<li style="color:#70cc50">' . sprintf(esc_html__('%1$s : Completed', 'event_espresso'),
843
-                        ucwords(str_replace('_', ' ', $reg_step))) . '</li>';
844
-            } else if (is_numeric($reg_step_status) && $reg_step_status !== false) {
845
-                $reg_steps .= '<li style="color:#2EA2CC">' . sprintf(
846
-                        esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
847
-                        ucwords(str_replace('_', ' ', $reg_step)),
848
-                        date(get_option('date_format') . ' ' . get_option('time_format'),
849
-                            ($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)))
850
-                    ) . '</li>';
851
-            } else {
852
-                $reg_steps .= '<li style="color:#E76700">' . sprintf(esc_html__('%1$s : Never Initiated',
853
-                        'event_espresso'), ucwords(str_replace('_', ' ', $reg_step))) . '</li>';
854
-            }
855
-        }
856
-        $reg_steps .= '</ul>';
857
-        $this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
858
-        $this->_template_args['txn_details']['reg_steps']['label'] = esc_html__('Registration Step Progress',
859
-            'event_espresso');
860
-
861
-
862
-        $this->_get_registrations_to_apply_payment_to();
863
-        $this->_get_payment_methods($payments);
864
-        $this->_get_payment_status_array();
865
-        $this->_get_reg_status_selection(); //sets up the template args for the reg status array for the transaction.
866
-
867
-        $this->_template_args['transaction_form_url']    = add_query_arg(array(
868
-            'action'  => 'edit_transaction',
869
-            'process' => 'transaction'
870
-        ), TXN_ADMIN_URL);
871
-        $this->_template_args['apply_payment_form_url']  = add_query_arg(array(
872
-            'page'   => 'espresso_transactions',
873
-            'action' => 'espresso_apply_payment'
874
-        ), WP_AJAX_URL);
875
-        $this->_template_args['delete_payment_form_url'] = add_query_arg(array(
876
-            'page'   => 'espresso_transactions',
877
-            'action' => 'espresso_delete_payment'
878
-        ), WP_AJAX_URL);
879
-
880
-        // 'espresso_delete_payment_nonce'
881
-
882
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
883
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);
884
-
885
-    }
886
-
887
-
888
-    /**
889
-     * _get_registration_payment_IDs
890
-     *
891
-     *    generates an array of Payment IDs and their corresponding Registration IDs
892
-     *
893
-     * @access protected
894
-     *
895
-     * @param EE_Payment[] $payments
896
-     *
897
-     * @return array
898
-     */
899
-    protected function _get_registration_payment_IDs($payments = array())
900
-    {
901
-        $existing_reg_payments = array();
902
-        // get all reg payments for these payments
903
-        $reg_payments = EEM_Registration_Payment::instance()->get_all(array(
904
-            array(
905
-                'PAY_ID' => array(
906
-                    'IN',
907
-                    array_keys($payments)
908
-                )
909
-            )
910
-        ));
911
-        if ( ! empty($reg_payments)) {
912
-            foreach ($payments as $payment) {
913
-                if ( ! $payment instanceof EE_Payment) {
914
-                    continue;
915
-                } else if ( ! isset($existing_reg_payments[$payment->ID()])) {
916
-                    $existing_reg_payments[$payment->ID()] = array();
917
-                }
918
-                foreach ($reg_payments as $reg_payment) {
919
-                    if ($reg_payment instanceof EE_Registration_Payment && $reg_payment->payment_ID() === $payment->ID()) {
920
-                        $existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID();
921
-                    }
922
-                }
923
-            }
924
-        }
925
-
926
-        return $existing_reg_payments;
927
-    }
928
-
929
-
930
-    /**
931
-     * _get_registrations_to_apply_payment_to
932
-     *    generates HTML for displaying a series of checkboxes in the admin payment modal window
933
-     * which allows the admin to only apply the payment to the specific registrations
934
-     *
935
-     * @access protected
936
-     * @return void
937
-     * @throws \EE_Error
938
-     */
939
-    protected function _get_registrations_to_apply_payment_to()
940
-    {
941
-        // we want any registration with an active status (ie: not deleted or cancelled)
942
-        $query_params                      = array(
943
-            array(
944
-                'STS_ID' => array(
945
-                    'IN',
946
-                    array(
947
-                        EEM_Registration::status_id_approved,
948
-                        EEM_Registration::status_id_pending_payment,
949
-                        EEM_Registration::status_id_not_approved,
950
-                    )
951
-                )
952
-            )
953
-        );
954
-        $registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
955
-                '', 'txn-admin-apply-payment-to-registrations-dv', '', 'clear: both; margin: 1.5em 0 0; display: none;'
956
-            );
957
-        $registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
958
-        $registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
959
-        $registrations_to_apply_payment_to .= EEH_HTML::thead(
960
-            EEH_HTML::tr(
961
-                EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
962
-                EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
963
-                EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
964
-                EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
965
-                EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
966
-                EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
967
-                EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
968
-            )
969
-        );
970
-        $registrations_to_apply_payment_to .= EEH_HTML::tbody();
971
-        // get registrations for TXN
972
-        $registrations = $this->_transaction->registrations($query_params);
973
-        foreach ($registrations as $registration) {
974
-            if ($registration instanceof EE_Registration) {
975
-                $attendee_name = $registration->attendee() instanceof EE_Attendee
976
-                    ? $registration->attendee()->full_name()
977
-                    : esc_html__('Unknown Attendee', 'event_espresso');
978
-                $owing         = $registration->final_price() - $registration->paid();
979
-                $taxable       = $registration->ticket()->taxable()
980
-                    ? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
981
-                    : '';
982
-                $checked       = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
983
-                    ? ' checked="checked"'
984
-                    : '';
985
-                $disabled      = $registration->final_price() > 0 ? '' : ' disabled';
986
-                $registrations_to_apply_payment_to .= EEH_HTML::tr(
987
-                    EEH_HTML::td($registration->ID()) .
988
-                    EEH_HTML::td($attendee_name) .
989
-                    EEH_HTML::td(
990
-                        $registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
991
-                    ) .
992
-                    EEH_HTML::td($registration->event_name()) .
993
-                    EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
994
-                    EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
995
-                    EEH_HTML::td(
996
-                        '<input type="checkbox" value="' . $registration->ID()
997
-                        . '" name="txn_admin_payment[registrations]"'
998
-                        . $checked . $disabled . '>',
999
-                        '', 'jst-cntr'
1000
-                    ),
1001
-                    'apply-payment-registration-row-' . $registration->ID()
1002
-                );
1003
-            }
1004
-        }
1005
-        $registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1006
-        $registrations_to_apply_payment_to .= EEH_HTML::tablex();
1007
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1008
-        $registrations_to_apply_payment_to .= EEH_HTML::p(
1009
-            esc_html__(
1010
-                '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.',
1011
-                'event_espresso'
1012
-            ),
1013
-            '', 'clear description'
1014
-        );
1015
-        $registrations_to_apply_payment_to .= EEH_HTML::divx();
1016
-        $this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1017
-    }
1018
-
1019
-
1020
-    /**
1021
-     * _get_reg_status_selection
1022
-     *
1023
-     * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1024
-     *         instead of events.
1025
-     * @access protected
1026
-     * @return void
1027
-     */
1028
-    protected function _get_reg_status_selection()
1029
-    {
1030
-        //first get all possible statuses
1031
-        $statuses = EEM_Registration::reg_status_array(array(), true);
1032
-        //let's add a "don't change" option.
1033
-        $status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
1034
-        $status_array                                        = array_merge($status_array, $statuses);
1035
-        $this->_template_args['status_change_select']        = EEH_Form_Fields::select_input('txn_reg_status_change[reg_status]',
1036
-            $status_array, 'NAN', 'id="txn-admin-payment-reg-status-inp"', 'txn-reg-status-change-reg-status');
1037
-        $this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input('delete_txn_reg_status_change[reg_status]',
1038
-            $status_array, 'NAN', 'delete-txn-admin-payment-reg-status-inp', 'delete-txn-reg-status-change-reg-status');
1039
-
1040
-    }
1041
-
1042
-
1043
-    /**
1044
-     *    _get_payment_methods
1045
-     * Gets all the payment methods available generally, or the ones that are already
1046
-     * selected on these payments (in case their payment methods are no longer active).
1047
-     * Has the side-effect of updating the template args' payment_methods item
1048
-     * @access private
1049
-     *
1050
-     * @param EE_Payment[] to show on this page
1051
-     *
1052
-     * @return void
1053
-     */
1054
-    private function _get_payment_methods($payments = array())
1055
-    {
1056
-        $payment_methods_of_payments = array();
1057
-        foreach ($payments as $payment) {
1058
-            if ($payment instanceof EE_Payment) {
1059
-                $payment_methods_of_payments[] = $payment->get('PMD_ID');
1060
-            }
1061
-        }
1062
-        if ($payment_methods_of_payments) {
1063
-            $query_args = array(
1064
-                array(
1065
-                    'OR*payment_method_for_payment' => array(
1066
-                        'PMD_ID'    => array('IN', $payment_methods_of_payments),
1067
-                        'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')
1068
-                    )
1069
-                )
1070
-            );
1071
-        } else {
1072
-            $query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1073
-        }
1074
-        $this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1075
-    }
1076
-
1077
-
1078
-    /**
1079
-     * txn_attendees_meta_box
1080
-     *    generates HTML for the Attendees Transaction main meta box
1081
-     *
1082
-     * @access public
1083
-     *
1084
-     * @param WP_Post $post
1085
-     * @param array   $metabox
1086
-     *
1087
-     * @return void
1088
-     */
1089
-    public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1090
-    {
1091
-
1092
-        extract($metabox['args']);
1093
-        $this->_template_args['post']            = $post;
1094
-        $this->_template_args['event_attendees'] = array();
1095
-        // process items in cart
1096
-        $line_items = $this->_transaction->get_many_related('Line_Item', array(array('LIN_type' => 'line-item')));
1097
-        if ( ! empty($line_items)) {
1098
-            foreach ($line_items as $item) {
1099
-                if ($item instanceof EE_Line_Item) {
1100
-                    switch ($item->OBJ_type()) {
1101
-
1102
-                        case 'Event' :
1103
-                            break;
1104
-
1105
-                        case 'Ticket' :
1106
-                            $ticket = $item->ticket();
1107
-                            //right now we're only handling tickets here.  Cause its expected that only tickets will have attendees right?
1108
-                            if ( ! $ticket instanceof EE_Ticket) {
1109
-                                continue;
1110
-                            }
1111
-                            try {
1112
-                                $event_name = $ticket->get_event_name();
1113
-                            } catch (Exception $e) {
1114
-                                EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1115
-                                $event_name = esc_html__('Unknown Event', 'event_espresso');
1116
-                            }
1117
-                            $event_name .= ' - ' . $item->get('LIN_name');
1118
-                            $ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1119
-                            // now get all of the registrations for this transaction that use this ticket
1120
-                            $registrations = $ticket->get_many_related('Registration',
1121
-                                array(array('TXN_ID' => $this->_transaction->ID())));
1122
-                            foreach ($registrations as $registration) {
1123
-                                if ( ! $registration instanceof EE_Registration) {
1124
-                                    continue;
1125
-                                }
1126
-                                $this->_template_args['event_attendees'][$registration->ID()]['STS_ID']            = $registration->status_ID();
1127
-                                $this->_template_args['event_attendees'][$registration->ID()]['att_num']           = $registration->count();
1128
-                                $this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name'] = $event_name;
1129
-                                $this->_template_args['event_attendees'][$registration->ID()]['ticket_price']      = $ticket_price;
1130
-                                // attendee info
1131
-                                $attendee = $registration->get_first_related('Attendee');
1132
-                                if ($attendee instanceof EE_Attendee) {
1133
-                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']   = $attendee->ID();
1134
-                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = $attendee->full_name();
1135
-                                    $this->_template_args['event_attendees'][$registration->ID()]['email']    = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name . esc_html__(' Event',
1136
-                                            'event_espresso') . '">' . $attendee->email() . '</a>';
1137
-                                    $this->_template_args['event_attendees'][$registration->ID()]['address']  = EEH_Address::format($attendee,
1138
-                                        'inline', false, false);
1139
-                                } else {
1140
-                                    $this->_template_args['event_attendees'][$registration->ID()]['att_id']   = '';
1141
-                                    $this->_template_args['event_attendees'][$registration->ID()]['attendee'] = '';
1142
-                                    $this->_template_args['event_attendees'][$registration->ID()]['email']    = '';
1143
-                                    $this->_template_args['event_attendees'][$registration->ID()]['address']  = '';
1144
-                                }
1145
-                            }
1146
-                            break;
1147
-
1148
-                    }
1149
-                }
1150
-            }
1151
-
1152
-            $this->_template_args['transaction_form_url'] = add_query_arg(array(
1153
-                'action'  => 'edit_transaction',
1154
-                'process' => 'attendees'
1155
-            ), TXN_ADMIN_URL);
1156
-            echo EEH_Template::display_template(TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1157
-                $this->_template_args, true);
1158
-
1159
-        } else {
1160
-            echo sprintf(
1161
-                esc_html__('%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1162
-                    'event_espresso'),
1163
-                '<p class="important-notice">',
1164
-                '</p>'
1165
-            );
1166
-        }
1167
-    }
1168
-
1169
-
1170
-    /**
1171
-     * txn_registrant_side_meta_box
1172
-     * generates HTML for the Edit Transaction side meta box
1173
-     *
1174
-     * @access public
1175
-     * @throws \EE_Error
1176
-     * @return void
1177
-     */
1178
-    public function txn_registrant_side_meta_box()
1179
-    {
1180
-        $primary_att = $this->_transaction->primary_registration() instanceof EE_Registration ? $this->_transaction->primary_registration()->get_first_related('Attendee') : null;
1181
-        if ( ! $primary_att instanceof EE_Attendee) {
1182
-            $this->_template_args['no_attendee_message'] = esc_html__('There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1183
-                'event_espresso');
1184
-            $primary_att                                 = EEM_Attendee::instance()->create_default_object();
1185
-        }
1186
-        $this->_template_args['ATT_ID']            = $primary_att->ID();
1187
-        $this->_template_args['prime_reg_fname']   = $primary_att->fname();
1188
-        $this->_template_args['prime_reg_lname']   = $primary_att->lname();
1189
-        $this->_template_args['prime_reg_email']   = $primary_att->email();
1190
-        $this->_template_args['prime_reg_phone']   = $primary_att->phone();
1191
-        $this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(array(
1192
-            'action' => 'edit_attendee',
1193
-            'post'   => $primary_att->ID()
1194
-        ), REG_ADMIN_URL);
1195
-        // get formatted address for registrant
1196
-        $this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1197
-        echo EEH_Template::display_template(TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1198
-            $this->_template_args, true);
1199
-    }
1200
-
1201
-
1202
-    /**
1203
-     * txn_billing_info_side_meta_box
1204
-     *    generates HTML for the Edit Transaction side meta box
1205
-     *
1206
-     * @access public
1207
-     * @return void
1208
-     */
1209
-    public function txn_billing_info_side_meta_box()
1210
-    {
1211
-
1212
-        $this->_template_args['billing_form']     = $this->_transaction->billing_info();
1213
-        $this->_template_args['billing_form_url'] = add_query_arg(
1214
-            array('action' => 'edit_transaction', 'process' => 'billing'),
1215
-            TXN_ADMIN_URL
1216
-        );
1217
-
1218
-        $template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1219
-        echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1220
-    }
1221
-
1222
-
1223
-    /**
1224
-     * apply_payments_or_refunds
1225
-     *    registers a payment or refund made towards a transaction
1226
-     *
1227
-     * @access public
1228
-     * @return void
1229
-     */
1230
-    public function apply_payments_or_refunds()
1231
-    {
1232
-        $json_response_data = array('return_data' => false);
1233
-        $valid_data         = $this->_validate_payment_request_data();
1234
-        if ( ! empty($valid_data)) {
1235
-            $PAY_ID = $valid_data['PAY_ID'];
1236
-            //save  the new payment
1237
-            $payment = $this->_create_payment_from_request_data($valid_data);
1238
-            // get the TXN for this payment
1239
-            $transaction = $payment->transaction();
1240
-            // verify transaction
1241
-            if ($transaction instanceof EE_Transaction) {
1242
-                // calculate_total_payments_and_update_status
1243
-                $this->_process_transaction_payments($transaction);
1244
-                $REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1245
-                $this->_remove_existing_registration_payments($payment, $PAY_ID);
1246
-                // apply payment to registrations (if applicable)
1247
-                if ( ! empty($REG_IDs)) {
1248
-                    $this->_update_registration_payments($transaction, $payment, $REG_IDs);
1249
-                    $this->_maybe_send_notifications();
1250
-                    // now process status changes for the same registrations
1251
-                    $this->_process_registration_status_change($transaction, $REG_IDs);
1252
-                }
1253
-                $this->_maybe_send_notifications($payment);
1254
-                //prepare to render page
1255
-                $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1256
-                do_action('AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording', $transaction,
1257
-                    $payment);
1258
-            } else {
1259
-                EE_Error::add_error(
1260
-                    esc_html__('A valid Transaction for this payment could not be retrieved.', 'event_espresso'),
1261
-                    __FILE__, __FUNCTION__, __LINE__
1262
-                );
1263
-            }
1264
-        } else {
1265
-            EE_Error::add_error(esc_html__('The payment form data could not be processed. Please try again.',
1266
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1267
-        }
1268
-
1269
-        $notices              = EE_Error::get_notices(false, false, false);
1270
-        $this->_template_args = array(
1271
-            'data'    => $json_response_data,
1272
-            'error'   => $notices['errors'],
1273
-            'success' => $notices['success']
1274
-        );
1275
-        $this->_return_json();
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * _validate_payment_request_data
1281
-     *
1282
-     * @return array
1283
-     */
1284
-    protected function _validate_payment_request_data()
1285
-    {
1286
-        if ( ! isset($this->_req_data['txn_admin_payment'])) {
1287
-            return false;
1288
-        }
1289
-        $payment_form = $this->_generate_payment_form_section();
1290
-        try {
1291
-            if ($payment_form->was_submitted()) {
1292
-                $payment_form->receive_form_submission();
1293
-                if ( ! $payment_form->is_valid()) {
1294
-                    $submission_error_messages = array();
1295
-                    foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1296
-                        if ($validation_error instanceof EE_Validation_Error) {
1297
-                            $submission_error_messages[] = sprintf(
1298
-                                _x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1299
-                                $validation_error->get_form_section()->html_label_text(),
1300
-                                $validation_error->getMessage()
1301
-                            );
1302
-                        }
1303
-                    }
1304
-                    EE_Error::add_error(join('<br />', $submission_error_messages), __FILE__, __FUNCTION__, __LINE__);
1305
-
1306
-                    return array();
1307
-                }
1308
-            }
1309
-        } catch (EE_Error $e) {
1310
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1311
-
1312
-            return array();
1313
-        }
1314
-
1315
-        return $payment_form->valid_data();
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * _generate_payment_form_section
1321
-     *
1322
-     * @return EE_Form_Section_Proper
1323
-     */
1324
-    protected function _generate_payment_form_section()
1325
-    {
1326
-        return new EE_Form_Section_Proper(
1327
-            array(
1328
-                'name'        => 'txn_admin_payment',
1329
-                'subsections' => array(
1330
-                    'PAY_ID'          => new EE_Text_Input(
1331
-                        array(
1332
-                            'default'               => 0,
1333
-                            'required'              => false,
1334
-                            'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1335
-                            'validation_strategies' => array(new EE_Int_Normalization())
1336
-                        )
1337
-                    ),
1338
-                    'TXN_ID'          => new EE_Text_Input(
1339
-                        array(
1340
-                            'default'               => 0,
1341
-                            'required'              => true,
1342
-                            'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1343
-                            'validation_strategies' => array(new EE_Int_Normalization())
1344
-                        )
1345
-                    ),
1346
-                    'type'            => new EE_Text_Input(
1347
-                        array(
1348
-                            'default'               => 1,
1349
-                            'required'              => true,
1350
-                            'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1351
-                            'validation_strategies' => array(new EE_Int_Normalization())
1352
-                        )
1353
-                    ),
1354
-                    'amount'          => new EE_Text_Input(
1355
-                        array(
1356
-                            'default'               => 0,
1357
-                            'required'              => true,
1358
-                            'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1359
-                            'validation_strategies' => array(new EE_Float_Normalization())
1360
-                        )
1361
-                    ),
1362
-                    'status'          => new EE_Text_Input(
1363
-                        array(
1364
-                            'default'         => EEM_Payment::status_id_approved,
1365
-                            'required'        => true,
1366
-                            'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1367
-                        )
1368
-                    ),
1369
-                    'PMD_ID'          => new EE_Text_Input(
1370
-                        array(
1371
-                            'default'               => 2,
1372
-                            'required'              => true,
1373
-                            'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1374
-                            'validation_strategies' => array(new EE_Int_Normalization())
1375
-                        )
1376
-                    ),
1377
-                    'date'            => new EE_Text_Input(
1378
-                        array(
1379
-                            'default'         => time(),
1380
-                            'required'        => true,
1381
-                            'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1382
-                        )
1383
-                    ),
1384
-                    'txn_id_chq_nmbr' => new EE_Text_Input(
1385
-                        array(
1386
-                            'default'               => '',
1387
-                            'required'              => false,
1388
-                            'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1389
-                            'validation_strategies' => array(
1390
-                                new EE_Max_Length_Validation_Strategy(esc_html__('Input too long', 'event_espresso'),
1391
-                                    100),
1392
-                            )
1393
-                        )
1394
-                    ),
1395
-                    'po_number'       => new EE_Text_Input(
1396
-                        array(
1397
-                            'default'               => '',
1398
-                            'required'              => false,
1399
-                            'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1400
-                            'validation_strategies' => array(
1401
-                                new EE_Max_Length_Validation_Strategy(esc_html__('Input too long', 'event_espresso'),
1402
-                                    100),
1403
-                            )
1404
-                        )
1405
-                    ),
1406
-                    'accounting'      => new EE_Text_Input(
1407
-                        array(
1408
-                            'default'               => '',
1409
-                            'required'              => false,
1410
-                            'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1411
-                            'validation_strategies' => array(
1412
-                                new EE_Max_Length_Validation_Strategy(esc_html__('Input too long', 'event_espresso'),
1413
-                                    100),
1414
-                            )
1415
-                        )
1416
-                    ),
1417
-                )
1418
-            )
1419
-        );
1420
-    }
1421
-
1422
-
1423
-    /**
1424
-     * _create_payment_from_request_data
1425
-     *
1426
-     * @param array $valid_data
1427
-     *
1428
-     * @return EE_Payment
1429
-     */
1430
-    protected function _create_payment_from_request_data($valid_data)
1431
-    {
1432
-        $PAY_ID = $valid_data['PAY_ID'];
1433
-        // get payment amount
1434
-        $amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1435
-        // payments have a type value of 1 and refunds have a type value of -1
1436
-        // so multiplying amount by type will give a positive value for payments, and negative values for refunds
1437
-        $amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1438
-        // for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1439
-        $date    = $valid_data['date'] ? preg_replace('/\s+/', ' ', $valid_data['date']) : date('Y-m-d g:i a',
1440
-            current_time('timestamp'));
1441
-        $payment = EE_Payment::new_instance(
1442
-            array(
1443
-                'TXN_ID'              => $valid_data['TXN_ID'],
1444
-                'STS_ID'              => $valid_data['status'],
1445
-                'PAY_timestamp'       => $date,
1446
-                'PAY_source'          => EEM_Payment_Method::scope_admin,
1447
-                'PMD_ID'              => $valid_data['PMD_ID'],
1448
-                'PAY_amount'          => $amount,
1449
-                'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1450
-                'PAY_po_number'       => $valid_data['po_number'],
1451
-                'PAY_extra_accntng'   => $valid_data['accounting'],
1452
-                'PAY_details'         => $valid_data,
1453
-                'PAY_ID'              => $PAY_ID
1454
-            ),
1455
-            '',
1456
-            array('Y-m-d', 'g:i a')
1457
-        );
1458
-
1459
-        if ( ! $payment->save()) {
1460
-            EE_Error::add_error(
1461
-                sprintf(
1462
-                    esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1463
-                    $payment->ID()
1464
-                ),
1465
-                __FILE__, __FUNCTION__, __LINE__
1466
-            );
1467
-        }
1468
-
1469
-        return $payment;
1470
-    }
1471
-
1472
-
1473
-    /**
1474
-     * _process_transaction_payments
1475
-     *
1476
-     * @param \EE_Transaction $transaction
1477
-     *
1478
-     * @return array
1479
-     */
1480
-    protected function _process_transaction_payments(EE_Transaction $transaction)
1481
-    {
1482
-        /** @type EE_Transaction_Payments $transaction_payments */
1483
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1484
-        //update the transaction with this payment
1485
-        if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1486
-            EE_Error::add_success(esc_html__('The payment has been processed successfully.', 'event_espresso'),
1487
-                __FILE__, __FUNCTION__, __LINE__);
1488
-        } else {
1489
-            EE_Error::add_error(
1490
-                esc_html__('The payment was processed successfully but the amount paid for the transaction was not updated.',
1491
-                    'event_espresso')
1492
-                , __FILE__, __FUNCTION__, __LINE__
1493
-            );
1494
-        }
1495
-    }
1496
-
1497
-
1498
-    /**
1499
-     * _get_REG_IDs_to_apply_payment_to
1500
-     *
1501
-     * returns a list of registration IDs that the payment will apply to
1502
-     *
1503
-     * @param \EE_Payment $payment
1504
-     *
1505
-     * @return array
1506
-     */
1507
-    protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1508
-    {
1509
-        $REG_IDs = array();
1510
-        // grab array of IDs for specific registrations to apply changes to
1511
-        if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1512
-            $REG_IDs = (array)$this->_req_data['txn_admin_payment']['registrations'];
1513
-        }
1514
-        //nothing specified ? then get all reg IDs
1515
-        if (empty($REG_IDs)) {
1516
-            $registrations = $payment->transaction()->registrations();
1517
-            $REG_IDs       = ! empty($registrations) ? array_keys($registrations) : $this->_get_existing_reg_payment_REG_IDs($payment);
1518
-        }
1519
-
1520
-        // ensure that REG_IDs are integers and NOT strings
1521
-        return array_map('intval', $REG_IDs);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * @return array
1527
-     */
1528
-    public function existing_reg_payment_REG_IDs()
1529
-    {
1530
-        return $this->_existing_reg_payment_REG_IDs;
1531
-    }
1532
-
1533
-
1534
-    /**
1535
-     * @param array $existing_reg_payment_REG_IDs
1536
-     */
1537
-    public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1538
-    {
1539
-        $this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1540
-    }
1541
-
1542
-
1543
-    /**
1544
-     * _get_existing_reg_payment_REG_IDs
1545
-     *
1546
-     * returns a list of registration IDs that the payment is currently related to
1547
-     * as recorded in the database
1548
-     *
1549
-     * @param \EE_Payment $payment
1550
-     *
1551
-     * @return array
1552
-     */
1553
-    protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1554
-    {
1555
-        if ($this->existing_reg_payment_REG_IDs() === null) {
1556
-            // let's get any existing reg payment records for this payment
1557
-            $existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1558
-            // but we only want the REG IDs, so grab the array keys
1559
-            $existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs) ? array_keys($existing_reg_payment_REG_IDs) : array();
1560
-            $this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1561
-        }
1562
-
1563
-        return $this->existing_reg_payment_REG_IDs();
1564
-    }
1565
-
1566
-
1567
-    /**
1568
-     * _remove_existing_registration_payments
1569
-     *
1570
-     * this calculates the difference between existing relations
1571
-     * to the supplied payment and the new list registration IDs,
1572
-     * removes any related registrations that no longer apply,
1573
-     * and then updates the registration paid fields
1574
-     *
1575
-     * @param \EE_Payment $payment
1576
-     * @param int         $PAY_ID
1577
-     *
1578
-     * @return bool;
1579
-     */
1580
-    protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
1581
-    {
1582
-        // newly created payments will have nothing recorded for $PAY_ID
1583
-        if ($PAY_ID == 0) {
1584
-            return false;
1585
-        }
1586
-        $existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1587
-        if (empty($existing_reg_payment_REG_IDs)) {
1588
-            return false;
1589
-        }
1590
-        /** @type EE_Transaction_Payments $transaction_payments */
1591
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1592
-
1593
-        return $transaction_payments->delete_registration_payments_and_update_registrations(
1594
-            $payment,
1595
-            array(
1596
-                array(
1597
-                    'PAY_ID' => $payment->ID(),
1598
-                    'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
1599
-                )
1600
-            )
1601
-        );
1602
-    }
1603
-
1604
-
1605
-    /**
1606
-     * _update_registration_payments
1607
-     *
1608
-     * this applies the payments to the selected registrations
1609
-     * but only if they have not already been paid for
1610
-     *
1611
-     * @param  EE_Transaction $transaction
1612
-     * @param \EE_Payment     $payment
1613
-     * @param array           $REG_IDs
1614
-     *
1615
-     * @return bool
1616
-     */
1617
-    protected function _update_registration_payments(
1618
-        EE_Transaction $transaction,
1619
-        EE_Payment $payment,
1620
-        $REG_IDs = array()
1621
-    ) {
1622
-        // we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
1623
-        // so let's do that using our set of REG_IDs from the form
1624
-        $registration_query_where_params = array(
1625
-            'REG_ID' => array('IN', $REG_IDs)
1626
-        );
1627
-        // but add in some conditions regarding payment,
1628
-        // so that we don't apply payments to registrations that are free or have already been paid for
1629
-        // but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
1630
-        if ( ! $payment->is_a_refund()) {
1631
-            $registration_query_where_params['REG_final_price']  = array('!=', 0);
1632
-            $registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
1633
-        }
1634
-        //EEH_Debug_Tools::printr( $registration_query_where_params, '$registration_query_where_params', __FILE__, __LINE__ );
1635
-        $registrations = $transaction->registrations(array($registration_query_where_params));
1636
-        if ( ! empty($registrations)) {
1637
-            /** @type EE_Payment_Processor $payment_processor */
1638
-            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
1639
-            $payment_processor->process_registration_payments($transaction, $payment, $registrations);
1640
-        }
1641
-    }
1642
-
1643
-
1644
-    /**
1645
-     * _process_registration_status_change
1646
-     *
1647
-     * This processes requested registration status changes for all the registrations
1648
-     * on a given transaction and (optionally) sends out notifications for the changes.
1649
-     *
1650
-     * @param  EE_Transaction $transaction
1651
-     * @param array           $REG_IDs
1652
-     *
1653
-     * @return bool
1654
-     */
1655
-    protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
1656
-    {
1657
-        // first if there is no change in status then we get out.
1658
-        if (
1659
-            ! isset($this->_req_data['txn_reg_status_change'], $this->_req_data['txn_reg_status_change']['reg_status'])
1660
-            || $this->_req_data['txn_reg_status_change']['reg_status'] == 'NAN'
1661
-        ) {
1662
-            //no error message, no change requested, just nothing to do man.
1663
-            return false;
1664
-        }
1665
-        /** @type EE_Transaction_Processor $transaction_processor */
1666
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1667
-
1668
-        // made it here dude?  Oh WOW.  K, let's take care of changing the statuses
1669
-        return $transaction_processor->manually_update_registration_statuses(
1670
-            $transaction,
1671
-            sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
1672
-            array(array('REG_ID' => array('IN', $REG_IDs)))
1673
-        );
1674
-    }
1675
-
1676
-
1677
-    /**
1678
-     * _build_payment_json_response
1679
-     *
1680
-     * @access public
1681
-     *
1682
-     * @param \EE_Payment $payment
1683
-     * @param array       $REG_IDs
1684
-     * @param bool | null $delete_txn_reg_status_change
1685
-     *
1686
-     * @return array
1687
-     */
1688
-    protected function _build_payment_json_response(
1689
-        EE_Payment $payment,
1690
-        $REG_IDs = array(),
1691
-        $delete_txn_reg_status_change = null
1692
-    ) {
1693
-        // was the payment deleted ?
1694
-        if (is_bool($delete_txn_reg_status_change)) {
1695
-            return array(
1696
-                'PAY_ID'                       => $payment->ID(),
1697
-                'amount'                       => $payment->amount(),
1698
-                'total_paid'                   => $payment->transaction()->paid(),
1699
-                'txn_status'                   => $payment->transaction()->status_ID(),
1700
-                'pay_status'                   => $payment->STS_ID(),
1701
-                'registrations'                => $this->_registration_payment_data_array($REG_IDs),
1702
-                'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
1703
-            );
1704
-        } else {
1705
-            $this->_get_payment_status_array();
1706
-
1707
-            return array(
1708
-                'amount'           => $payment->amount(),
1709
-                'total_paid'       => $payment->transaction()->paid(),
1710
-                'txn_status'       => $payment->transaction()->status_ID(),
1711
-                'pay_status'       => $payment->STS_ID(),
1712
-                'PAY_ID'           => $payment->ID(),
1713
-                'STS_ID'           => $payment->STS_ID(),
1714
-                'status'           => self::$_pay_status[$payment->STS_ID()],
1715
-                'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
1716
-                'method'           => strtoupper($payment->source()),
1717
-                'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
1718
-                'gateway'          => $payment->payment_method() ? $payment->payment_method()->admin_name() : esc_html__("Unknown",
1719
-                    'event_espresso'),
1720
-                'gateway_response' => $payment->gateway_response(),
1721
-                'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
1722
-                'po_number'        => $payment->po_number(),
1723
-                'extra_accntng'    => $payment->extra_accntng(),
1724
-                'registrations'    => $this->_registration_payment_data_array($REG_IDs),
1725
-            );
1726
-        }
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * delete_payment
1732
-     *    delete a payment or refund made towards a transaction
1733
-     *
1734
-     * @access public
1735
-     * @return void
1736
-     */
1737
-    public function delete_payment()
1738
-    {
1739
-        $json_response_data = array('return_data' => false);
1740
-        $PAY_ID             = isset($this->_req_data['delete_txn_admin_payment'], $this->_req_data['delete_txn_admin_payment']['PAY_ID']) ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID']) : 0;
1741
-        if ($PAY_ID) {
1742
-            $delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change']) ? $this->_req_data['delete_txn_reg_status_change'] : false;
1743
-            $payment                      = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
1744
-            if ($payment instanceof EE_Payment) {
1745
-                $REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1746
-                /** @type EE_Transaction_Payments $transaction_payments */
1747
-                $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1748
-                if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
1749
-                    $json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs,
1750
-                        $delete_txn_reg_status_change);
1751
-                    if ($delete_txn_reg_status_change) {
1752
-                        $this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
1753
-                        //MAKE sure we also add the delete_txn_req_status_change to the
1754
-                        //$_REQUEST global because that's how messages will be looking for it.
1755
-                        $_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
1756
-                        $this->_maybe_send_notifications();
1757
-                        $this->_process_registration_status_change($payment->transaction(), $REG_IDs);
1758
-                    }
1759
-                }
1760
-            } else {
1761
-                EE_Error::add_error(
1762
-                    esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
1763
-                    __FILE__, __FUNCTION__, __LINE__
1764
-                );
1765
-            }
1766
-        } else {
1767
-            EE_Error::add_error(
1768
-                esc_html__('A valid Payment ID was not received, therefore payment form data could not be loaded.',
1769
-                    'event_espresso'),
1770
-                __FILE__, __FUNCTION__, __LINE__
1771
-            );
1772
-        }
1773
-        $notices              = EE_Error::get_notices(false, false, false);
1774
-        $this->_template_args = array(
1775
-            'data'      => $json_response_data,
1776
-            'success'   => $notices['success'],
1777
-            'error'     => $notices['errors'],
1778
-            'attention' => $notices['attention']
1779
-        );
1780
-        $this->_return_json();
1781
-    }
1782
-
1783
-
1784
-    /**
1785
-     * _registration_payment_data_array
1786
-     * adds info for 'owing' and 'paid' for each registration to the json response
1787
-     *
1788
-     * @access protected
1789
-     *
1790
-     * @param array $REG_IDs
1791
-     *
1792
-     * @return array
1793
-     */
1794
-    protected function _registration_payment_data_array($REG_IDs)
1795
-    {
1796
-        $registration_payment_data = array();
1797
-        //if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
1798
-        if ( ! empty($REG_IDs)) {
1799
-            $registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
1800
-            foreach ($registrations as $registration) {
1801
-                if ($registration instanceof EE_Registration) {
1802
-                    $registration_payment_data[$registration->ID()] = array(
1803
-                        'paid'  => $registration->pretty_paid(),
1804
-                        'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
1805
-                    );
1806
-                }
1807
-            }
1808
-        }
1809
-
1810
-        return $registration_payment_data;
1811
-    }
1812
-
1813
-
1814
-    /**
1815
-     * _maybe_send_notifications
1816
-     *
1817
-     * determines whether or not the admin has indicated that notifications should be sent.
1818
-     * If so, will toggle a filter switch for delivering registration notices.
1819
-     * If passed an EE_Payment object, then it will trigger payment notifications instead.
1820
-     *
1821
-     * @access protected
1822
-     *
1823
-     * @param \EE_Payment | null $payment
1824
-     */
1825
-    protected function _maybe_send_notifications($payment = null)
1826
-    {
1827
-        switch ($payment instanceof EE_Payment) {
1828
-            // payment notifications
1829
-            case true :
1830
-                if (
1831
-                    isset(
1832
-                        $this->_req_data['txn_payments'],
1833
-                        $this->_req_data['txn_payments']['send_notifications']
1834
-                    ) &&
1835
-                    filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
1836
-                ) {
1837
-                    $this->_process_payment_notification($payment);
1838
-                }
1839
-                break;
1840
-            // registration notifications
1841
-            case false :
1842
-                if (
1843
-                    isset(
1844
-                        $this->_req_data['txn_reg_status_change'],
1845
-                        $this->_req_data['txn_reg_status_change']['send_notifications']
1846
-                    ) &&
1847
-                    filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
1848
-                ) {
1849
-                    add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
1850
-                }
1851
-                break;
1852
-        }
1853
-    }
1854
-
1855
-
1856
-    /**
1857
-     * _send_payment_reminder
1858
-     *    generates HTML for the View Transaction Details Admin page
1859
-     *
1860
-     * @access protected
1861
-     * @return void
1862
-     */
1863
-    protected function _send_payment_reminder()
1864
-    {
1865
-        $TXN_ID      = ( ! empty($this->_req_data['TXN_ID'])) ? absint($this->_req_data['TXN_ID']) : false;
1866
-        $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
1867
-        $query_args  = isset($this->_req_data['redirect_to']) ? array(
1868
-            'action' => $this->_req_data['redirect_to'],
1869
-            'TXN_ID' => $this->_req_data['TXN_ID']
1870
-        ) : array();
1871
-        do_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
1872
-            $transaction);
1873
-        $this->_redirect_after_action(false, esc_html__('payment reminder', 'event_espresso'),
1874
-            esc_html__('sent', 'event_espresso'), $query_args, true);
1875
-    }
1876
-
1877
-
1878
-    /**
1879
-     *  get_transactions
1880
-     *    get transactions for given parameters (used by list table)
1881
-     *
1882
-     * @param  int     $perpage how many transactions displayed per page
1883
-     * @param  boolean $count   return the count or objects
1884
-     * @param string   $view
1885
-     *
1886
-     * @return mixed int = count || array of transaction objects
1887
-     */
1888
-    public function get_transactions($perpage, $count = false, $view = '')
1889
-    {
1890
-
1891
-        $TXN = EEM_Transaction::instance();
1892
-
1893
-        $start_date = isset($this->_req_data['txn-filter-start-date']) ? wp_strip_all_tags($this->_req_data['txn-filter-start-date']) : date('m/d/Y',
1894
-            strtotime('-10 year'));
1895
-        $end_date   = isset($this->_req_data['txn-filter-end-date']) ? wp_strip_all_tags($this->_req_data['txn-filter-end-date']) : date('m/d/Y');
1896
-
1897
-        //make sure our timestamps start and end right at the boundaries for each day
1898
-        $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1899
-        $end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1900
-
1901
-
1902
-        //convert to timestamps
1903
-        $start_date = strtotime($start_date);
1904
-        $end_date   = strtotime($end_date);
1905
-
1906
-        //makes sure start date is the lowest value and vice versa
1907
-        $start_date = min($start_date, $end_date);
1908
-        $end_date   = max($start_date, $end_date);
1909
-
1910
-        //convert to correct format for query
1911
-        $start_date = EEM_Transaction::instance()->convert_datetime_for_query('TXN_timestamp',
1912
-            date('Y-m-d H:i:s', $start_date), 'Y-m-d H:i:s');
1913
-        $end_date   = EEM_Transaction::instance()->convert_datetime_for_query('TXN_timestamp',
1914
-            date('Y-m-d H:i:s', $end_date), 'Y-m-d H:i:s');
1915
-
1916
-
1917
-        //set orderby
1918
-        $this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
1919
-
1920
-        switch ($this->_req_data['orderby']) {
1921
-            case 'TXN_ID':
1922
-                $orderby = 'TXN_ID';
1923
-                break;
1924
-            case 'ATT_fname':
1925
-                $orderby = 'Registration.Attendee.ATT_fname';
1926
-                break;
1927
-            case 'event_name':
1928
-                $orderby = 'Registration.Event.EVT_name';
1929
-                break;
1930
-            default: //'TXN_timestamp'
1931
-                $orderby = 'TXN_timestamp';
1932
-        }
1933
-
1934
-        $sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'DESC';
1935
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1936
-        $per_page     = isset($perpage) && ! empty($perpage) ? $perpage : 10;
1937
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
1938
-
1939
-        $offset = ($current_page - 1) * $per_page;
1940
-        $limit  = array($offset, $per_page);
1941
-
1942
-        $_where = array(
1943
-            'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
1944
-            'Registration.REG_count' => 1
1945
-        );
1946
-
1947
-        if (isset($this->_req_data['EVT_ID'])) {
1948
-            $_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
1949
-        }
1950
-
1951
-        if (isset($this->_req_data['s'])) {
1952
-            $search_string = '%' . $this->_req_data['s'] . '%';
1953
-            $_where['OR']  = array(
1954
-                'Registration.Event.EVT_name'         => array('LIKE', $search_string),
1955
-                'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
1956
-                'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
1957
-                'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
1958
-                'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
1959
-                'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
1960
-                'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
1961
-                'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
1962
-                'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
1963
-                'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
1964
-                'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
1965
-                'Registration.REG_final_price'        => array('LIKE', $search_string),
1966
-                'Registration.REG_code'               => array('LIKE', $search_string),
1967
-                'Registration.REG_count'              => array('LIKE', $search_string),
1968
-                'Registration.REG_group_size'         => array('LIKE', $search_string),
1969
-                'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
1970
-                'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
1971
-                'Payment.PAY_source'                  => array('LIKE', $search_string),
1972
-                'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
1973
-                'TXN_session_data'                    => array('LIKE', $search_string),
1974
-                'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string)
1975
-            );
1976
-        }
1977
-
1978
-        //failed transactions
1979
-        $failed    = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] == 'failed' && ! $count) || ($count && $view == 'failed') ? true : false;
1980
-        $abandoned = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] == 'abandoned' && ! $count) || ($count && $view == 'abandoned') ? true : false;
1981
-
1982
-        if ($failed) {
1983
-            $_where['STS_ID'] = EEM_Transaction::failed_status_code;
1984
-        } else if ($abandoned) {
1985
-            $_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
1986
-        } else {
1987
-            $_where['STS_ID']  = array('!=', EEM_Transaction::failed_status_code);
1988
-            $_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
1989
-        }
1990
-
1991
-        $query_params = array(
1992
-            $_where,
1993
-            'order_by' => array($orderby => $sort),
1994
-            'limit' => $limit,
1995
-            'default_where_conditions' => EEM_Base::default_where_conditions_this_only
1996
-        );
1997
-
1998
-        $transactions = $count ? $TXN->count(array($_where), 'TXN_ID', true) : $TXN->get_all($query_params);
1999
-
2000
-
2001
-        return $transactions;
2002
-
2003
-    }
807
+		// process payment details
808
+		$payments = $this->_transaction->get_many_related('Payment');
809
+		if ( ! empty($payments)) {
810
+			$this->_template_args['payments']              = $payments;
811
+			$this->_template_args['existing_reg_payments'] = $this->_get_registration_payment_IDs($payments);
812
+		} else {
813
+			$this->_template_args['payments']              = false;
814
+			$this->_template_args['existing_reg_payments'] = array();
815
+		}
816
+
817
+		$this->_template_args['edit_payment_url']   = add_query_arg(array('action' => 'edit_payment'), TXN_ADMIN_URL);
818
+		$this->_template_args['delete_payment_url'] = add_query_arg(array('action' => 'espresso_delete_payment'),
819
+			TXN_ADMIN_URL);
820
+
821
+		if (isset($txn_details['invoice_number'])) {
822
+			$this->_template_args['txn_details']['invoice_number']['value'] = $this->_template_args['REG_code'];
823
+			$this->_template_args['txn_details']['invoice_number']['label'] = esc_html__('Invoice Number',
824
+				'event_espresso');
825
+		}
826
+
827
+		$this->_template_args['txn_details']['registration_session']['value'] = $this->_transaction->get_first_related('Registration')->get('REG_session');
828
+		$this->_template_args['txn_details']['registration_session']['label'] = esc_html__('Registration Session',
829
+			'event_espresso');
830
+
831
+		$this->_template_args['txn_details']['ip_address']['value'] = isset($this->_session['ip_address']) ? $this->_session['ip_address'] : '';
832
+		$this->_template_args['txn_details']['ip_address']['label'] = esc_html__('Transaction placed from IP',
833
+			'event_espresso');
834
+
835
+		$this->_template_args['txn_details']['user_agent']['value'] = isset($this->_session['user_agent']) ? $this->_session['user_agent'] : '';
836
+		$this->_template_args['txn_details']['user_agent']['label'] = esc_html__('Registrant User Agent',
837
+			'event_espresso');
838
+
839
+		$reg_steps = '<ul>';
840
+		foreach ($this->_transaction->reg_steps() as $reg_step => $reg_step_status) {
841
+			if ($reg_step_status === true) {
842
+				$reg_steps .= '<li style="color:#70cc50">' . sprintf(esc_html__('%1$s : Completed', 'event_espresso'),
843
+						ucwords(str_replace('_', ' ', $reg_step))) . '</li>';
844
+			} else if (is_numeric($reg_step_status) && $reg_step_status !== false) {
845
+				$reg_steps .= '<li style="color:#2EA2CC">' . sprintf(
846
+						esc_html__('%1$s : Initiated %2$s', 'event_espresso'),
847
+						ucwords(str_replace('_', ' ', $reg_step)),
848
+						date(get_option('date_format') . ' ' . get_option('time_format'),
849
+							($reg_step_status + (get_option('gmt_offset') * HOUR_IN_SECONDS)))
850
+					) . '</li>';
851
+			} else {
852
+				$reg_steps .= '<li style="color:#E76700">' . sprintf(esc_html__('%1$s : Never Initiated',
853
+						'event_espresso'), ucwords(str_replace('_', ' ', $reg_step))) . '</li>';
854
+			}
855
+		}
856
+		$reg_steps .= '</ul>';
857
+		$this->_template_args['txn_details']['reg_steps']['value'] = $reg_steps;
858
+		$this->_template_args['txn_details']['reg_steps']['label'] = esc_html__('Registration Step Progress',
859
+			'event_espresso');
860
+
861
+
862
+		$this->_get_registrations_to_apply_payment_to();
863
+		$this->_get_payment_methods($payments);
864
+		$this->_get_payment_status_array();
865
+		$this->_get_reg_status_selection(); //sets up the template args for the reg status array for the transaction.
866
+
867
+		$this->_template_args['transaction_form_url']    = add_query_arg(array(
868
+			'action'  => 'edit_transaction',
869
+			'process' => 'transaction'
870
+		), TXN_ADMIN_URL);
871
+		$this->_template_args['apply_payment_form_url']  = add_query_arg(array(
872
+			'page'   => 'espresso_transactions',
873
+			'action' => 'espresso_apply_payment'
874
+		), WP_AJAX_URL);
875
+		$this->_template_args['delete_payment_form_url'] = add_query_arg(array(
876
+			'page'   => 'espresso_transactions',
877
+			'action' => 'espresso_delete_payment'
878
+		), WP_AJAX_URL);
879
+
880
+		// 'espresso_delete_payment_nonce'
881
+
882
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_txn_details.template.php';
883
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);
884
+
885
+	}
886
+
887
+
888
+	/**
889
+	 * _get_registration_payment_IDs
890
+	 *
891
+	 *    generates an array of Payment IDs and their corresponding Registration IDs
892
+	 *
893
+	 * @access protected
894
+	 *
895
+	 * @param EE_Payment[] $payments
896
+	 *
897
+	 * @return array
898
+	 */
899
+	protected function _get_registration_payment_IDs($payments = array())
900
+	{
901
+		$existing_reg_payments = array();
902
+		// get all reg payments for these payments
903
+		$reg_payments = EEM_Registration_Payment::instance()->get_all(array(
904
+			array(
905
+				'PAY_ID' => array(
906
+					'IN',
907
+					array_keys($payments)
908
+				)
909
+			)
910
+		));
911
+		if ( ! empty($reg_payments)) {
912
+			foreach ($payments as $payment) {
913
+				if ( ! $payment instanceof EE_Payment) {
914
+					continue;
915
+				} else if ( ! isset($existing_reg_payments[$payment->ID()])) {
916
+					$existing_reg_payments[$payment->ID()] = array();
917
+				}
918
+				foreach ($reg_payments as $reg_payment) {
919
+					if ($reg_payment instanceof EE_Registration_Payment && $reg_payment->payment_ID() === $payment->ID()) {
920
+						$existing_reg_payments[$payment->ID()][] = $reg_payment->registration_ID();
921
+					}
922
+				}
923
+			}
924
+		}
925
+
926
+		return $existing_reg_payments;
927
+	}
928
+
929
+
930
+	/**
931
+	 * _get_registrations_to_apply_payment_to
932
+	 *    generates HTML for displaying a series of checkboxes in the admin payment modal window
933
+	 * which allows the admin to only apply the payment to the specific registrations
934
+	 *
935
+	 * @access protected
936
+	 * @return void
937
+	 * @throws \EE_Error
938
+	 */
939
+	protected function _get_registrations_to_apply_payment_to()
940
+	{
941
+		// we want any registration with an active status (ie: not deleted or cancelled)
942
+		$query_params                      = array(
943
+			array(
944
+				'STS_ID' => array(
945
+					'IN',
946
+					array(
947
+						EEM_Registration::status_id_approved,
948
+						EEM_Registration::status_id_pending_payment,
949
+						EEM_Registration::status_id_not_approved,
950
+					)
951
+				)
952
+			)
953
+		);
954
+		$registrations_to_apply_payment_to = EEH_HTML::br() . EEH_HTML::div(
955
+				'', 'txn-admin-apply-payment-to-registrations-dv', '', 'clear: both; margin: 1.5em 0 0; display: none;'
956
+			);
957
+		$registrations_to_apply_payment_to .= EEH_HTML::br() . EEH_HTML::div('', '', 'admin-primary-mbox-tbl-wrap');
958
+		$registrations_to_apply_payment_to .= EEH_HTML::table('', '', 'admin-primary-mbox-tbl');
959
+		$registrations_to_apply_payment_to .= EEH_HTML::thead(
960
+			EEH_HTML::tr(
961
+				EEH_HTML::th(esc_html__('ID', 'event_espresso')) .
962
+				EEH_HTML::th(esc_html__('Registrant', 'event_espresso')) .
963
+				EEH_HTML::th(esc_html__('Ticket', 'event_espresso')) .
964
+				EEH_HTML::th(esc_html__('Event', 'event_espresso')) .
965
+				EEH_HTML::th(esc_html__('Paid', 'event_espresso'), '', 'txn-admin-payment-paid-td jst-cntr') .
966
+				EEH_HTML::th(esc_html__('Owing', 'event_espresso'), '', 'txn-admin-payment-owing-td jst-cntr') .
967
+				EEH_HTML::th(esc_html__('Apply', 'event_espresso'), '', 'jst-cntr')
968
+			)
969
+		);
970
+		$registrations_to_apply_payment_to .= EEH_HTML::tbody();
971
+		// get registrations for TXN
972
+		$registrations = $this->_transaction->registrations($query_params);
973
+		foreach ($registrations as $registration) {
974
+			if ($registration instanceof EE_Registration) {
975
+				$attendee_name = $registration->attendee() instanceof EE_Attendee
976
+					? $registration->attendee()->full_name()
977
+					: esc_html__('Unknown Attendee', 'event_espresso');
978
+				$owing         = $registration->final_price() - $registration->paid();
979
+				$taxable       = $registration->ticket()->taxable()
980
+					? ' <span class="smaller-text lt-grey-text"> ' . esc_html__('+ tax', 'event_espresso') . '</span>'
981
+					: '';
982
+				$checked       = empty($existing_reg_payments) || in_array($registration->ID(), $existing_reg_payments)
983
+					? ' checked="checked"'
984
+					: '';
985
+				$disabled      = $registration->final_price() > 0 ? '' : ' disabled';
986
+				$registrations_to_apply_payment_to .= EEH_HTML::tr(
987
+					EEH_HTML::td($registration->ID()) .
988
+					EEH_HTML::td($attendee_name) .
989
+					EEH_HTML::td(
990
+						$registration->ticket()->name() . ' : ' . $registration->ticket()->pretty_price() . $taxable
991
+					) .
992
+					EEH_HTML::td($registration->event_name()) .
993
+					EEH_HTML::td($registration->pretty_paid(), '', 'txn-admin-payment-paid-td jst-cntr') .
994
+					EEH_HTML::td(EEH_Template::format_currency($owing), '', 'txn-admin-payment-owing-td jst-cntr') .
995
+					EEH_HTML::td(
996
+						'<input type="checkbox" value="' . $registration->ID()
997
+						. '" name="txn_admin_payment[registrations]"'
998
+						. $checked . $disabled . '>',
999
+						'', 'jst-cntr'
1000
+					),
1001
+					'apply-payment-registration-row-' . $registration->ID()
1002
+				);
1003
+			}
1004
+		}
1005
+		$registrations_to_apply_payment_to .= EEH_HTML::tbodyx();
1006
+		$registrations_to_apply_payment_to .= EEH_HTML::tablex();
1007
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1008
+		$registrations_to_apply_payment_to .= EEH_HTML::p(
1009
+			esc_html__(
1010
+				'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.',
1011
+				'event_espresso'
1012
+			),
1013
+			'', 'clear description'
1014
+		);
1015
+		$registrations_to_apply_payment_to .= EEH_HTML::divx();
1016
+		$this->_template_args['registrations_to_apply_payment_to'] = $registrations_to_apply_payment_to;
1017
+	}
1018
+
1019
+
1020
+	/**
1021
+	 * _get_reg_status_selection
1022
+	 *
1023
+	 * @todo   this will need to be adjusted either once MER comes along OR we move default reg status to tickets
1024
+	 *         instead of events.
1025
+	 * @access protected
1026
+	 * @return void
1027
+	 */
1028
+	protected function _get_reg_status_selection()
1029
+	{
1030
+		//first get all possible statuses
1031
+		$statuses = EEM_Registration::reg_status_array(array(), true);
1032
+		//let's add a "don't change" option.
1033
+		$status_array['NAN']                                 = esc_html__('Leave the Same', 'event_espresso');
1034
+		$status_array                                        = array_merge($status_array, $statuses);
1035
+		$this->_template_args['status_change_select']        = EEH_Form_Fields::select_input('txn_reg_status_change[reg_status]',
1036
+			$status_array, 'NAN', 'id="txn-admin-payment-reg-status-inp"', 'txn-reg-status-change-reg-status');
1037
+		$this->_template_args['delete_status_change_select'] = EEH_Form_Fields::select_input('delete_txn_reg_status_change[reg_status]',
1038
+			$status_array, 'NAN', 'delete-txn-admin-payment-reg-status-inp', 'delete-txn-reg-status-change-reg-status');
1039
+
1040
+	}
1041
+
1042
+
1043
+	/**
1044
+	 *    _get_payment_methods
1045
+	 * Gets all the payment methods available generally, or the ones that are already
1046
+	 * selected on these payments (in case their payment methods are no longer active).
1047
+	 * Has the side-effect of updating the template args' payment_methods item
1048
+	 * @access private
1049
+	 *
1050
+	 * @param EE_Payment[] to show on this page
1051
+	 *
1052
+	 * @return void
1053
+	 */
1054
+	private function _get_payment_methods($payments = array())
1055
+	{
1056
+		$payment_methods_of_payments = array();
1057
+		foreach ($payments as $payment) {
1058
+			if ($payment instanceof EE_Payment) {
1059
+				$payment_methods_of_payments[] = $payment->get('PMD_ID');
1060
+			}
1061
+		}
1062
+		if ($payment_methods_of_payments) {
1063
+			$query_args = array(
1064
+				array(
1065
+					'OR*payment_method_for_payment' => array(
1066
+						'PMD_ID'    => array('IN', $payment_methods_of_payments),
1067
+						'PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')
1068
+					)
1069
+				)
1070
+			);
1071
+		} else {
1072
+			$query_args = array(array('PMD_scope' => array('LIKE', '%' . EEM_Payment_Method::scope_admin . '%')));
1073
+		}
1074
+		$this->_template_args['payment_methods'] = EEM_Payment_Method::instance()->get_all($query_args);
1075
+	}
1076
+
1077
+
1078
+	/**
1079
+	 * txn_attendees_meta_box
1080
+	 *    generates HTML for the Attendees Transaction main meta box
1081
+	 *
1082
+	 * @access public
1083
+	 *
1084
+	 * @param WP_Post $post
1085
+	 * @param array   $metabox
1086
+	 *
1087
+	 * @return void
1088
+	 */
1089
+	public function txn_attendees_meta_box($post, $metabox = array('args' => array()))
1090
+	{
1091
+
1092
+		extract($metabox['args']);
1093
+		$this->_template_args['post']            = $post;
1094
+		$this->_template_args['event_attendees'] = array();
1095
+		// process items in cart
1096
+		$line_items = $this->_transaction->get_many_related('Line_Item', array(array('LIN_type' => 'line-item')));
1097
+		if ( ! empty($line_items)) {
1098
+			foreach ($line_items as $item) {
1099
+				if ($item instanceof EE_Line_Item) {
1100
+					switch ($item->OBJ_type()) {
1101
+
1102
+						case 'Event' :
1103
+							break;
1104
+
1105
+						case 'Ticket' :
1106
+							$ticket = $item->ticket();
1107
+							//right now we're only handling tickets here.  Cause its expected that only tickets will have attendees right?
1108
+							if ( ! $ticket instanceof EE_Ticket) {
1109
+								continue;
1110
+							}
1111
+							try {
1112
+								$event_name = $ticket->get_event_name();
1113
+							} catch (Exception $e) {
1114
+								EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1115
+								$event_name = esc_html__('Unknown Event', 'event_espresso');
1116
+							}
1117
+							$event_name .= ' - ' . $item->get('LIN_name');
1118
+							$ticket_price = EEH_Template::format_currency($item->get('LIN_unit_price'));
1119
+							// now get all of the registrations for this transaction that use this ticket
1120
+							$registrations = $ticket->get_many_related('Registration',
1121
+								array(array('TXN_ID' => $this->_transaction->ID())));
1122
+							foreach ($registrations as $registration) {
1123
+								if ( ! $registration instanceof EE_Registration) {
1124
+									continue;
1125
+								}
1126
+								$this->_template_args['event_attendees'][$registration->ID()]['STS_ID']            = $registration->status_ID();
1127
+								$this->_template_args['event_attendees'][$registration->ID()]['att_num']           = $registration->count();
1128
+								$this->_template_args['event_attendees'][$registration->ID()]['event_ticket_name'] = $event_name;
1129
+								$this->_template_args['event_attendees'][$registration->ID()]['ticket_price']      = $ticket_price;
1130
+								// attendee info
1131
+								$attendee = $registration->get_first_related('Attendee');
1132
+								if ($attendee instanceof EE_Attendee) {
1133
+									$this->_template_args['event_attendees'][$registration->ID()]['att_id']   = $attendee->ID();
1134
+									$this->_template_args['event_attendees'][$registration->ID()]['attendee'] = $attendee->full_name();
1135
+									$this->_template_args['event_attendees'][$registration->ID()]['email']    = '<a href="mailto:' . $attendee->email() . '?subject=' . $event_name . esc_html__(' Event',
1136
+											'event_espresso') . '">' . $attendee->email() . '</a>';
1137
+									$this->_template_args['event_attendees'][$registration->ID()]['address']  = EEH_Address::format($attendee,
1138
+										'inline', false, false);
1139
+								} else {
1140
+									$this->_template_args['event_attendees'][$registration->ID()]['att_id']   = '';
1141
+									$this->_template_args['event_attendees'][$registration->ID()]['attendee'] = '';
1142
+									$this->_template_args['event_attendees'][$registration->ID()]['email']    = '';
1143
+									$this->_template_args['event_attendees'][$registration->ID()]['address']  = '';
1144
+								}
1145
+							}
1146
+							break;
1147
+
1148
+					}
1149
+				}
1150
+			}
1151
+
1152
+			$this->_template_args['transaction_form_url'] = add_query_arg(array(
1153
+				'action'  => 'edit_transaction',
1154
+				'process' => 'attendees'
1155
+			), TXN_ADMIN_URL);
1156
+			echo EEH_Template::display_template(TXN_TEMPLATE_PATH . 'txn_admin_details_main_meta_box_attendees.template.php',
1157
+				$this->_template_args, true);
1158
+
1159
+		} else {
1160
+			echo sprintf(
1161
+				esc_html__('%1$sFor some reason, there are no attendees registered for this transaction. Likely the registration was abandoned in process.%2$s',
1162
+					'event_espresso'),
1163
+				'<p class="important-notice">',
1164
+				'</p>'
1165
+			);
1166
+		}
1167
+	}
1168
+
1169
+
1170
+	/**
1171
+	 * txn_registrant_side_meta_box
1172
+	 * generates HTML for the Edit Transaction side meta box
1173
+	 *
1174
+	 * @access public
1175
+	 * @throws \EE_Error
1176
+	 * @return void
1177
+	 */
1178
+	public function txn_registrant_side_meta_box()
1179
+	{
1180
+		$primary_att = $this->_transaction->primary_registration() instanceof EE_Registration ? $this->_transaction->primary_registration()->get_first_related('Attendee') : null;
1181
+		if ( ! $primary_att instanceof EE_Attendee) {
1182
+			$this->_template_args['no_attendee_message'] = esc_html__('There is no attached contact for this transaction.  The transaction either failed due to an error or was abandoned.',
1183
+				'event_espresso');
1184
+			$primary_att                                 = EEM_Attendee::instance()->create_default_object();
1185
+		}
1186
+		$this->_template_args['ATT_ID']            = $primary_att->ID();
1187
+		$this->_template_args['prime_reg_fname']   = $primary_att->fname();
1188
+		$this->_template_args['prime_reg_lname']   = $primary_att->lname();
1189
+		$this->_template_args['prime_reg_email']   = $primary_att->email();
1190
+		$this->_template_args['prime_reg_phone']   = $primary_att->phone();
1191
+		$this->_template_args['edit_attendee_url'] = EE_Admin_Page::add_query_args_and_nonce(array(
1192
+			'action' => 'edit_attendee',
1193
+			'post'   => $primary_att->ID()
1194
+		), REG_ADMIN_URL);
1195
+		// get formatted address for registrant
1196
+		$this->_template_args['formatted_address'] = EEH_Address::format($primary_att);
1197
+		echo EEH_Template::display_template(TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_registrant.template.php',
1198
+			$this->_template_args, true);
1199
+	}
1200
+
1201
+
1202
+	/**
1203
+	 * txn_billing_info_side_meta_box
1204
+	 *    generates HTML for the Edit Transaction side meta box
1205
+	 *
1206
+	 * @access public
1207
+	 * @return void
1208
+	 */
1209
+	public function txn_billing_info_side_meta_box()
1210
+	{
1211
+
1212
+		$this->_template_args['billing_form']     = $this->_transaction->billing_info();
1213
+		$this->_template_args['billing_form_url'] = add_query_arg(
1214
+			array('action' => 'edit_transaction', 'process' => 'billing'),
1215
+			TXN_ADMIN_URL
1216
+		);
1217
+
1218
+		$template_path = TXN_TEMPLATE_PATH . 'txn_admin_details_side_meta_box_billing_info.template.php';
1219
+		echo EEH_Template::display_template($template_path, $this->_template_args, true);/**/
1220
+	}
1221
+
1222
+
1223
+	/**
1224
+	 * apply_payments_or_refunds
1225
+	 *    registers a payment or refund made towards a transaction
1226
+	 *
1227
+	 * @access public
1228
+	 * @return void
1229
+	 */
1230
+	public function apply_payments_or_refunds()
1231
+	{
1232
+		$json_response_data = array('return_data' => false);
1233
+		$valid_data         = $this->_validate_payment_request_data();
1234
+		if ( ! empty($valid_data)) {
1235
+			$PAY_ID = $valid_data['PAY_ID'];
1236
+			//save  the new payment
1237
+			$payment = $this->_create_payment_from_request_data($valid_data);
1238
+			// get the TXN for this payment
1239
+			$transaction = $payment->transaction();
1240
+			// verify transaction
1241
+			if ($transaction instanceof EE_Transaction) {
1242
+				// calculate_total_payments_and_update_status
1243
+				$this->_process_transaction_payments($transaction);
1244
+				$REG_IDs = $this->_get_REG_IDs_to_apply_payment_to($payment);
1245
+				$this->_remove_existing_registration_payments($payment, $PAY_ID);
1246
+				// apply payment to registrations (if applicable)
1247
+				if ( ! empty($REG_IDs)) {
1248
+					$this->_update_registration_payments($transaction, $payment, $REG_IDs);
1249
+					$this->_maybe_send_notifications();
1250
+					// now process status changes for the same registrations
1251
+					$this->_process_registration_status_change($transaction, $REG_IDs);
1252
+				}
1253
+				$this->_maybe_send_notifications($payment);
1254
+				//prepare to render page
1255
+				$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs);
1256
+				do_action('AHEE__Transactions_Admin_Page__apply_payments_or_refund__after_recording', $transaction,
1257
+					$payment);
1258
+			} else {
1259
+				EE_Error::add_error(
1260
+					esc_html__('A valid Transaction for this payment could not be retrieved.', 'event_espresso'),
1261
+					__FILE__, __FUNCTION__, __LINE__
1262
+				);
1263
+			}
1264
+		} else {
1265
+			EE_Error::add_error(esc_html__('The payment form data could not be processed. Please try again.',
1266
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1267
+		}
1268
+
1269
+		$notices              = EE_Error::get_notices(false, false, false);
1270
+		$this->_template_args = array(
1271
+			'data'    => $json_response_data,
1272
+			'error'   => $notices['errors'],
1273
+			'success' => $notices['success']
1274
+		);
1275
+		$this->_return_json();
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * _validate_payment_request_data
1281
+	 *
1282
+	 * @return array
1283
+	 */
1284
+	protected function _validate_payment_request_data()
1285
+	{
1286
+		if ( ! isset($this->_req_data['txn_admin_payment'])) {
1287
+			return false;
1288
+		}
1289
+		$payment_form = $this->_generate_payment_form_section();
1290
+		try {
1291
+			if ($payment_form->was_submitted()) {
1292
+				$payment_form->receive_form_submission();
1293
+				if ( ! $payment_form->is_valid()) {
1294
+					$submission_error_messages = array();
1295
+					foreach ($payment_form->get_validation_errors_accumulated() as $validation_error) {
1296
+						if ($validation_error instanceof EE_Validation_Error) {
1297
+							$submission_error_messages[] = sprintf(
1298
+								_x('%s : %s', 'Form Section Name : Form Validation Error', 'event_espresso'),
1299
+								$validation_error->get_form_section()->html_label_text(),
1300
+								$validation_error->getMessage()
1301
+							);
1302
+						}
1303
+					}
1304
+					EE_Error::add_error(join('<br />', $submission_error_messages), __FILE__, __FUNCTION__, __LINE__);
1305
+
1306
+					return array();
1307
+				}
1308
+			}
1309
+		} catch (EE_Error $e) {
1310
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1311
+
1312
+			return array();
1313
+		}
1314
+
1315
+		return $payment_form->valid_data();
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * _generate_payment_form_section
1321
+	 *
1322
+	 * @return EE_Form_Section_Proper
1323
+	 */
1324
+	protected function _generate_payment_form_section()
1325
+	{
1326
+		return new EE_Form_Section_Proper(
1327
+			array(
1328
+				'name'        => 'txn_admin_payment',
1329
+				'subsections' => array(
1330
+					'PAY_ID'          => new EE_Text_Input(
1331
+						array(
1332
+							'default'               => 0,
1333
+							'required'              => false,
1334
+							'html_label_text'       => esc_html__('Payment ID', 'event_espresso'),
1335
+							'validation_strategies' => array(new EE_Int_Normalization())
1336
+						)
1337
+					),
1338
+					'TXN_ID'          => new EE_Text_Input(
1339
+						array(
1340
+							'default'               => 0,
1341
+							'required'              => true,
1342
+							'html_label_text'       => esc_html__('Transaction ID', 'event_espresso'),
1343
+							'validation_strategies' => array(new EE_Int_Normalization())
1344
+						)
1345
+					),
1346
+					'type'            => new EE_Text_Input(
1347
+						array(
1348
+							'default'               => 1,
1349
+							'required'              => true,
1350
+							'html_label_text'       => esc_html__('Payment or Refund', 'event_espresso'),
1351
+							'validation_strategies' => array(new EE_Int_Normalization())
1352
+						)
1353
+					),
1354
+					'amount'          => new EE_Text_Input(
1355
+						array(
1356
+							'default'               => 0,
1357
+							'required'              => true,
1358
+							'html_label_text'       => esc_html__('Payment amount', 'event_espresso'),
1359
+							'validation_strategies' => array(new EE_Float_Normalization())
1360
+						)
1361
+					),
1362
+					'status'          => new EE_Text_Input(
1363
+						array(
1364
+							'default'         => EEM_Payment::status_id_approved,
1365
+							'required'        => true,
1366
+							'html_label_text' => esc_html__('Payment status', 'event_espresso'),
1367
+						)
1368
+					),
1369
+					'PMD_ID'          => new EE_Text_Input(
1370
+						array(
1371
+							'default'               => 2,
1372
+							'required'              => true,
1373
+							'html_label_text'       => esc_html__('Payment Method', 'event_espresso'),
1374
+							'validation_strategies' => array(new EE_Int_Normalization())
1375
+						)
1376
+					),
1377
+					'date'            => new EE_Text_Input(
1378
+						array(
1379
+							'default'         => time(),
1380
+							'required'        => true,
1381
+							'html_label_text' => esc_html__('Payment date', 'event_espresso'),
1382
+						)
1383
+					),
1384
+					'txn_id_chq_nmbr' => new EE_Text_Input(
1385
+						array(
1386
+							'default'               => '',
1387
+							'required'              => false,
1388
+							'html_label_text'       => esc_html__('Transaction or Cheque Number', 'event_espresso'),
1389
+							'validation_strategies' => array(
1390
+								new EE_Max_Length_Validation_Strategy(esc_html__('Input too long', 'event_espresso'),
1391
+									100),
1392
+							)
1393
+						)
1394
+					),
1395
+					'po_number'       => new EE_Text_Input(
1396
+						array(
1397
+							'default'               => '',
1398
+							'required'              => false,
1399
+							'html_label_text'       => esc_html__('Purchase Order Number', 'event_espresso'),
1400
+							'validation_strategies' => array(
1401
+								new EE_Max_Length_Validation_Strategy(esc_html__('Input too long', 'event_espresso'),
1402
+									100),
1403
+							)
1404
+						)
1405
+					),
1406
+					'accounting'      => new EE_Text_Input(
1407
+						array(
1408
+							'default'               => '',
1409
+							'required'              => false,
1410
+							'html_label_text'       => esc_html__('Extra Field for Accounting', 'event_espresso'),
1411
+							'validation_strategies' => array(
1412
+								new EE_Max_Length_Validation_Strategy(esc_html__('Input too long', 'event_espresso'),
1413
+									100),
1414
+							)
1415
+						)
1416
+					),
1417
+				)
1418
+			)
1419
+		);
1420
+	}
1421
+
1422
+
1423
+	/**
1424
+	 * _create_payment_from_request_data
1425
+	 *
1426
+	 * @param array $valid_data
1427
+	 *
1428
+	 * @return EE_Payment
1429
+	 */
1430
+	protected function _create_payment_from_request_data($valid_data)
1431
+	{
1432
+		$PAY_ID = $valid_data['PAY_ID'];
1433
+		// get payment amount
1434
+		$amount = $valid_data['amount'] ? abs($valid_data['amount']) : 0;
1435
+		// payments have a type value of 1 and refunds have a type value of -1
1436
+		// so multiplying amount by type will give a positive value for payments, and negative values for refunds
1437
+		$amount = $valid_data['type'] < 0 ? $amount * -1 : $amount;
1438
+		// for some reason the date string coming in has extra spaces between the date and time.  This fixes that.
1439
+		$date    = $valid_data['date'] ? preg_replace('/\s+/', ' ', $valid_data['date']) : date('Y-m-d g:i a',
1440
+			current_time('timestamp'));
1441
+		$payment = EE_Payment::new_instance(
1442
+			array(
1443
+				'TXN_ID'              => $valid_data['TXN_ID'],
1444
+				'STS_ID'              => $valid_data['status'],
1445
+				'PAY_timestamp'       => $date,
1446
+				'PAY_source'          => EEM_Payment_Method::scope_admin,
1447
+				'PMD_ID'              => $valid_data['PMD_ID'],
1448
+				'PAY_amount'          => $amount,
1449
+				'PAY_txn_id_chq_nmbr' => $valid_data['txn_id_chq_nmbr'],
1450
+				'PAY_po_number'       => $valid_data['po_number'],
1451
+				'PAY_extra_accntng'   => $valid_data['accounting'],
1452
+				'PAY_details'         => $valid_data,
1453
+				'PAY_ID'              => $PAY_ID
1454
+			),
1455
+			'',
1456
+			array('Y-m-d', 'g:i a')
1457
+		);
1458
+
1459
+		if ( ! $payment->save()) {
1460
+			EE_Error::add_error(
1461
+				sprintf(
1462
+					esc_html__('Payment %1$d has not been successfully saved to the database.', 'event_espresso'),
1463
+					$payment->ID()
1464
+				),
1465
+				__FILE__, __FUNCTION__, __LINE__
1466
+			);
1467
+		}
1468
+
1469
+		return $payment;
1470
+	}
1471
+
1472
+
1473
+	/**
1474
+	 * _process_transaction_payments
1475
+	 *
1476
+	 * @param \EE_Transaction $transaction
1477
+	 *
1478
+	 * @return array
1479
+	 */
1480
+	protected function _process_transaction_payments(EE_Transaction $transaction)
1481
+	{
1482
+		/** @type EE_Transaction_Payments $transaction_payments */
1483
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1484
+		//update the transaction with this payment
1485
+		if ($transaction_payments->calculate_total_payments_and_update_status($transaction)) {
1486
+			EE_Error::add_success(esc_html__('The payment has been processed successfully.', 'event_espresso'),
1487
+				__FILE__, __FUNCTION__, __LINE__);
1488
+		} else {
1489
+			EE_Error::add_error(
1490
+				esc_html__('The payment was processed successfully but the amount paid for the transaction was not updated.',
1491
+					'event_espresso')
1492
+				, __FILE__, __FUNCTION__, __LINE__
1493
+			);
1494
+		}
1495
+	}
1496
+
1497
+
1498
+	/**
1499
+	 * _get_REG_IDs_to_apply_payment_to
1500
+	 *
1501
+	 * returns a list of registration IDs that the payment will apply to
1502
+	 *
1503
+	 * @param \EE_Payment $payment
1504
+	 *
1505
+	 * @return array
1506
+	 */
1507
+	protected function _get_REG_IDs_to_apply_payment_to(EE_Payment $payment)
1508
+	{
1509
+		$REG_IDs = array();
1510
+		// grab array of IDs for specific registrations to apply changes to
1511
+		if (isset($this->_req_data['txn_admin_payment']['registrations'])) {
1512
+			$REG_IDs = (array)$this->_req_data['txn_admin_payment']['registrations'];
1513
+		}
1514
+		//nothing specified ? then get all reg IDs
1515
+		if (empty($REG_IDs)) {
1516
+			$registrations = $payment->transaction()->registrations();
1517
+			$REG_IDs       = ! empty($registrations) ? array_keys($registrations) : $this->_get_existing_reg_payment_REG_IDs($payment);
1518
+		}
1519
+
1520
+		// ensure that REG_IDs are integers and NOT strings
1521
+		return array_map('intval', $REG_IDs);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * @return array
1527
+	 */
1528
+	public function existing_reg_payment_REG_IDs()
1529
+	{
1530
+		return $this->_existing_reg_payment_REG_IDs;
1531
+	}
1532
+
1533
+
1534
+	/**
1535
+	 * @param array $existing_reg_payment_REG_IDs
1536
+	 */
1537
+	public function set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs = null)
1538
+	{
1539
+		$this->_existing_reg_payment_REG_IDs = $existing_reg_payment_REG_IDs;
1540
+	}
1541
+
1542
+
1543
+	/**
1544
+	 * _get_existing_reg_payment_REG_IDs
1545
+	 *
1546
+	 * returns a list of registration IDs that the payment is currently related to
1547
+	 * as recorded in the database
1548
+	 *
1549
+	 * @param \EE_Payment $payment
1550
+	 *
1551
+	 * @return array
1552
+	 */
1553
+	protected function _get_existing_reg_payment_REG_IDs(EE_Payment $payment)
1554
+	{
1555
+		if ($this->existing_reg_payment_REG_IDs() === null) {
1556
+			// let's get any existing reg payment records for this payment
1557
+			$existing_reg_payment_REG_IDs = $payment->get_many_related('Registration');
1558
+			// but we only want the REG IDs, so grab the array keys
1559
+			$existing_reg_payment_REG_IDs = ! empty($existing_reg_payment_REG_IDs) ? array_keys($existing_reg_payment_REG_IDs) : array();
1560
+			$this->set_existing_reg_payment_REG_IDs($existing_reg_payment_REG_IDs);
1561
+		}
1562
+
1563
+		return $this->existing_reg_payment_REG_IDs();
1564
+	}
1565
+
1566
+
1567
+	/**
1568
+	 * _remove_existing_registration_payments
1569
+	 *
1570
+	 * this calculates the difference between existing relations
1571
+	 * to the supplied payment and the new list registration IDs,
1572
+	 * removes any related registrations that no longer apply,
1573
+	 * and then updates the registration paid fields
1574
+	 *
1575
+	 * @param \EE_Payment $payment
1576
+	 * @param int         $PAY_ID
1577
+	 *
1578
+	 * @return bool;
1579
+	 */
1580
+	protected function _remove_existing_registration_payments(EE_Payment $payment, $PAY_ID = 0)
1581
+	{
1582
+		// newly created payments will have nothing recorded for $PAY_ID
1583
+		if ($PAY_ID == 0) {
1584
+			return false;
1585
+		}
1586
+		$existing_reg_payment_REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1587
+		if (empty($existing_reg_payment_REG_IDs)) {
1588
+			return false;
1589
+		}
1590
+		/** @type EE_Transaction_Payments $transaction_payments */
1591
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1592
+
1593
+		return $transaction_payments->delete_registration_payments_and_update_registrations(
1594
+			$payment,
1595
+			array(
1596
+				array(
1597
+					'PAY_ID' => $payment->ID(),
1598
+					'REG_ID' => array('IN', $existing_reg_payment_REG_IDs),
1599
+				)
1600
+			)
1601
+		);
1602
+	}
1603
+
1604
+
1605
+	/**
1606
+	 * _update_registration_payments
1607
+	 *
1608
+	 * this applies the payments to the selected registrations
1609
+	 * but only if they have not already been paid for
1610
+	 *
1611
+	 * @param  EE_Transaction $transaction
1612
+	 * @param \EE_Payment     $payment
1613
+	 * @param array           $REG_IDs
1614
+	 *
1615
+	 * @return bool
1616
+	 */
1617
+	protected function _update_registration_payments(
1618
+		EE_Transaction $transaction,
1619
+		EE_Payment $payment,
1620
+		$REG_IDs = array()
1621
+	) {
1622
+		// we can pass our own custom set of registrations to EE_Payment_Processor::process_registration_payments()
1623
+		// so let's do that using our set of REG_IDs from the form
1624
+		$registration_query_where_params = array(
1625
+			'REG_ID' => array('IN', $REG_IDs)
1626
+		);
1627
+		// but add in some conditions regarding payment,
1628
+		// so that we don't apply payments to registrations that are free or have already been paid for
1629
+		// but ONLY if the payment is NOT a refund ( ie: the payment amount is not negative )
1630
+		if ( ! $payment->is_a_refund()) {
1631
+			$registration_query_where_params['REG_final_price']  = array('!=', 0);
1632
+			$registration_query_where_params['REG_final_price*'] = array('!=', 'REG_paid', true);
1633
+		}
1634
+		//EEH_Debug_Tools::printr( $registration_query_where_params, '$registration_query_where_params', __FILE__, __LINE__ );
1635
+		$registrations = $transaction->registrations(array($registration_query_where_params));
1636
+		if ( ! empty($registrations)) {
1637
+			/** @type EE_Payment_Processor $payment_processor */
1638
+			$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
1639
+			$payment_processor->process_registration_payments($transaction, $payment, $registrations);
1640
+		}
1641
+	}
1642
+
1643
+
1644
+	/**
1645
+	 * _process_registration_status_change
1646
+	 *
1647
+	 * This processes requested registration status changes for all the registrations
1648
+	 * on a given transaction and (optionally) sends out notifications for the changes.
1649
+	 *
1650
+	 * @param  EE_Transaction $transaction
1651
+	 * @param array           $REG_IDs
1652
+	 *
1653
+	 * @return bool
1654
+	 */
1655
+	protected function _process_registration_status_change(EE_Transaction $transaction, $REG_IDs = array())
1656
+	{
1657
+		// first if there is no change in status then we get out.
1658
+		if (
1659
+			! isset($this->_req_data['txn_reg_status_change'], $this->_req_data['txn_reg_status_change']['reg_status'])
1660
+			|| $this->_req_data['txn_reg_status_change']['reg_status'] == 'NAN'
1661
+		) {
1662
+			//no error message, no change requested, just nothing to do man.
1663
+			return false;
1664
+		}
1665
+		/** @type EE_Transaction_Processor $transaction_processor */
1666
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
1667
+
1668
+		// made it here dude?  Oh WOW.  K, let's take care of changing the statuses
1669
+		return $transaction_processor->manually_update_registration_statuses(
1670
+			$transaction,
1671
+			sanitize_text_field($this->_req_data['txn_reg_status_change']['reg_status']),
1672
+			array(array('REG_ID' => array('IN', $REG_IDs)))
1673
+		);
1674
+	}
1675
+
1676
+
1677
+	/**
1678
+	 * _build_payment_json_response
1679
+	 *
1680
+	 * @access public
1681
+	 *
1682
+	 * @param \EE_Payment $payment
1683
+	 * @param array       $REG_IDs
1684
+	 * @param bool | null $delete_txn_reg_status_change
1685
+	 *
1686
+	 * @return array
1687
+	 */
1688
+	protected function _build_payment_json_response(
1689
+		EE_Payment $payment,
1690
+		$REG_IDs = array(),
1691
+		$delete_txn_reg_status_change = null
1692
+	) {
1693
+		// was the payment deleted ?
1694
+		if (is_bool($delete_txn_reg_status_change)) {
1695
+			return array(
1696
+				'PAY_ID'                       => $payment->ID(),
1697
+				'amount'                       => $payment->amount(),
1698
+				'total_paid'                   => $payment->transaction()->paid(),
1699
+				'txn_status'                   => $payment->transaction()->status_ID(),
1700
+				'pay_status'                   => $payment->STS_ID(),
1701
+				'registrations'                => $this->_registration_payment_data_array($REG_IDs),
1702
+				'delete_txn_reg_status_change' => $delete_txn_reg_status_change,
1703
+			);
1704
+		} else {
1705
+			$this->_get_payment_status_array();
1706
+
1707
+			return array(
1708
+				'amount'           => $payment->amount(),
1709
+				'total_paid'       => $payment->transaction()->paid(),
1710
+				'txn_status'       => $payment->transaction()->status_ID(),
1711
+				'pay_status'       => $payment->STS_ID(),
1712
+				'PAY_ID'           => $payment->ID(),
1713
+				'STS_ID'           => $payment->STS_ID(),
1714
+				'status'           => self::$_pay_status[$payment->STS_ID()],
1715
+				'date'             => $payment->timestamp('Y-m-d', 'h:i a'),
1716
+				'method'           => strtoupper($payment->source()),
1717
+				'PM_ID'            => $payment->payment_method() ? $payment->payment_method()->ID() : 1,
1718
+				'gateway'          => $payment->payment_method() ? $payment->payment_method()->admin_name() : esc_html__("Unknown",
1719
+					'event_espresso'),
1720
+				'gateway_response' => $payment->gateway_response(),
1721
+				'txn_id_chq_nmbr'  => $payment->txn_id_chq_nmbr(),
1722
+				'po_number'        => $payment->po_number(),
1723
+				'extra_accntng'    => $payment->extra_accntng(),
1724
+				'registrations'    => $this->_registration_payment_data_array($REG_IDs),
1725
+			);
1726
+		}
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * delete_payment
1732
+	 *    delete a payment or refund made towards a transaction
1733
+	 *
1734
+	 * @access public
1735
+	 * @return void
1736
+	 */
1737
+	public function delete_payment()
1738
+	{
1739
+		$json_response_data = array('return_data' => false);
1740
+		$PAY_ID             = isset($this->_req_data['delete_txn_admin_payment'], $this->_req_data['delete_txn_admin_payment']['PAY_ID']) ? absint($this->_req_data['delete_txn_admin_payment']['PAY_ID']) : 0;
1741
+		if ($PAY_ID) {
1742
+			$delete_txn_reg_status_change = isset($this->_req_data['delete_txn_reg_status_change']) ? $this->_req_data['delete_txn_reg_status_change'] : false;
1743
+			$payment                      = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
1744
+			if ($payment instanceof EE_Payment) {
1745
+				$REG_IDs = $this->_get_existing_reg_payment_REG_IDs($payment);
1746
+				/** @type EE_Transaction_Payments $transaction_payments */
1747
+				$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
1748
+				if ($transaction_payments->delete_payment_and_update_transaction($payment)) {
1749
+					$json_response_data['return_data'] = $this->_build_payment_json_response($payment, $REG_IDs,
1750
+						$delete_txn_reg_status_change);
1751
+					if ($delete_txn_reg_status_change) {
1752
+						$this->_req_data['txn_reg_status_change'] = $delete_txn_reg_status_change;
1753
+						//MAKE sure we also add the delete_txn_req_status_change to the
1754
+						//$_REQUEST global because that's how messages will be looking for it.
1755
+						$_REQUEST['txn_reg_status_change'] = $delete_txn_reg_status_change;
1756
+						$this->_maybe_send_notifications();
1757
+						$this->_process_registration_status_change($payment->transaction(), $REG_IDs);
1758
+					}
1759
+				}
1760
+			} else {
1761
+				EE_Error::add_error(
1762
+					esc_html__('Valid Payment data could not be retrieved from the database.', 'event_espresso'),
1763
+					__FILE__, __FUNCTION__, __LINE__
1764
+				);
1765
+			}
1766
+		} else {
1767
+			EE_Error::add_error(
1768
+				esc_html__('A valid Payment ID was not received, therefore payment form data could not be loaded.',
1769
+					'event_espresso'),
1770
+				__FILE__, __FUNCTION__, __LINE__
1771
+			);
1772
+		}
1773
+		$notices              = EE_Error::get_notices(false, false, false);
1774
+		$this->_template_args = array(
1775
+			'data'      => $json_response_data,
1776
+			'success'   => $notices['success'],
1777
+			'error'     => $notices['errors'],
1778
+			'attention' => $notices['attention']
1779
+		);
1780
+		$this->_return_json();
1781
+	}
1782
+
1783
+
1784
+	/**
1785
+	 * _registration_payment_data_array
1786
+	 * adds info for 'owing' and 'paid' for each registration to the json response
1787
+	 *
1788
+	 * @access protected
1789
+	 *
1790
+	 * @param array $REG_IDs
1791
+	 *
1792
+	 * @return array
1793
+	 */
1794
+	protected function _registration_payment_data_array($REG_IDs)
1795
+	{
1796
+		$registration_payment_data = array();
1797
+		//if non empty reg_ids lets get an array of registrations and update the values for the apply_payment/refund rows.
1798
+		if ( ! empty($REG_IDs)) {
1799
+			$registrations = EEM_Registration::instance()->get_all(array(array('REG_ID' => array('IN', $REG_IDs))));
1800
+			foreach ($registrations as $registration) {
1801
+				if ($registration instanceof EE_Registration) {
1802
+					$registration_payment_data[$registration->ID()] = array(
1803
+						'paid'  => $registration->pretty_paid(),
1804
+						'owing' => EEH_Template::format_currency($registration->final_price() - $registration->paid()),
1805
+					);
1806
+				}
1807
+			}
1808
+		}
1809
+
1810
+		return $registration_payment_data;
1811
+	}
1812
+
1813
+
1814
+	/**
1815
+	 * _maybe_send_notifications
1816
+	 *
1817
+	 * determines whether or not the admin has indicated that notifications should be sent.
1818
+	 * If so, will toggle a filter switch for delivering registration notices.
1819
+	 * If passed an EE_Payment object, then it will trigger payment notifications instead.
1820
+	 *
1821
+	 * @access protected
1822
+	 *
1823
+	 * @param \EE_Payment | null $payment
1824
+	 */
1825
+	protected function _maybe_send_notifications($payment = null)
1826
+	{
1827
+		switch ($payment instanceof EE_Payment) {
1828
+			// payment notifications
1829
+			case true :
1830
+				if (
1831
+					isset(
1832
+						$this->_req_data['txn_payments'],
1833
+						$this->_req_data['txn_payments']['send_notifications']
1834
+					) &&
1835
+					filter_var($this->_req_data['txn_payments']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
1836
+				) {
1837
+					$this->_process_payment_notification($payment);
1838
+				}
1839
+				break;
1840
+			// registration notifications
1841
+			case false :
1842
+				if (
1843
+					isset(
1844
+						$this->_req_data['txn_reg_status_change'],
1845
+						$this->_req_data['txn_reg_status_change']['send_notifications']
1846
+					) &&
1847
+					filter_var($this->_req_data['txn_reg_status_change']['send_notifications'], FILTER_VALIDATE_BOOLEAN)
1848
+				) {
1849
+					add_filter('FHEE__EED_Messages___maybe_registration__deliver_notifications', '__return_true');
1850
+				}
1851
+				break;
1852
+		}
1853
+	}
1854
+
1855
+
1856
+	/**
1857
+	 * _send_payment_reminder
1858
+	 *    generates HTML for the View Transaction Details Admin page
1859
+	 *
1860
+	 * @access protected
1861
+	 * @return void
1862
+	 */
1863
+	protected function _send_payment_reminder()
1864
+	{
1865
+		$TXN_ID      = ( ! empty($this->_req_data['TXN_ID'])) ? absint($this->_req_data['TXN_ID']) : false;
1866
+		$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
1867
+		$query_args  = isset($this->_req_data['redirect_to']) ? array(
1868
+			'action' => $this->_req_data['redirect_to'],
1869
+			'TXN_ID' => $this->_req_data['TXN_ID']
1870
+		) : array();
1871
+		do_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
1872
+			$transaction);
1873
+		$this->_redirect_after_action(false, esc_html__('payment reminder', 'event_espresso'),
1874
+			esc_html__('sent', 'event_espresso'), $query_args, true);
1875
+	}
1876
+
1877
+
1878
+	/**
1879
+	 *  get_transactions
1880
+	 *    get transactions for given parameters (used by list table)
1881
+	 *
1882
+	 * @param  int     $perpage how many transactions displayed per page
1883
+	 * @param  boolean $count   return the count or objects
1884
+	 * @param string   $view
1885
+	 *
1886
+	 * @return mixed int = count || array of transaction objects
1887
+	 */
1888
+	public function get_transactions($perpage, $count = false, $view = '')
1889
+	{
1890
+
1891
+		$TXN = EEM_Transaction::instance();
1892
+
1893
+		$start_date = isset($this->_req_data['txn-filter-start-date']) ? wp_strip_all_tags($this->_req_data['txn-filter-start-date']) : date('m/d/Y',
1894
+			strtotime('-10 year'));
1895
+		$end_date   = isset($this->_req_data['txn-filter-end-date']) ? wp_strip_all_tags($this->_req_data['txn-filter-end-date']) : date('m/d/Y');
1896
+
1897
+		//make sure our timestamps start and end right at the boundaries for each day
1898
+		$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1899
+		$end_date   = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1900
+
1901
+
1902
+		//convert to timestamps
1903
+		$start_date = strtotime($start_date);
1904
+		$end_date   = strtotime($end_date);
1905
+
1906
+		//makes sure start date is the lowest value and vice versa
1907
+		$start_date = min($start_date, $end_date);
1908
+		$end_date   = max($start_date, $end_date);
1909
+
1910
+		//convert to correct format for query
1911
+		$start_date = EEM_Transaction::instance()->convert_datetime_for_query('TXN_timestamp',
1912
+			date('Y-m-d H:i:s', $start_date), 'Y-m-d H:i:s');
1913
+		$end_date   = EEM_Transaction::instance()->convert_datetime_for_query('TXN_timestamp',
1914
+			date('Y-m-d H:i:s', $end_date), 'Y-m-d H:i:s');
1915
+
1916
+
1917
+		//set orderby
1918
+		$this->_req_data['orderby'] = ! empty($this->_req_data['orderby']) ? $this->_req_data['orderby'] : '';
1919
+
1920
+		switch ($this->_req_data['orderby']) {
1921
+			case 'TXN_ID':
1922
+				$orderby = 'TXN_ID';
1923
+				break;
1924
+			case 'ATT_fname':
1925
+				$orderby = 'Registration.Attendee.ATT_fname';
1926
+				break;
1927
+			case 'event_name':
1928
+				$orderby = 'Registration.Event.EVT_name';
1929
+				break;
1930
+			default: //'TXN_timestamp'
1931
+				$orderby = 'TXN_timestamp';
1932
+		}
1933
+
1934
+		$sort         = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order'] : 'DESC';
1935
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged']) ? $this->_req_data['paged'] : 1;
1936
+		$per_page     = isset($perpage) && ! empty($perpage) ? $perpage : 10;
1937
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage']) ? $this->_req_data['perpage'] : $per_page;
1938
+
1939
+		$offset = ($current_page - 1) * $per_page;
1940
+		$limit  = array($offset, $per_page);
1941
+
1942
+		$_where = array(
1943
+			'TXN_timestamp'          => array('BETWEEN', array($start_date, $end_date)),
1944
+			'Registration.REG_count' => 1
1945
+		);
1946
+
1947
+		if (isset($this->_req_data['EVT_ID'])) {
1948
+			$_where['Registration.EVT_ID'] = $this->_req_data['EVT_ID'];
1949
+		}
1950
+
1951
+		if (isset($this->_req_data['s'])) {
1952
+			$search_string = '%' . $this->_req_data['s'] . '%';
1953
+			$_where['OR']  = array(
1954
+				'Registration.Event.EVT_name'         => array('LIKE', $search_string),
1955
+				'Registration.Event.EVT_desc'         => array('LIKE', $search_string),
1956
+				'Registration.Event.EVT_short_desc'   => array('LIKE', $search_string),
1957
+				'Registration.Attendee.ATT_full_name' => array('LIKE', $search_string),
1958
+				'Registration.Attendee.ATT_fname'     => array('LIKE', $search_string),
1959
+				'Registration.Attendee.ATT_lname'     => array('LIKE', $search_string),
1960
+				'Registration.Attendee.ATT_short_bio' => array('LIKE', $search_string),
1961
+				'Registration.Attendee.ATT_email'     => array('LIKE', $search_string),
1962
+				'Registration.Attendee.ATT_address'   => array('LIKE', $search_string),
1963
+				'Registration.Attendee.ATT_address2'  => array('LIKE', $search_string),
1964
+				'Registration.Attendee.ATT_city'      => array('LIKE', $search_string),
1965
+				'Registration.REG_final_price'        => array('LIKE', $search_string),
1966
+				'Registration.REG_code'               => array('LIKE', $search_string),
1967
+				'Registration.REG_count'              => array('LIKE', $search_string),
1968
+				'Registration.REG_group_size'         => array('LIKE', $search_string),
1969
+				'Registration.Ticket.TKT_name'        => array('LIKE', $search_string),
1970
+				'Registration.Ticket.TKT_description' => array('LIKE', $search_string),
1971
+				'Payment.PAY_source'                  => array('LIKE', $search_string),
1972
+				'Payment.Payment_Method.PMD_name'     => array('LIKE', $search_string),
1973
+				'TXN_session_data'                    => array('LIKE', $search_string),
1974
+				'Payment.PAY_txn_id_chq_nmbr'         => array('LIKE', $search_string)
1975
+			);
1976
+		}
1977
+
1978
+		//failed transactions
1979
+		$failed    = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] == 'failed' && ! $count) || ($count && $view == 'failed') ? true : false;
1980
+		$abandoned = ( ! empty($this->_req_data['status']) && $this->_req_data['status'] == 'abandoned' && ! $count) || ($count && $view == 'abandoned') ? true : false;
1981
+
1982
+		if ($failed) {
1983
+			$_where['STS_ID'] = EEM_Transaction::failed_status_code;
1984
+		} else if ($abandoned) {
1985
+			$_where['STS_ID'] = EEM_Transaction::abandoned_status_code;
1986
+		} else {
1987
+			$_where['STS_ID']  = array('!=', EEM_Transaction::failed_status_code);
1988
+			$_where['STS_ID*'] = array('!=', EEM_Transaction::abandoned_status_code);
1989
+		}
1990
+
1991
+		$query_params = array(
1992
+			$_where,
1993
+			'order_by' => array($orderby => $sort),
1994
+			'limit' => $limit,
1995
+			'default_where_conditions' => EEM_Base::default_where_conditions_this_only
1996
+		);
1997
+
1998
+		$transactions = $count ? $TXN->count(array($_where), 'TXN_ID', true) : $TXN->get_all($query_params);
1999
+
2000
+
2001
+		return $transactions;
2002
+
2003
+	}
2004 2004
 
2005 2005
 
2006 2006
 }
Please login to merge, or discard this patch.
modules/messages/EED_Messages.module.php 1 patch
Indentation   +1080 added lines, -1080 removed lines patch added patch discarded remove patch
@@ -13,1095 +13,1095 @@
 block discarded – undo
13 13
 class EED_Messages extends EED_Module
14 14
 {
15 15
 
16
-    /**
17
-     * This holds the EE_messages controller
18
-     *
19
-     * @deprecated 4.9.0
20
-     * @var EE_messages $_EEMSG
21
-     */
22
-    protected static $_EEMSG;
23
-
24
-    /**
25
-     * @type EE_Message_Resource_Manager $_message_resource_manager
26
-     */
27
-    protected static $_message_resource_manager;
28
-
29
-    /**
30
-     * This holds the EE_Messages_Processor business class.
31
-     *
32
-     * @type EE_Messages_Processor
33
-     */
34
-    protected static $_MSG_PROCESSOR;
35
-
36
-    /**
37
-     * holds all the paths for various messages components.
38
-     * Utilized by autoloader registry
39
-     *
40
-     * @var array
41
-     */
42
-    protected static $_MSG_PATHS;
43
-
44
-
45
-    /**
46
-     * This will hold an array of messages template packs that are registered in the messages system.
47
-     * Format is:
48
-     * array(
49
-     *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
50
-     * )
51
-     *
52
-     * @var EE_Messages_Template_Pack[]
53
-     */
54
-    protected static $_TMP_PACKS = array();
55
-
56
-
57
-    /**
58
-     * @return EED_Messages
59
-     */
60
-    public static function instance()
61
-    {
62
-        return parent::get_instance(__CLASS__);
63
-    }
64
-
65
-
66
-    /**
67
-     *  set_hooks - for hooking into EE Core, other modules, etc
68
-     *
69
-     * @since 4.5.0
70
-     * @return    void
71
-     */
72
-    public static function set_hooks()
73
-    {
74
-        //actions
75
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
76
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
77
-            array('EED_Messages', 'maybe_registration'), 10, 2);
78
-        //filters
79
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
80
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
81
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
82
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
83
-        //register routes
84
-        self::_register_routes();
85
-    }
86
-
87
-    /**
88
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
89
-     *
90
-     * @access    public
91
-     * @return    void
92
-     */
93
-    public static function set_hooks_admin()
94
-    {
95
-        //actions
96
-        add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
97
-        add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
98
-            array('EED_Messages', 'payment_reminder'), 10);
99
-        add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
100
-            array('EED_Messages', 'maybe_registration'), 10, 3);
101
-        add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
102
-            array('EED_Messages', 'send_newsletter_message'), 10, 2);
103
-        add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
104
-            array('EED_Messages', 'cancelled_registration'), 10);
105
-        add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
106
-            array('EED_Messages', 'process_admin_payment'), 10, 1);
107
-        //filters
108
-        add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
109
-            array('EED_Messages', 'process_resend'), 10, 2);
110
-        add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
111
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
112
-        add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
113
-            array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
114
-    }
115
-
116
-
117
-    /**
118
-     * All the message triggers done by route go in here.
119
-     *
120
-     * @since 4.5.0
121
-     * @return void
122
-     */
123
-    protected static function _register_routes()
124
-    {
125
-        EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
126
-        EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
127
-        EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
128
-        EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
129
-        do_action('AHEE__EED_Messages___register_routes');
130
-    }
131
-
132
-
133
-    /**
134
-     * This is called when a browser display trigger is executed.
135
-     * The browser display trigger is typically used when a already generated message is displayed directly in the
136
-     * browser.
137
-     *
138
-     * @since 4.9.0
139
-     * @param WP $WP
140
-     */
141
-    public function browser_trigger($WP)
142
-    {
143
-        //ensure controller is loaded
144
-        self::_load_controller();
145
-        $token = EE_Registry::instance()->REQ->get('token');
146
-        try {
147
-            $mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
148
-            self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
149
-        } catch (EE_Error $e) {
150
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
151
-                'event_espresso');
152
-            // add specific message for developers if WP_DEBUG in on
153
-            $error_msg .= '||' . $e->getMessage();
154
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
155
-        }
156
-    }
157
-
158
-
159
-    /**
160
-     * This is called when a browser error trigger is executed.
161
-     * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
162
-     * message and display it.
163
-     *
164
-     * @since 4.9.0
165
-     * @param $WP
166
-     */
167
-    public function browser_error_trigger($WP)
168
-    {
169
-        $token = EE_Registry::instance()->REQ->get('token');
170
-        if ($token) {
171
-            $message = EEM_Message::instance()->get_one_by_token($token);
172
-            if ($message instanceof EE_Message) {
173
-                header('HTTP/1.1 200 OK');
174
-                $error_msg = nl2br($message->error_message());
175
-                ?>
16
+	/**
17
+	 * This holds the EE_messages controller
18
+	 *
19
+	 * @deprecated 4.9.0
20
+	 * @var EE_messages $_EEMSG
21
+	 */
22
+	protected static $_EEMSG;
23
+
24
+	/**
25
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
26
+	 */
27
+	protected static $_message_resource_manager;
28
+
29
+	/**
30
+	 * This holds the EE_Messages_Processor business class.
31
+	 *
32
+	 * @type EE_Messages_Processor
33
+	 */
34
+	protected static $_MSG_PROCESSOR;
35
+
36
+	/**
37
+	 * holds all the paths for various messages components.
38
+	 * Utilized by autoloader registry
39
+	 *
40
+	 * @var array
41
+	 */
42
+	protected static $_MSG_PATHS;
43
+
44
+
45
+	/**
46
+	 * This will hold an array of messages template packs that are registered in the messages system.
47
+	 * Format is:
48
+	 * array(
49
+	 *    'template_pack_dbref' => EE_Messages_Template_Pack (instance)
50
+	 * )
51
+	 *
52
+	 * @var EE_Messages_Template_Pack[]
53
+	 */
54
+	protected static $_TMP_PACKS = array();
55
+
56
+
57
+	/**
58
+	 * @return EED_Messages
59
+	 */
60
+	public static function instance()
61
+	{
62
+		return parent::get_instance(__CLASS__);
63
+	}
64
+
65
+
66
+	/**
67
+	 *  set_hooks - for hooking into EE Core, other modules, etc
68
+	 *
69
+	 * @since 4.5.0
70
+	 * @return    void
71
+	 */
72
+	public static function set_hooks()
73
+	{
74
+		//actions
75
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
76
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
77
+			array('EED_Messages', 'maybe_registration'), 10, 2);
78
+		//filters
79
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
80
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
81
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
82
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
83
+		//register routes
84
+		self::_register_routes();
85
+	}
86
+
87
+	/**
88
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
89
+	 *
90
+	 * @access    public
91
+	 * @return    void
92
+	 */
93
+	public static function set_hooks_admin()
94
+	{
95
+		//actions
96
+		add_action('AHEE__EE_Payment_Processor__update_txn_based_on_payment', array('EED_Messages', 'payment'), 10, 2);
97
+		add_action('AHEE__Transactions_Admin_Page___send_payment_reminder__process_admin_payment_reminder',
98
+			array('EED_Messages', 'payment_reminder'), 10);
99
+		add_action('AHEE__EE_Registration_Processor__trigger_registration_update_notifications',
100
+			array('EED_Messages', 'maybe_registration'), 10, 3);
101
+		add_action('AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send__with_registrations',
102
+			array('EED_Messages', 'send_newsletter_message'), 10, 2);
103
+		add_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction',
104
+			array('EED_Messages', 'cancelled_registration'), 10);
105
+		add_action('AHEE__EE_Admin_Page___process_admin_payment_notification',
106
+			array('EED_Messages', 'process_admin_payment'), 10, 1);
107
+		//filters
108
+		add_filter('FHEE__EE_Admin_Page___process_resend_registration__success',
109
+			array('EED_Messages', 'process_resend'), 10, 2);
110
+		add_filter('FHEE__EE_Registration__receipt_url__receipt_url',
111
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
112
+		add_filter('FHEE__EE_Registration__invoice_url__invoice_url',
113
+			array('EED_Messages', 'registration_message_trigger_url'), 10, 4);
114
+	}
115
+
116
+
117
+	/**
118
+	 * All the message triggers done by route go in here.
119
+	 *
120
+	 * @since 4.5.0
121
+	 * @return void
122
+	 */
123
+	protected static function _register_routes()
124
+	{
125
+		EE_Config::register_route('msg_url_trigger', 'Messages', 'run');
126
+		EE_Config::register_route('msg_cron_trigger', 'Messages', 'execute_batch_request');
127
+		EE_Config::register_route('msg_browser_trigger', 'Messages', 'browser_trigger');
128
+		EE_Config::register_route('msg_browser_error_trigger', 'Messages', 'browser_error_trigger');
129
+		do_action('AHEE__EED_Messages___register_routes');
130
+	}
131
+
132
+
133
+	/**
134
+	 * This is called when a browser display trigger is executed.
135
+	 * The browser display trigger is typically used when a already generated message is displayed directly in the
136
+	 * browser.
137
+	 *
138
+	 * @since 4.9.0
139
+	 * @param WP $WP
140
+	 */
141
+	public function browser_trigger($WP)
142
+	{
143
+		//ensure controller is loaded
144
+		self::_load_controller();
145
+		$token = EE_Registry::instance()->REQ->get('token');
146
+		try {
147
+			$mtg = new EE_Message_Generated_From_Token($token, 'html', self::$_message_resource_manager);
148
+			self::$_MSG_PROCESSOR->generate_and_send_now($mtg);
149
+		} catch (EE_Error $e) {
150
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
151
+				'event_espresso');
152
+			// add specific message for developers if WP_DEBUG in on
153
+			$error_msg .= '||' . $e->getMessage();
154
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
155
+		}
156
+	}
157
+
158
+
159
+	/**
160
+	 * This is called when a browser error trigger is executed.
161
+	 * When triggered this will grab the EE_Message matching the token in the request and use that to get the error
162
+	 * message and display it.
163
+	 *
164
+	 * @since 4.9.0
165
+	 * @param $WP
166
+	 */
167
+	public function browser_error_trigger($WP)
168
+	{
169
+		$token = EE_Registry::instance()->REQ->get('token');
170
+		if ($token) {
171
+			$message = EEM_Message::instance()->get_one_by_token($token);
172
+			if ($message instanceof EE_Message) {
173
+				header('HTTP/1.1 200 OK');
174
+				$error_msg = nl2br($message->error_message());
175
+				?>
176 176
                 <!DOCTYPE html>
177 177
                 <html>
178 178
                 <head></head>
179 179
                 <body>
180 180
                 <?php echo empty($error_msg)
181
-                    ? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
182
-                        'event_espresso')
183
-                    : wp_kses(
184
-                        $error_msg,
185
-                        array(
186
-                            'a'      => array(
187
-                                'href'  => array(),
188
-                                'title' => array(),
189
-                            ),
190
-                            'span'   => array(),
191
-                            'div'    => array(),
192
-                            'p'      => array(),
193
-                            'strong' => array(),
194
-                            'em'     => array(),
195
-                            'br'     => array(),
196
-                        )
197
-                    ); ?>
181
+					? esc_html__('Unfortunately, we were unable to capture the error message for this message.',
182
+						'event_espresso')
183
+					: wp_kses(
184
+						$error_msg,
185
+						array(
186
+							'a'      => array(
187
+								'href'  => array(),
188
+								'title' => array(),
189
+							),
190
+							'span'   => array(),
191
+							'div'    => array(),
192
+							'p'      => array(),
193
+							'strong' => array(),
194
+							'em'     => array(),
195
+							'br'     => array(),
196
+						)
197
+					); ?>
198 198
                 </body>
199 199
                 </html>
200 200
                 <?php
201
-                exit;
202
-            }
203
-        }
204
-        return;
205
-    }
206
-
207
-
208
-    /**
209
-     *  This runs when the msg_url_trigger route has initiated.
210
-     *
211
-     * @since 4.5.0
212
-     * @param WP $WP
213
-     * @throws EE_Error
214
-     * @return    void
215
-     */
216
-    public function run($WP)
217
-    {
218
-        //ensure controller is loaded
219
-        self::_load_controller();
220
-        // attempt to process message
221
-        try {
222
-            /** @type EE_Message_To_Generate_From_Request $message_to_generate */
223
-            $message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
224
-            self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
225
-        } catch (EE_Error $e) {
226
-            $error_msg = __('Please note that a system message failed to send due to a technical issue.',
227
-                'event_espresso');
228
-            // add specific message for developers if WP_DEBUG in on
229
-            $error_msg .= '||' . $e->getMessage();
230
-            EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
231
-        }
232
-    }
233
-
234
-
235
-    /**
236
-     * This is triggered by the 'msg_cron_trigger' route.
237
-     *
238
-     * @param WP $WP
239
-     */
240
-    public function execute_batch_request($WP)
241
-    {
242
-        $this->run_cron();
243
-        header('HTTP/1.1 200 OK');
244
-        exit();
245
-    }
246
-
247
-
248
-    /**
249
-     * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
250
-     * request.
251
-     */
252
-    public function run_cron()
253
-    {
254
-        self::_load_controller();
255
-        //get required vars
256
-        $cron_type     = EE_Registry::instance()->REQ->get('type');
257
-        $transient_key = EE_Registry::instance()->REQ->get('key');
258
-
259
-        //now let's verify transient, if not valid exit immediately
260
-        if (! get_transient($transient_key)) {
261
-            /**
262
-             * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
263
-             */
264
-            trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
265
-        }
266
-
267
-        //if made it here, lets' delete the transient to keep the db clean
268
-        delete_transient($transient_key);
269
-
270
-        if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
271
-
272
-            $method = 'batch_' . $cron_type . '_from_queue';
273
-            if (method_exists(self::$_MSG_PROCESSOR, $method)) {
274
-                self::$_MSG_PROCESSOR->$method();
275
-            } else {
276
-                //no matching task
277
-                /**
278
-                 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
279
-                 */
280
-                trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
281
-                    $cron_type)));
282
-            }
283
-        }
284
-
285
-        do_action('FHEE__EED_Messages__run_cron__end');
286
-    }
287
-
288
-
289
-    /**
290
-     * This is used to retrieve the template pack for the given name.
291
-     * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
292
-     * the default template pack is returned.
293
-     *
294
-     * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
295
-     * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
296
-     *                                   in generating the Pack class name).
297
-     * @return EE_Messages_Template_Pack
298
-     */
299
-    public static function get_template_pack($template_pack_name)
300
-    {
301
-        EE_Registry::instance()->load_helper('MSG_Template');
302
-        return EEH_MSG_Template::get_template_pack($template_pack_name);
303
-    }
304
-
305
-
306
-    /**
307
-     * Retrieves an array of all template packs.
308
-     * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
309
-     *
310
-     * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
311
-     * @return EE_Messages_Template_Pack[]
312
-     */
313
-    public static function get_template_packs()
314
-    {
315
-        EE_Registry::instance()->load_helper('MSG_Template');
316
-
317
-        //for backward compat, let's make sure this returns in the same format as originally.
318
-        $template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
319
-        $template_pack_collection->rewind();
320
-        $template_packs = array();
321
-        while ($template_pack_collection->valid()) {
322
-            $template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
323
-            $template_pack_collection->next();
324
-        }
325
-        return $template_packs;
326
-    }
327
-
328
-
329
-    /**
330
-     * This simply makes sure the autoloaders are registered for the EE_messages system.
331
-     *
332
-     * @since 4.5.0
333
-     * @return void
334
-     */
335
-    public static function set_autoloaders()
336
-    {
337
-        if (empty(self::$_MSG_PATHS)) {
338
-            self::_set_messages_paths();
339
-            foreach (self::$_MSG_PATHS as $path) {
340
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
341
-            }
342
-            // add aliases
343
-            EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
344
-            EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
345
-        }
346
-    }
347
-
348
-
349
-    /**
350
-     * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
351
-     * for use by the Messages Autoloaders
352
-     *
353
-     * @since 4.5.0
354
-     * @return void.
355
-     */
356
-    protected static function _set_messages_paths()
357
-    {
358
-        $dir_ref = array(
359
-            'messages/message_type',
360
-            'messages/messenger',
361
-            'messages/defaults',
362
-            'messages/defaults/email',
363
-            'messages/data_class',
364
-            'messages/validators',
365
-            'messages/validators/email',
366
-            'messages/validators/html',
367
-            'shortcodes',
368
-        );
369
-        $paths   = array();
370
-        foreach ($dir_ref as $index => $dir) {
371
-            $paths[$index] = EE_LIBRARIES . $dir;
372
-        }
373
-        self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
374
-    }
375
-
376
-
377
-    /**
378
-     * Takes care of loading dependencies
379
-     *
380
-     * @since 4.5.0
381
-     * @return void
382
-     */
383
-    protected static function _load_controller()
384
-    {
385
-        if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
386
-            EE_Registry::instance()->load_core('Request_Handler');
387
-            self::set_autoloaders();
388
-            self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
389
-            self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
390
-            self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
391
-        }
392
-    }
393
-
394
-
395
-    /**
396
-     * @param EE_Transaction $transaction
397
-     */
398
-    public static function payment_reminder(EE_Transaction $transaction)
399
-    {
400
-        self::_load_controller();
401
-        $data = array($transaction, null);
402
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
403
-    }
404
-
405
-
406
-    /**
407
-     * Any messages triggers for after successful gateway payments should go in here.
408
-     *
409
-     * @param  EE_Transaction object
410
-     * @param  EE_Payment     object
411
-     * @return void
412
-     */
413
-    public static function payment(EE_Transaction $transaction, EE_Payment $payment)
414
-    {
415
-        self::_load_controller();
416
-        $data = array($transaction, $payment);
417
-        EE_Registry::instance()->load_helper('MSG_Template');
418
-        $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
419
-        //if payment amount is less than 0 then switch to payment_refund message type.
420
-        $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
421
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
422
-    }
423
-
424
-
425
-    /**
426
-     * @param EE_Transaction $transaction
427
-     */
428
-    public static function cancelled_registration(EE_Transaction $transaction)
429
-    {
430
-        self::_load_controller();
431
-        $data = array($transaction, null);
432
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
433
-    }
434
-
435
-
436
-    /**
437
-     * Trigger for Registration messages
438
-     * Note that what registration message type is sent depends on what the reg status is for the registrations on the
439
-     * incoming transaction.
440
-     *
441
-     * @param EE_Registration $registration
442
-     * @param array           $extra_details
443
-     * @return void
444
-     */
445
-    public static function maybe_registration(EE_Registration $registration, $extra_details = array())
446
-    {
447
-
448
-        if (! self::_verify_registration_notification_send($registration, $extra_details)) {
449
-            //no messages please
450
-            return;
451
-        }
452
-
453
-
454
-        //get all registrations so we make sure we send messages for the right status.
455
-        $all_registrations = $registration->transaction()->registrations();
456
-
457
-        //cached array of statuses so we only trigger messages once per status.
458
-        $statuses_sent = array();
459
-        self::_load_controller();
460
-        $mtgs = array();
461
-
462
-        //loop through registrations and trigger messages once per status.
463
-        foreach ($all_registrations as $reg) {
464
-
465
-            //already triggered?
466
-            if (in_array($reg->status_ID(), $statuses_sent)) {
467
-                continue;
468
-            }
469
-
470
-            $message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
471
-            $mtgs            = array_merge(
472
-                    $mtgs,
473
-                    self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
474
-                            $message_type,
475
-                            array($registration->transaction(), null, $reg->status_ID())
476
-                    )
477
-            );
478
-            $statuses_sent[] = $reg->status_ID();
479
-        }
480
-
481
-        if (count($statuses_sent) > 1) {
482
-            $mtgs = array_merge(
483
-                $mtgs,
484
-                self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
485
-                    'registration_summary',
486
-                    array($registration->transaction(), null)
487
-                )
488
-            );
489
-        }
490
-
491
-        //batch queue and initiate request
492
-        self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
493
-        self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
494
-    }
495
-
496
-
497
-    /**
498
-     * This is a helper method used to very whether a registration notification should be sent or
499
-     * not.  Prevents duplicate notifications going out for registration context notifications.
500
-     *
501
-     * @param EE_Registration $registration  [description]
502
-     * @param array           $extra_details [description]
503
-     * @return bool          true = send away, false = nope halt the presses.
504
-     */
505
-    protected static function _verify_registration_notification_send(
506
-        EE_Registration $registration,
507
-        $extra_details = array()
508
-    ) {
509
-        //self::log(
510
-        //	__CLASS__, __FUNCTION__, __LINE__,
511
-        //	$registration->transaction(),
512
-        //	array( '$extra_details' => $extra_details )
513
-        //);
514
-        // currently only using this to send messages for the primary registrant
515
-        if (! $registration->is_primary_registrant()) {
516
-            return false;
517
-        }
518
-        // first we check if we're in admin and not doing front ajax
519
-        if (is_admin() && ! EE_FRONT_AJAX) {
520
-            //make sure appropriate admin params are set for sending messages
521
-            if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
522
-                //no messages sent please.
523
-                return false;
524
-            }
525
-        } else {
526
-            // frontend request (either regular or via AJAX)
527
-            // TXN is NOT finalized ?
528
-            if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
529
-                return false;
530
-            }
531
-            // return visit but nothing changed ???
532
-            if (
533
-                isset($extra_details['revisit'], $extra_details['status_updates']) &&
534
-                $extra_details['revisit'] && ! $extra_details['status_updates']
535
-            ) {
536
-                return false;
537
-            }
538
-            // NOT sending messages && reg status is something other than "Not-Approved"
539
-            if (
540
-                ! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
541
-                $registration->status_ID() !== EEM_Registration::status_id_not_approved
542
-            ) {
543
-                return false;
544
-            }
545
-        }
546
-        // release the kraken
547
-        return true;
548
-    }
549
-
550
-
551
-    /**
552
-     * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
553
-     * status id.
554
-     *
555
-     * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
556
-     *                    or EEH_MSG_Template::convert_reg_status_to_message_type
557
-     * @param string $reg_status
558
-     * @return array
559
-     */
560
-    protected static function _get_reg_status_array($reg_status = '')
561
-    {
562
-        EE_Registry::instance()->load_helper('MSG_Template');
563
-        return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
564
-            ? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
565
-            : EEH_MSG_Template::reg_status_to_message_type_array();
566
-    }
567
-
568
-
569
-    /**
570
-     * Simply returns the payment message type for the given payment status.
571
-     *
572
-     * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
573
-     *                   or EEH_MSG_Template::convert_payment_status_to_message_type
574
-     * @param string $payment_status The payment status being matched.
575
-     * @return string|bool The payment message type slug matching the status or false if no match.
576
-     */
577
-    protected static function _get_payment_message_type($payment_status)
578
-    {
579
-        EE_Registry::instance()->load_helper('MSG_Template');
580
-        return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
581
-            ? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
582
-            : false;
583
-    }
584
-
585
-
586
-    /**
587
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
588
-     *
589
-     * @access public
590
-     * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
591
-     * @return bool          success/fail
592
-     */
593
-    public static function process_resend($req_data)
594
-    {
595
-        self::_load_controller();
596
-
597
-        //if $msgID in this request then skip to the new resend_message
598
-        if (EE_Registry::instance()->REQ->get('MSG_ID')) {
599
-            return self::resend_message();
600
-        }
601
-
602
-        //make sure any incoming request data is set on the REQ so that it gets picked up later.
603
-        $req_data = (array)$req_data;
604
-        foreach ($req_data as $request_key => $request_value) {
605
-            EE_Registry::instance()->REQ->set($request_key, $request_value);
606
-        }
607
-
608
-        if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
609
-            return false;
610
-        }
611
-
612
-        try {
613
-            self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
614
-            self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
615
-        } catch (EE_Error $e) {
616
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
617
-            return false;
618
-        }
619
-        EE_Error::add_success(
620
-            __('Messages have been successfully queued for generation and sending.', 'event_espresso')
621
-        );
622
-        return true; //everything got queued.
623
-    }
624
-
625
-
626
-    /**
627
-     * Message triggers for a resending already sent message(s) (via EE_Message list table)
628
-     *
629
-     * @return bool
630
-     */
631
-    public static function resend_message()
632
-    {
633
-        self::_load_controller();
634
-
635
-        $msgID = EE_Registry::instance()->REQ->get('MSG_ID');
636
-        if (! $msgID) {
637
-            EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
638
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
639
-            return false;
640
-        }
641
-
642
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
643
-
644
-        //setup success message.
645
-        $count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
646
-        EE_Error::add_success(sprintf(
647
-            _n(
648
-                'There was %d message queued for resending.',
649
-                'There were %d messages queued for resending.',
650
-                $count_ready_for_resend,
651
-                'event_espresso'
652
-            ),
653
-            $count_ready_for_resend
654
-        ));
655
-        return true;
656
-    }
657
-
658
-
659
-    /**
660
-     * Message triggers for manual payment applied by admin
661
-     *
662
-     * @param  EE_Payment $payment EE_payment object
663
-     * @return bool              success/fail
664
-     */
665
-    public static function process_admin_payment(EE_Payment $payment)
666
-    {
667
-        EE_Registry::instance()->load_helper('MSG_Template');
668
-        //we need to get the transaction object
669
-        $transaction = $payment->transaction();
670
-        if ($transaction instanceof EE_Transaction) {
671
-            $data         = array($transaction, $payment);
672
-            $message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
673
-
674
-            //if payment amount is less than 0 then switch to payment_refund message type.
675
-            $message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
676
-
677
-            //if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
678
-            $message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
679
-
680
-            self::_load_controller();
681
-
682
-            self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
683
-
684
-            //get count of queued for generation
685
-            $count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
686
-                EEM_Message::status_incomplete,
687
-                EEM_Message::status_idle,
688
-            ));
689
-
690
-            if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
691
-                add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
692
-                return true;
693
-            } else {
694
-                $count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
695
-                /**
696
-                 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
697
-                 * IMMEDIATE generation.
698
-                 */
699
-                if ($count_failed > 0) {
700
-                    EE_Error::add_error(sprintf(
701
-                        _n(
702
-                            'The payment notification generation failed.',
703
-                            '%d payment notifications failed being sent.',
704
-                            $count_failed,
705
-                            'event_espresso'
706
-                        ),
707
-                        $count_failed
708
-                    ), __FILE__, __FUNCTION__, __LINE__);
709
-
710
-                    return false;
711
-                } else {
712
-                    add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
713
-                    return true;
714
-                }
715
-            }
716
-        } else {
717
-            EE_Error::add_error(
718
-                'Unable to generate the payment notification because the given value for the transaction is invalid.',
719
-                'event_espresso'
720
-            );
721
-            return false;
722
-        }
723
-    }
724
-
725
-
726
-    /**
727
-     * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
728
-     *
729
-     * @since   4.3.0
730
-     * @param  EE_Registration[] $registrations an array of EE_Registration objects
731
-     * @param  int               $grp_id        a specific message template group id.
732
-     * @return void
733
-     */
734
-    public static function send_newsletter_message($registrations, $grp_id)
735
-    {
736
-        //make sure mtp is id and set it in the EE_Request Handler later messages setup.
737
-        EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
738
-        self::_load_controller();
739
-        self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
740
-    }
741
-
742
-
743
-    /**
744
-     * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
745
-     *
746
-     * @since   4.3.0
747
-     * @param    string          $registration_message_trigger_url
748
-     * @param    EE_Registration $registration
749
-     * @param string             $messenger
750
-     * @param string             $message_type
751
-     * @return    string
752
-     */
753
-    public static function registration_message_trigger_url(
754
-        $registration_message_trigger_url,
755
-        EE_Registration $registration,
756
-        $messenger = 'html',
757
-        $message_type = 'invoice'
758
-    ) {
759
-        // whitelist $messenger
760
-        switch ($messenger) {
761
-            case 'pdf' :
762
-                $sending_messenger    = 'pdf';
763
-                $generating_messenger = 'html';
764
-                break;
765
-            case 'html' :
766
-            default :
767
-                $sending_messenger    = 'html';
768
-                $generating_messenger = 'html';
769
-                break;
770
-        }
771
-        // whitelist $message_type
772
-        switch ($message_type) {
773
-            case 'receipt' :
774
-                $message_type = 'receipt';
775
-                break;
776
-            case 'invoice' :
777
-            default :
778
-                $message_type = 'invoice';
779
-                break;
780
-        }
781
-        // verify that both the messenger AND the message type are active
782
-        if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
783
-            //need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
784
-            $template_query_params = array(
785
-                'MTP_is_active'    => true,
786
-                'MTP_messenger'    => $generating_messenger,
787
-                'MTP_message_type' => $message_type,
788
-                'Event.EVT_ID'     => $registration->event_ID(),
789
-            );
790
-            //get the message template group.
791
-            $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
792
-            //if we don't have an EE_Message_Template_Group then return
793
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
794
-                // remove EVT_ID from query params so that global templates get picked up
795
-                unset($template_query_params['Event.EVT_ID']);
796
-                //get global template as the fallback
797
-                $msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
798
-            }
799
-            //if we don't have an EE_Message_Template_Group then return
800
-            if (! $msg_template_group instanceof EE_Message_Template_Group) {
801
-                return '';
802
-            }
803
-            // generate the URL
804
-            $registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
805
-                $sending_messenger,
806
-                $generating_messenger,
807
-                'purchaser',
808
-                $message_type,
809
-                $registration,
810
-                $msg_template_group->ID(),
811
-                $registration->transaction_ID()
812
-            );
813
-
814
-        }
815
-        return $registration_message_trigger_url;
816
-    }
817
-
818
-
819
-    /**
820
-     * Use to generate and return a message preview!
821
-     *
822
-     * @param  string $type      This should correspond with a valid message type
823
-     * @param  string $context   This should correspond with a valid context for the message type
824
-     * @param  string $messenger This should correspond with a valid messenger.
825
-     * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
826
-     *                           preview
827
-     * @return bool|string The body of the message or if send is requested, sends.
828
-     * @throws EE_Error
829
-     */
830
-    public static function preview_message($type, $context, $messenger, $send = false)
831
-    {
832
-        self::_load_controller();
833
-        $mtg                     = new EE_Message_To_Generate(
834
-            $messenger,
835
-            $type,
836
-            array(),
837
-            $context,
838
-            true
839
-        );
840
-        $generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
841
-        if ($generated_preview_queue instanceof EE_Messages_Queue) {
842
-            //loop through all content for the preview and remove any persisted records.
843
-            $content = '';
844
-            foreach ($generated_preview_queue->get_message_repository() as $message) {
845
-                $content = $message->content();
846
-                if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
847
-                    $message->delete();
848
-                }
849
-            }
850
-            return $content;
851
-        } else {
852
-            return $generated_preview_queue;
853
-        }
854
-    }
855
-
856
-
857
-    /**
858
-     * This is a method that allows for sending a message using a messenger matching the string given and the provided
859
-     * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
860
-     * content found in the EE_Message objects in the queue.
861
-     *
862
-     * @since 4.9.0
863
-     * @param string            $messenger            a string matching a valid active messenger in the system
864
-     * @param string            $message_type         Although it seems contrary to the name of the method, a message
865
-     *                                                type name is still required to send along the message type to the
866
-     *                                                messenger because this is used for determining what specific
867
-     *                                                variations might be loaded for the generated message.
868
-     * @param EE_Messages_Queue $queue
869
-     * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
870
-     *                                                aggregate EE_Message object.
871
-     * @return bool          success or fail.
872
-     */
873
-    public static function send_message_with_messenger_only(
874
-        $messenger,
875
-        $message_type,
876
-        EE_Messages_Queue $queue,
877
-        $custom_subject = ''
878
-    ) {
879
-        self::_load_controller();
880
-        /** @type EE_Message_To_Generate_From_Queue $message_to_generate */
881
-        $message_to_generate = EE_Registry::instance()->load_lib(
882
-            'Message_To_Generate_From_Queue',
883
-            array(
884
-                $messenger,
885
-                $message_type,
886
-                $queue,
887
-                $custom_subject,
888
-            )
889
-        );
890
-        return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
891
-    }
892
-
893
-
894
-    /**
895
-     * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
896
-     *
897
-     * @since 4.9.0
898
-     * @param array $message_ids An array of message ids
899
-     * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
900
-     *              messages.
901
-     */
902
-    public static function generate_now($message_ids)
903
-    {
904
-        self::_load_controller();
905
-        $messages        = EEM_Message::instance()->get_all(
906
-            array(
907
-                0 => array(
908
-                    'MSG_ID' => array('IN', $message_ids),
909
-                    'STS_ID' => EEM_Message::status_incomplete,
910
-                ),
911
-            )
912
-        );
913
-        $generated_queue = false;
914
-        if ($messages) {
915
-            $generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
916
-        }
917
-
918
-        if (! $generated_queue instanceof EE_Messages_Queue) {
919
-            EE_Error::add_error(
920
-                __('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
921
-                    'event_espresso'),
922
-                __FILE__, __FUNCTION__, __LINE__
923
-            );
924
-        }
925
-        return $generated_queue;
926
-    }
927
-
928
-
929
-    /**
930
-     * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
931
-     * EEM_Message::status_idle
932
-     *
933
-     * @since 4.9.0
934
-     * @param $message_ids
935
-     * @return bool | EE_Messages_Queue  false if no messages sent.
936
-     */
937
-    public static function send_now($message_ids)
938
-    {
939
-        self::_load_controller();
940
-        $messages   = EEM_Message::instance()->get_all(
941
-            array(
942
-                0 => array(
943
-                    'MSG_ID' => array('IN', $message_ids),
944
-                    'STS_ID' => array(
945
-                        'IN',
946
-                        array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
947
-                    ),
948
-                ),
949
-            )
950
-        );
951
-        $sent_queue = false;
952
-        if ($messages) {
953
-            $sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
954
-        }
955
-
956
-        if (! $sent_queue instanceof EE_Messages_Queue) {
957
-            EE_Error::add_error(
958
-                __('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
959
-                    'event_espresso'),
960
-                __FILE__, __FUNCTION__, __LINE__
961
-            );
962
-        } else {
963
-            //can count how many sent by using the messages in the queue
964
-            $sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
965
-            if ($sent_count > 0) {
966
-                EE_Error::add_success(
967
-                    sprintf(
968
-                        _n(
969
-                            'There was %d message successfully sent.',
970
-                            'There were %d messages successfully sent.',
971
-                            $sent_count,
972
-                            'event_espresso'
973
-                        ),
974
-                        $sent_count
975
-                    )
976
-                );
977
-            } else {
978
-                EE_Error::overwrite_errors();
979
-                EE_Error::add_error(
980
-                    __('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
201
+				exit;
202
+			}
203
+		}
204
+		return;
205
+	}
206
+
207
+
208
+	/**
209
+	 *  This runs when the msg_url_trigger route has initiated.
210
+	 *
211
+	 * @since 4.5.0
212
+	 * @param WP $WP
213
+	 * @throws EE_Error
214
+	 * @return    void
215
+	 */
216
+	public function run($WP)
217
+	{
218
+		//ensure controller is loaded
219
+		self::_load_controller();
220
+		// attempt to process message
221
+		try {
222
+			/** @type EE_Message_To_Generate_From_Request $message_to_generate */
223
+			$message_to_generate = EE_Registry::instance()->load_lib('Message_To_Generate_From_Request');
224
+			self::$_MSG_PROCESSOR->generate_and_send_now($message_to_generate);
225
+		} catch (EE_Error $e) {
226
+			$error_msg = __('Please note that a system message failed to send due to a technical issue.',
227
+				'event_espresso');
228
+			// add specific message for developers if WP_DEBUG in on
229
+			$error_msg .= '||' . $e->getMessage();
230
+			EE_Error::add_error($error_msg, __FILE__, __FUNCTION__, __LINE__);
231
+		}
232
+	}
233
+
234
+
235
+	/**
236
+	 * This is triggered by the 'msg_cron_trigger' route.
237
+	 *
238
+	 * @param WP $WP
239
+	 */
240
+	public function execute_batch_request($WP)
241
+	{
242
+		$this->run_cron();
243
+		header('HTTP/1.1 200 OK');
244
+		exit();
245
+	}
246
+
247
+
248
+	/**
249
+	 * This gets executed on wp_cron jobs or when a batch request is initiated on its own separate non regular wp
250
+	 * request.
251
+	 */
252
+	public function run_cron()
253
+	{
254
+		self::_load_controller();
255
+		//get required vars
256
+		$cron_type     = EE_Registry::instance()->REQ->get('type');
257
+		$transient_key = EE_Registry::instance()->REQ->get('key');
258
+
259
+		//now let's verify transient, if not valid exit immediately
260
+		if (! get_transient($transient_key)) {
261
+			/**
262
+			 * trigger error so this gets in the error logs.  This is important because it happens on a non-user request.
263
+			 */
264
+			trigger_error(esc_attr__('Invalid Request (Transient does not exist)', 'event_espresso'));
265
+		}
266
+
267
+		//if made it here, lets' delete the transient to keep the db clean
268
+		delete_transient($transient_key);
269
+
270
+		if (apply_filters('FHEE__EED_Messages__run_cron__use_wp_cron', true)) {
271
+
272
+			$method = 'batch_' . $cron_type . '_from_queue';
273
+			if (method_exists(self::$_MSG_PROCESSOR, $method)) {
274
+				self::$_MSG_PROCESSOR->$method();
275
+			} else {
276
+				//no matching task
277
+				/**
278
+				 * trigger error so this gets in the error logs.  This is important because it happens on a non user request.
279
+				 */
280
+				trigger_error(esc_attr(sprintf(__('There is no task corresponding to this route %s', 'event_espresso'),
281
+					$cron_type)));
282
+			}
283
+		}
284
+
285
+		do_action('FHEE__EED_Messages__run_cron__end');
286
+	}
287
+
288
+
289
+	/**
290
+	 * This is used to retrieve the template pack for the given name.
291
+	 * Retrieved packs are cached on the static $_TMP_PACKS array.  If there is no class matching the given name then
292
+	 * the default template pack is returned.
293
+	 *
294
+	 * @deprecated 4.9.0  @see EEH_MSG_Template::get_template_pack()
295
+	 * @param string $template_pack_name This should correspond to the dbref of the template pack (which is also used
296
+	 *                                   in generating the Pack class name).
297
+	 * @return EE_Messages_Template_Pack
298
+	 */
299
+	public static function get_template_pack($template_pack_name)
300
+	{
301
+		EE_Registry::instance()->load_helper('MSG_Template');
302
+		return EEH_MSG_Template::get_template_pack($template_pack_name);
303
+	}
304
+
305
+
306
+	/**
307
+	 * Retrieves an array of all template packs.
308
+	 * Array is in the format array( 'dbref' => EE_Messages_Template_Pack )
309
+	 *
310
+	 * @deprecated 4.9.0  @see EEH_MSG_Template_Pack::get_template_pack_collection
311
+	 * @return EE_Messages_Template_Pack[]
312
+	 */
313
+	public static function get_template_packs()
314
+	{
315
+		EE_Registry::instance()->load_helper('MSG_Template');
316
+
317
+		//for backward compat, let's make sure this returns in the same format as originally.
318
+		$template_pack_collection = EEH_MSG_Template::get_template_pack_collection();
319
+		$template_pack_collection->rewind();
320
+		$template_packs = array();
321
+		while ($template_pack_collection->valid()) {
322
+			$template_packs[$template_pack_collection->current()->dbref] = $template_pack_collection->current();
323
+			$template_pack_collection->next();
324
+		}
325
+		return $template_packs;
326
+	}
327
+
328
+
329
+	/**
330
+	 * This simply makes sure the autoloaders are registered for the EE_messages system.
331
+	 *
332
+	 * @since 4.5.0
333
+	 * @return void
334
+	 */
335
+	public static function set_autoloaders()
336
+	{
337
+		if (empty(self::$_MSG_PATHS)) {
338
+			self::_set_messages_paths();
339
+			foreach (self::$_MSG_PATHS as $path) {
340
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($path);
341
+			}
342
+			// add aliases
343
+			EEH_Autoloader::add_alias('EE_messages', 'EE_messages');
344
+			EEH_Autoloader::add_alias('EE_messenger', 'EE_messenger');
345
+		}
346
+	}
347
+
348
+
349
+	/**
350
+	 * Take care of adding all the paths for the messages components to the $_MSG_PATHS property
351
+	 * for use by the Messages Autoloaders
352
+	 *
353
+	 * @since 4.5.0
354
+	 * @return void.
355
+	 */
356
+	protected static function _set_messages_paths()
357
+	{
358
+		$dir_ref = array(
359
+			'messages/message_type',
360
+			'messages/messenger',
361
+			'messages/defaults',
362
+			'messages/defaults/email',
363
+			'messages/data_class',
364
+			'messages/validators',
365
+			'messages/validators/email',
366
+			'messages/validators/html',
367
+			'shortcodes',
368
+		);
369
+		$paths   = array();
370
+		foreach ($dir_ref as $index => $dir) {
371
+			$paths[$index] = EE_LIBRARIES . $dir;
372
+		}
373
+		self::$_MSG_PATHS = apply_filters('FHEE__EED_Messages___set_messages_paths___MSG_PATHS', $paths);
374
+	}
375
+
376
+
377
+	/**
378
+	 * Takes care of loading dependencies
379
+	 *
380
+	 * @since 4.5.0
381
+	 * @return void
382
+	 */
383
+	protected static function _load_controller()
384
+	{
385
+		if (! self::$_MSG_PROCESSOR instanceof EE_Messages_Processor) {
386
+			EE_Registry::instance()->load_core('Request_Handler');
387
+			self::set_autoloaders();
388
+			self::$_EEMSG                    = EE_Registry::instance()->load_lib('messages');
389
+			self::$_MSG_PROCESSOR            = EE_Registry::instance()->load_lib('Messages_Processor');
390
+			self::$_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
391
+		}
392
+	}
393
+
394
+
395
+	/**
396
+	 * @param EE_Transaction $transaction
397
+	 */
398
+	public static function payment_reminder(EE_Transaction $transaction)
399
+	{
400
+		self::_load_controller();
401
+		$data = array($transaction, null);
402
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('payment_reminder', $data);
403
+	}
404
+
405
+
406
+	/**
407
+	 * Any messages triggers for after successful gateway payments should go in here.
408
+	 *
409
+	 * @param  EE_Transaction object
410
+	 * @param  EE_Payment     object
411
+	 * @return void
412
+	 */
413
+	public static function payment(EE_Transaction $transaction, EE_Payment $payment)
414
+	{
415
+		self::_load_controller();
416
+		$data = array($transaction, $payment);
417
+		EE_Registry::instance()->load_helper('MSG_Template');
418
+		$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
419
+		//if payment amount is less than 0 then switch to payment_refund message type.
420
+		$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
421
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
422
+	}
423
+
424
+
425
+	/**
426
+	 * @param EE_Transaction $transaction
427
+	 */
428
+	public static function cancelled_registration(EE_Transaction $transaction)
429
+	{
430
+		self::_load_controller();
431
+		$data = array($transaction, null);
432
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('cancelled_registration', $data);
433
+	}
434
+
435
+
436
+	/**
437
+	 * Trigger for Registration messages
438
+	 * Note that what registration message type is sent depends on what the reg status is for the registrations on the
439
+	 * incoming transaction.
440
+	 *
441
+	 * @param EE_Registration $registration
442
+	 * @param array           $extra_details
443
+	 * @return void
444
+	 */
445
+	public static function maybe_registration(EE_Registration $registration, $extra_details = array())
446
+	{
447
+
448
+		if (! self::_verify_registration_notification_send($registration, $extra_details)) {
449
+			//no messages please
450
+			return;
451
+		}
452
+
453
+
454
+		//get all registrations so we make sure we send messages for the right status.
455
+		$all_registrations = $registration->transaction()->registrations();
456
+
457
+		//cached array of statuses so we only trigger messages once per status.
458
+		$statuses_sent = array();
459
+		self::_load_controller();
460
+		$mtgs = array();
461
+
462
+		//loop through registrations and trigger messages once per status.
463
+		foreach ($all_registrations as $reg) {
464
+
465
+			//already triggered?
466
+			if (in_array($reg->status_ID(), $statuses_sent)) {
467
+				continue;
468
+			}
469
+
470
+			$message_type    = EEH_MSG_Template::convert_reg_status_to_message_type($reg->status_ID());
471
+			$mtgs            = array_merge(
472
+					$mtgs,
473
+					self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
474
+							$message_type,
475
+							array($registration->transaction(), null, $reg->status_ID())
476
+					)
477
+			);
478
+			$statuses_sent[] = $reg->status_ID();
479
+		}
480
+
481
+		if (count($statuses_sent) > 1) {
482
+			$mtgs = array_merge(
483
+				$mtgs,
484
+				self::$_MSG_PROCESSOR->setup_mtgs_for_all_active_messengers(
485
+					'registration_summary',
486
+					array($registration->transaction(), null)
487
+				)
488
+			);
489
+		}
490
+
491
+		//batch queue and initiate request
492
+		self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($mtgs);
493
+		self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
494
+	}
495
+
496
+
497
+	/**
498
+	 * This is a helper method used to very whether a registration notification should be sent or
499
+	 * not.  Prevents duplicate notifications going out for registration context notifications.
500
+	 *
501
+	 * @param EE_Registration $registration  [description]
502
+	 * @param array           $extra_details [description]
503
+	 * @return bool          true = send away, false = nope halt the presses.
504
+	 */
505
+	protected static function _verify_registration_notification_send(
506
+		EE_Registration $registration,
507
+		$extra_details = array()
508
+	) {
509
+		//self::log(
510
+		//	__CLASS__, __FUNCTION__, __LINE__,
511
+		//	$registration->transaction(),
512
+		//	array( '$extra_details' => $extra_details )
513
+		//);
514
+		// currently only using this to send messages for the primary registrant
515
+		if (! $registration->is_primary_registrant()) {
516
+			return false;
517
+		}
518
+		// first we check if we're in admin and not doing front ajax
519
+		if (is_admin() && ! EE_FRONT_AJAX) {
520
+			//make sure appropriate admin params are set for sending messages
521
+			if (empty($_REQUEST['txn_reg_status_change']['send_notifications']) || ! absint($_REQUEST['txn_reg_status_change']['send_notifications'])) {
522
+				//no messages sent please.
523
+				return false;
524
+			}
525
+		} else {
526
+			// frontend request (either regular or via AJAX)
527
+			// TXN is NOT finalized ?
528
+			if (! isset($extra_details['finalized']) || $extra_details['finalized'] === false) {
529
+				return false;
530
+			}
531
+			// return visit but nothing changed ???
532
+			if (
533
+				isset($extra_details['revisit'], $extra_details['status_updates']) &&
534
+				$extra_details['revisit'] && ! $extra_details['status_updates']
535
+			) {
536
+				return false;
537
+			}
538
+			// NOT sending messages && reg status is something other than "Not-Approved"
539
+			if (
540
+				! apply_filters('FHEE__EED_Messages___maybe_registration__deliver_notifications', false) &&
541
+				$registration->status_ID() !== EEM_Registration::status_id_not_approved
542
+			) {
543
+				return false;
544
+			}
545
+		}
546
+		// release the kraken
547
+		return true;
548
+	}
549
+
550
+
551
+	/**
552
+	 * Simply returns an array indexed by Registration Status ID and the related message_type name associated with that
553
+	 * status id.
554
+	 *
555
+	 * @deprecated 4.9.0  Use EEH_MSG_Template::reg_status_to_message_type_array()
556
+	 *                    or EEH_MSG_Template::convert_reg_status_to_message_type
557
+	 * @param string $reg_status
558
+	 * @return array
559
+	 */
560
+	protected static function _get_reg_status_array($reg_status = '')
561
+	{
562
+		EE_Registry::instance()->load_helper('MSG_Template');
563
+		return EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
564
+			? EEH_MSG_Template::convert_reg_status_to_message_type($reg_status)
565
+			: EEH_MSG_Template::reg_status_to_message_type_array();
566
+	}
567
+
568
+
569
+	/**
570
+	 * Simply returns the payment message type for the given payment status.
571
+	 *
572
+	 * @deprecated 4.9.0 Use EEH_MSG_Template::payment_status_to_message_type_array
573
+	 *                   or EEH_MSG_Template::convert_payment_status_to_message_type
574
+	 * @param string $payment_status The payment status being matched.
575
+	 * @return string|bool The payment message type slug matching the status or false if no match.
576
+	 */
577
+	protected static function _get_payment_message_type($payment_status)
578
+	{
579
+		EE_Registry::instance()->load_helper('MSG_Template');
580
+		return EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
581
+			? EEH_MSG_Template::convert_payment_status_to_message_type($payment_status)
582
+			: false;
583
+	}
584
+
585
+
586
+	/**
587
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
588
+	 *
589
+	 * @access public
590
+	 * @param array $req_data This is the $_POST & $_GET data sent from EE_Admin Pages
591
+	 * @return bool          success/fail
592
+	 */
593
+	public static function process_resend($req_data)
594
+	{
595
+		self::_load_controller();
596
+
597
+		//if $msgID in this request then skip to the new resend_message
598
+		if (EE_Registry::instance()->REQ->get('MSG_ID')) {
599
+			return self::resend_message();
600
+		}
601
+
602
+		//make sure any incoming request data is set on the REQ so that it gets picked up later.
603
+		$req_data = (array)$req_data;
604
+		foreach ($req_data as $request_key => $request_value) {
605
+			EE_Registry::instance()->REQ->set($request_key, $request_value);
606
+		}
607
+
608
+		if (! $messages_to_send = self::$_MSG_PROCESSOR->setup_messages_to_generate_from_registration_ids_in_request()) {
609
+			return false;
610
+		}
611
+
612
+		try {
613
+			self::$_MSG_PROCESSOR->batch_queue_for_generation_and_persist($messages_to_send);
614
+			self::$_MSG_PROCESSOR->get_queue()->initiate_request_by_priority();
615
+		} catch (EE_Error $e) {
616
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
617
+			return false;
618
+		}
619
+		EE_Error::add_success(
620
+			__('Messages have been successfully queued for generation and sending.', 'event_espresso')
621
+		);
622
+		return true; //everything got queued.
623
+	}
624
+
625
+
626
+	/**
627
+	 * Message triggers for a resending already sent message(s) (via EE_Message list table)
628
+	 *
629
+	 * @return bool
630
+	 */
631
+	public static function resend_message()
632
+	{
633
+		self::_load_controller();
634
+
635
+		$msgID = EE_Registry::instance()->REQ->get('MSG_ID');
636
+		if (! $msgID) {
637
+			EE_Error::add_error(__('Something went wrong because there is no "MSG_ID" value in the request',
638
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
639
+			return false;
640
+		}
641
+
642
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send((array)$msgID);
643
+
644
+		//setup success message.
645
+		$count_ready_for_resend = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
646
+		EE_Error::add_success(sprintf(
647
+			_n(
648
+				'There was %d message queued for resending.',
649
+				'There were %d messages queued for resending.',
650
+				$count_ready_for_resend,
651
+				'event_espresso'
652
+			),
653
+			$count_ready_for_resend
654
+		));
655
+		return true;
656
+	}
657
+
658
+
659
+	/**
660
+	 * Message triggers for manual payment applied by admin
661
+	 *
662
+	 * @param  EE_Payment $payment EE_payment object
663
+	 * @return bool              success/fail
664
+	 */
665
+	public static function process_admin_payment(EE_Payment $payment)
666
+	{
667
+		EE_Registry::instance()->load_helper('MSG_Template');
668
+		//we need to get the transaction object
669
+		$transaction = $payment->transaction();
670
+		if ($transaction instanceof EE_Transaction) {
671
+			$data         = array($transaction, $payment);
672
+			$message_type = EEH_MSG_Template::convert_payment_status_to_message_type($payment->STS_ID());
673
+
674
+			//if payment amount is less than 0 then switch to payment_refund message type.
675
+			$message_type = $payment->amount() < 0 ? 'payment_refund' : $message_type;
676
+
677
+			//if payment_refund is selected, but the status is NOT accepted.  Then change message type to false so NO message notification goes out.
678
+			$message_type = $message_type == 'payment_refund' && $payment->STS_ID() != EEM_Payment::status_id_approved ? false : $message_type;
679
+
680
+			self::_load_controller();
681
+
682
+			self::$_MSG_PROCESSOR->generate_for_all_active_messengers($message_type, $data);
683
+
684
+			//get count of queued for generation
685
+			$count_to_generate = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(array(
686
+				EEM_Message::status_incomplete,
687
+				EEM_Message::status_idle,
688
+			));
689
+
690
+			if ($count_to_generate > 0 && self::$_MSG_PROCESSOR->get_queue()->get_message_repository()->count() !== 0) {
691
+				add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
692
+				return true;
693
+			} else {
694
+				$count_failed = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::instance()->stati_indicating_failed_sending());
695
+				/**
696
+				 * Verify that there are actually errors.  If not then we return a success message because the queue might have been emptied due to successful
697
+				 * IMMEDIATE generation.
698
+				 */
699
+				if ($count_failed > 0) {
700
+					EE_Error::add_error(sprintf(
701
+						_n(
702
+							'The payment notification generation failed.',
703
+							'%d payment notifications failed being sent.',
704
+							$count_failed,
705
+							'event_espresso'
706
+						),
707
+						$count_failed
708
+					), __FILE__, __FUNCTION__, __LINE__);
709
+
710
+					return false;
711
+				} else {
712
+					add_filter('FHEE__EE_Admin_Page___process_admin_payment_notification__success', '__return_true');
713
+					return true;
714
+				}
715
+			}
716
+		} else {
717
+			EE_Error::add_error(
718
+				'Unable to generate the payment notification because the given value for the transaction is invalid.',
719
+				'event_espresso'
720
+			);
721
+			return false;
722
+		}
723
+	}
724
+
725
+
726
+	/**
727
+	 * Callback for AHEE__Extend_Registrations_Admin_Page___newsletter_selected_send_with_registrations trigger
728
+	 *
729
+	 * @since   4.3.0
730
+	 * @param  EE_Registration[] $registrations an array of EE_Registration objects
731
+	 * @param  int               $grp_id        a specific message template group id.
732
+	 * @return void
733
+	 */
734
+	public static function send_newsletter_message($registrations, $grp_id)
735
+	{
736
+		//make sure mtp is id and set it in the EE_Request Handler later messages setup.
737
+		EE_Registry::instance()->REQ->set('GRP_ID', (int)$grp_id);
738
+		self::_load_controller();
739
+		self::$_MSG_PROCESSOR->generate_for_all_active_messengers('newsletter', $registrations);
740
+	}
741
+
742
+
743
+	/**
744
+	 * Callback for FHEE__EE_Registration__invoice_url__invoice_url or FHEE__EE_Registration__receipt_url__receipt_url
745
+	 *
746
+	 * @since   4.3.0
747
+	 * @param    string          $registration_message_trigger_url
748
+	 * @param    EE_Registration $registration
749
+	 * @param string             $messenger
750
+	 * @param string             $message_type
751
+	 * @return    string
752
+	 */
753
+	public static function registration_message_trigger_url(
754
+		$registration_message_trigger_url,
755
+		EE_Registration $registration,
756
+		$messenger = 'html',
757
+		$message_type = 'invoice'
758
+	) {
759
+		// whitelist $messenger
760
+		switch ($messenger) {
761
+			case 'pdf' :
762
+				$sending_messenger    = 'pdf';
763
+				$generating_messenger = 'html';
764
+				break;
765
+			case 'html' :
766
+			default :
767
+				$sending_messenger    = 'html';
768
+				$generating_messenger = 'html';
769
+				break;
770
+		}
771
+		// whitelist $message_type
772
+		switch ($message_type) {
773
+			case 'receipt' :
774
+				$message_type = 'receipt';
775
+				break;
776
+			case 'invoice' :
777
+			default :
778
+				$message_type = 'invoice';
779
+				break;
780
+		}
781
+		// verify that both the messenger AND the message type are active
782
+		if (EEH_MSG_Template::is_messenger_active($sending_messenger) && EEH_MSG_Template::is_mt_active($message_type)) {
783
+			//need to get the correct message template group for this (i.e. is there a custom invoice for the event this registration is registered for?)
784
+			$template_query_params = array(
785
+				'MTP_is_active'    => true,
786
+				'MTP_messenger'    => $generating_messenger,
787
+				'MTP_message_type' => $message_type,
788
+				'Event.EVT_ID'     => $registration->event_ID(),
789
+			);
790
+			//get the message template group.
791
+			$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
792
+			//if we don't have an EE_Message_Template_Group then return
793
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
794
+				// remove EVT_ID from query params so that global templates get picked up
795
+				unset($template_query_params['Event.EVT_ID']);
796
+				//get global template as the fallback
797
+				$msg_template_group = EEM_Message_Template_Group::instance()->get_one(array($template_query_params));
798
+			}
799
+			//if we don't have an EE_Message_Template_Group then return
800
+			if (! $msg_template_group instanceof EE_Message_Template_Group) {
801
+				return '';
802
+			}
803
+			// generate the URL
804
+			$registration_message_trigger_url = EEH_MSG_Template::generate_url_trigger(
805
+				$sending_messenger,
806
+				$generating_messenger,
807
+				'purchaser',
808
+				$message_type,
809
+				$registration,
810
+				$msg_template_group->ID(),
811
+				$registration->transaction_ID()
812
+			);
813
+
814
+		}
815
+		return $registration_message_trigger_url;
816
+	}
817
+
818
+
819
+	/**
820
+	 * Use to generate and return a message preview!
821
+	 *
822
+	 * @param  string $type      This should correspond with a valid message type
823
+	 * @param  string $context   This should correspond with a valid context for the message type
824
+	 * @param  string $messenger This should correspond with a valid messenger.
825
+	 * @param bool    $send      true we will do a test send using the messenger delivery, false we just do a regular
826
+	 *                           preview
827
+	 * @return bool|string The body of the message or if send is requested, sends.
828
+	 * @throws EE_Error
829
+	 */
830
+	public static function preview_message($type, $context, $messenger, $send = false)
831
+	{
832
+		self::_load_controller();
833
+		$mtg                     = new EE_Message_To_Generate(
834
+			$messenger,
835
+			$type,
836
+			array(),
837
+			$context,
838
+			true
839
+		);
840
+		$generated_preview_queue = self::$_MSG_PROCESSOR->generate_for_preview($mtg, $send);
841
+		if ($generated_preview_queue instanceof EE_Messages_Queue) {
842
+			//loop through all content for the preview and remove any persisted records.
843
+			$content = '';
844
+			foreach ($generated_preview_queue->get_message_repository() as $message) {
845
+				$content = $message->content();
846
+				if ($message->ID() > 0 && $message->STS_ID() !== EEM_Message::status_failed) {
847
+					$message->delete();
848
+				}
849
+			}
850
+			return $content;
851
+		} else {
852
+			return $generated_preview_queue;
853
+		}
854
+	}
855
+
856
+
857
+	/**
858
+	 * This is a method that allows for sending a message using a messenger matching the string given and the provided
859
+	 * EE_Message_Queue object.  The EE_Message_Queue object is used to create a single aggregate EE_Message via the
860
+	 * content found in the EE_Message objects in the queue.
861
+	 *
862
+	 * @since 4.9.0
863
+	 * @param string            $messenger            a string matching a valid active messenger in the system
864
+	 * @param string            $message_type         Although it seems contrary to the name of the method, a message
865
+	 *                                                type name is still required to send along the message type to the
866
+	 *                                                messenger because this is used for determining what specific
867
+	 *                                                variations might be loaded for the generated message.
868
+	 * @param EE_Messages_Queue $queue
869
+	 * @param string            $custom_subject       Can be used to set what the custom subject string will be on the
870
+	 *                                                aggregate EE_Message object.
871
+	 * @return bool          success or fail.
872
+	 */
873
+	public static function send_message_with_messenger_only(
874
+		$messenger,
875
+		$message_type,
876
+		EE_Messages_Queue $queue,
877
+		$custom_subject = ''
878
+	) {
879
+		self::_load_controller();
880
+		/** @type EE_Message_To_Generate_From_Queue $message_to_generate */
881
+		$message_to_generate = EE_Registry::instance()->load_lib(
882
+			'Message_To_Generate_From_Queue',
883
+			array(
884
+				$messenger,
885
+				$message_type,
886
+				$queue,
887
+				$custom_subject,
888
+			)
889
+		);
890
+		return self::$_MSG_PROCESSOR->queue_for_sending($message_to_generate);
891
+	}
892
+
893
+
894
+	/**
895
+	 * Generates Messages immediately for EE_Message IDs (but only for the correct status for generation)
896
+	 *
897
+	 * @since 4.9.0
898
+	 * @param array $message_ids An array of message ids
899
+	 * @return bool | EE_Messages_Queue     false if nothing was generated, EE_Messages_Queue containing generated
900
+	 *              messages.
901
+	 */
902
+	public static function generate_now($message_ids)
903
+	{
904
+		self::_load_controller();
905
+		$messages        = EEM_Message::instance()->get_all(
906
+			array(
907
+				0 => array(
908
+					'MSG_ID' => array('IN', $message_ids),
909
+					'STS_ID' => EEM_Message::status_incomplete,
910
+				),
911
+			)
912
+		);
913
+		$generated_queue = false;
914
+		if ($messages) {
915
+			$generated_queue = self::$_MSG_PROCESSOR->batch_generate_from_queue($messages);
916
+		}
917
+
918
+		if (! $generated_queue instanceof EE_Messages_Queue) {
919
+			EE_Error::add_error(
920
+				__('The messages were not generated. This could mean there is already a batch being generated on a separate request, or because the selected messages are not ready for generation. Please wait a minute or two and try again.',
921
+					'event_espresso'),
922
+				__FILE__, __FUNCTION__, __LINE__
923
+			);
924
+		}
925
+		return $generated_queue;
926
+	}
927
+
928
+
929
+	/**
930
+	 * Sends messages immediately for the incoming message_ids that have the status of EEM_Message::status_resend or,
931
+	 * EEM_Message::status_idle
932
+	 *
933
+	 * @since 4.9.0
934
+	 * @param $message_ids
935
+	 * @return bool | EE_Messages_Queue  false if no messages sent.
936
+	 */
937
+	public static function send_now($message_ids)
938
+	{
939
+		self::_load_controller();
940
+		$messages   = EEM_Message::instance()->get_all(
941
+			array(
942
+				0 => array(
943
+					'MSG_ID' => array('IN', $message_ids),
944
+					'STS_ID' => array(
945
+						'IN',
946
+						array(EEM_Message::status_idle, EEM_Message::status_resend, EEM_Message::status_retry),
947
+					),
948
+				),
949
+			)
950
+		);
951
+		$sent_queue = false;
952
+		if ($messages) {
953
+			$sent_queue = self::$_MSG_PROCESSOR->batch_send_from_queue($messages);
954
+		}
955
+
956
+		if (! $sent_queue instanceof EE_Messages_Queue) {
957
+			EE_Error::add_error(
958
+				__('The messages were not sent. This could mean there is already a batch being sent on a separate request, or because the selected messages are not sendable. Please wait a minute or two and try again.',
959
+					'event_espresso'),
960
+				__FILE__, __FUNCTION__, __LINE__
961
+			);
962
+		} else {
963
+			//can count how many sent by using the messages in the queue
964
+			$sent_count = $sent_queue->count_STS_in_queue(EEM_Message::instance()->stati_indicating_sent());
965
+			if ($sent_count > 0) {
966
+				EE_Error::add_success(
967
+					sprintf(
968
+						_n(
969
+							'There was %d message successfully sent.',
970
+							'There were %d messages successfully sent.',
971
+							$sent_count,
972
+							'event_espresso'
973
+						),
974
+						$sent_count
975
+					)
976
+				);
977
+			} else {
978
+				EE_Error::overwrite_errors();
979
+				EE_Error::add_error(
980
+					__('No message was sent because of problems with sending. Either all the messages you selected were not a sendable message, they were ALREADY sent on a different scheduled task, or there was an error.
981 981
 					If there was an error, you can look at the messages in the message activity list table for any error messages.',
982
-                        'event_espresso'),
983
-                    __FILE__, __FUNCTION__, __LINE__
984
-                );
985
-            }
986
-        }
987
-        return $sent_queue;
988
-    }
989
-
990
-
991
-    /**
992
-     * This will queue the incoming message ids for resending.
993
-     * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
994
-     *
995
-     * @since 4.9.0
996
-     * @param array $message_ids An array of EE_Message IDs
997
-     * @return bool  true means messages were successfully queued for resending, false means none were queued for
998
-     *               resending.
999
-     */
1000
-    public static function queue_for_resending($message_ids)
1001
-    {
1002
-        self::_load_controller();
1003
-        self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1004
-
1005
-        //get queue and count
1006
-        $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1007
-
1008
-        if (
1009
-            $queue_count > 0
1010
-        ) {
1011
-            EE_Error::add_success(
1012
-                sprintf(
1013
-                    _n(
1014
-                        '%d message successfully queued for resending.',
1015
-                        '%d messages successfully queued for resending.',
1016
-                        $queue_count,
1017
-                        'event_espresso'
1018
-                    ),
1019
-                    $queue_count
1020
-                )
1021
-            );
1022
-            /**
1023
-             * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1024
-             */
1025
-        } elseif (
1026
-            apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1027
-            || EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1028
-        ) {
1029
-            $queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1030
-            if ($queue_count > 0) {
1031
-                EE_Error::add_success(
1032
-                    sprintf(
1033
-                        _n(
1034
-                            '%d message successfully sent.',
1035
-                            '%d messages successfully sent.',
1036
-                            $queue_count,
1037
-                            'event_espresso'
1038
-                        ),
1039
-                        $queue_count
1040
-                    )
1041
-                );
1042
-            } else {
1043
-                EE_Error::add_error(
1044
-                    __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1045
-                        'event_espresso'),
1046
-                    __FILE__, __FUNCTION__, __LINE__
1047
-                );
1048
-            }
1049
-        } else {
1050
-            EE_Error::add_error(
1051
-                __('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1052
-                    'event_espresso'),
1053
-                __FILE__, __FUNCTION__, __LINE__
1054
-            );
1055
-        }
1056
-        return (bool)$queue_count;
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * debug
1062
-     *
1063
-     * @param string          $class
1064
-     * @param string          $func
1065
-     * @param string          $line
1066
-     * @param \EE_Transaction $transaction
1067
-     * @param array           $info
1068
-     * @param bool            $display_request
1069
-     */
1070
-    protected static function log(
1071
-        $class = '',
1072
-        $func = '',
1073
-        $line = '',
1074
-        EE_Transaction $transaction,
1075
-        $info = array(),
1076
-        $display_request = false
1077
-    ) {
1078
-        if (WP_DEBUG && false) {
1079
-            if ($transaction instanceof EE_Transaction) {
1080
-                // don't serialize objects
1081
-                $info                  = EEH_Debug_Tools::strip_objects($info);
1082
-                $info['TXN_status']    = $transaction->status_ID();
1083
-                $info['TXN_reg_steps'] = $transaction->reg_steps();
1084
-                if ($transaction->ID()) {
1085
-                    $index = 'EE_Transaction: ' . $transaction->ID();
1086
-                    EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1087
-                }
1088
-            }
1089
-        }
1090
-
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     *  Resets all the static properties in this class when called.
1096
-     */
1097
-    public static function reset()
1098
-    {
1099
-        self::$_EEMSG                    = null;
1100
-        self::$_message_resource_manager = null;
1101
-        self::$_MSG_PROCESSOR            = null;
1102
-        self::$_MSG_PATHS                = null;
1103
-        self::$_TMP_PACKS                = array();
1104
-    }
982
+						'event_espresso'),
983
+					__FILE__, __FUNCTION__, __LINE__
984
+				);
985
+			}
986
+		}
987
+		return $sent_queue;
988
+	}
989
+
990
+
991
+	/**
992
+	 * This will queue the incoming message ids for resending.
993
+	 * Note, only message_ids corresponding to messages with the status of EEM_Message::sent will be queued.
994
+	 *
995
+	 * @since 4.9.0
996
+	 * @param array $message_ids An array of EE_Message IDs
997
+	 * @return bool  true means messages were successfully queued for resending, false means none were queued for
998
+	 *               resending.
999
+	 */
1000
+	public static function queue_for_resending($message_ids)
1001
+	{
1002
+		self::_load_controller();
1003
+		self::$_MSG_PROCESSOR->setup_messages_from_ids_and_send($message_ids);
1004
+
1005
+		//get queue and count
1006
+		$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_resend);
1007
+
1008
+		if (
1009
+			$queue_count > 0
1010
+		) {
1011
+			EE_Error::add_success(
1012
+				sprintf(
1013
+					_n(
1014
+						'%d message successfully queued for resending.',
1015
+						'%d messages successfully queued for resending.',
1016
+						$queue_count,
1017
+						'event_espresso'
1018
+					),
1019
+					$queue_count
1020
+				)
1021
+			);
1022
+			/**
1023
+			 * @see filter usage in EE_Messages_Queue::initiate_request_by_priority
1024
+			 */
1025
+		} elseif (
1026
+			apply_filters('FHEE__EE_Messages_Processor__initiate_request_by_priority__do_immediate_processing', true)
1027
+			|| EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request
1028
+		) {
1029
+			$queue_count = self::$_MSG_PROCESSOR->get_queue()->count_STS_in_queue(EEM_Message::status_sent);
1030
+			if ($queue_count > 0) {
1031
+				EE_Error::add_success(
1032
+					sprintf(
1033
+						_n(
1034
+							'%d message successfully sent.',
1035
+							'%d messages successfully sent.',
1036
+							$queue_count,
1037
+							'event_espresso'
1038
+						),
1039
+						$queue_count
1040
+					)
1041
+				);
1042
+			} else {
1043
+				EE_Error::add_error(
1044
+					__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1045
+						'event_espresso'),
1046
+					__FILE__, __FUNCTION__, __LINE__
1047
+				);
1048
+			}
1049
+		} else {
1050
+			EE_Error::add_error(
1051
+				__('No messages were queued for resending. This usually only happens when all the messages flagged for resending are not a status that can be resent.',
1052
+					'event_espresso'),
1053
+				__FILE__, __FUNCTION__, __LINE__
1054
+			);
1055
+		}
1056
+		return (bool)$queue_count;
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * debug
1062
+	 *
1063
+	 * @param string          $class
1064
+	 * @param string          $func
1065
+	 * @param string          $line
1066
+	 * @param \EE_Transaction $transaction
1067
+	 * @param array           $info
1068
+	 * @param bool            $display_request
1069
+	 */
1070
+	protected static function log(
1071
+		$class = '',
1072
+		$func = '',
1073
+		$line = '',
1074
+		EE_Transaction $transaction,
1075
+		$info = array(),
1076
+		$display_request = false
1077
+	) {
1078
+		if (WP_DEBUG && false) {
1079
+			if ($transaction instanceof EE_Transaction) {
1080
+				// don't serialize objects
1081
+				$info                  = EEH_Debug_Tools::strip_objects($info);
1082
+				$info['TXN_status']    = $transaction->status_ID();
1083
+				$info['TXN_reg_steps'] = $transaction->reg_steps();
1084
+				if ($transaction->ID()) {
1085
+					$index = 'EE_Transaction: ' . $transaction->ID();
1086
+					EEH_Debug_Tools::log($class, $func, $line, $info, $display_request, $index);
1087
+				}
1088
+			}
1089
+		}
1090
+
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 *  Resets all the static properties in this class when called.
1096
+	 */
1097
+	public static function reset()
1098
+	{
1099
+		self::$_EEMSG                    = null;
1100
+		self::$_message_resource_manager = null;
1101
+		self::$_MSG_PROCESSOR            = null;
1102
+		self::$_MSG_PATHS                = null;
1103
+		self::$_TMP_PACKS                = array();
1104
+	}
1105 1105
 
1106 1106
 }
1107 1107
 // End of file EED_Messages.module.php
Please login to merge, or discard this patch.
acceptance_tests/Page/EventsAdmin.php 1 patch
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -14,231 +14,231 @@
 block discarded – undo
14 14
 class EventsAdmin extends CoreAdmin
15 15
 {
16 16
 
17
-    /**
18
-     * Selector for the Add new Event button in the admin.
19
-     * @var string
20
-     */
21
-    const ADD_NEW_EVENT_BUTTON_SELECTOR = '#add-new-event';
22
-
23
-
24
-    /**
25
-     * Selector for the Event Title field in the event editor
26
-     * @var string
27
-     */
28
-    const EVENT_EDITOR_TITLE_FIELD_SELECTOR = "//input[@id='title']";
29
-
30
-    /**
31
-     * Selector for the publish submit button in the event editor.
32
-     * @var string
33
-     */
34
-    const EVENT_EDITOR_PUBLISH_BUTTON_SELECTOR = "#publish";
35
-
36
-
37
-    /**
38
-     * Selector for the save button in the event editor
39
-     */
40
-    const EVENT_EDITOR_SAVE_BUTTON_SELECTOR = "#save-post";
41
-
42
-
43
-    /**
44
-     * @var string
45
-     */
46
-    const EVENT_EDITOR_DEFAULT_REGISTRATION_STATUS_FIELD_SELECTOR = '#EVT_default_registration_status';
17
+	/**
18
+	 * Selector for the Add new Event button in the admin.
19
+	 * @var string
20
+	 */
21
+	const ADD_NEW_EVENT_BUTTON_SELECTOR = '#add-new-event';
22
+
23
+
24
+	/**
25
+	 * Selector for the Event Title field in the event editor
26
+	 * @var string
27
+	 */
28
+	const EVENT_EDITOR_TITLE_FIELD_SELECTOR = "//input[@id='title']";
29
+
30
+	/**
31
+	 * Selector for the publish submit button in the event editor.
32
+	 * @var string
33
+	 */
34
+	const EVENT_EDITOR_PUBLISH_BUTTON_SELECTOR = "#publish";
35
+
36
+
37
+	/**
38
+	 * Selector for the save button in the event editor
39
+	 */
40
+	const EVENT_EDITOR_SAVE_BUTTON_SELECTOR = "#save-post";
41
+
42
+
43
+	/**
44
+	 * @var string
45
+	 */
46
+	const EVENT_EDITOR_DEFAULT_REGISTRATION_STATUS_FIELD_SELECTOR = '#EVT_default_registration_status';
47 47
 
48
-    /**
49
-     * Selector for the view link after publishing an event.
50
-     * @var string
51
-     */
52
-    const EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR = "//span[@id='sample-permalink']/a";
48
+	/**
49
+	 * Selector for the view link after publishing an event.
50
+	 * @var string
51
+	 */
52
+	const EVENT_EDITOR_VIEW_LINK_AFTER_PUBLISH_SELECTOR = "//span[@id='sample-permalink']/a";
53 53
 
54 54
 
55
-    /**
56
-     * Selector for the ID of the event in the event editor
57
-     * @var string
58
-     */
59
-    const EVENT_EDITOR_EVT_ID_SELECTOR = "//input[@id='post_ID']";
55
+	/**
56
+	 * Selector for the ID of the event in the event editor
57
+	 * @var string
58
+	 */
59
+	const EVENT_EDITOR_EVT_ID_SELECTOR = "//input[@id='post_ID']";
60 60
 
61 61
 
62
-    /**
63
-     * Selector for the search input on the event list table page.
64
-     * @var string
65
-     */
66
-    const EVENT_LIST_TABLE_SEARCH_INPUT_SELECTOR = '#toplevel_page_espresso_events-search-input';
67
-
68
-
69
-
70
-
71
-    /**
72
-     * @param string $additional_params
73
-     * @return string
74
-     */
75
-    public static function defaultEventsListTableUrl($additional_params = '')
76
-    {
77
-        return self::adminUrl('espresso_events', 'default', $additional_params);
78
-    }
79
-
80
-
81
-    /**
82
-     * The selector for the DTTname field for the given row in the event editor.
83
-     * @param int $row_number
84
-     * @return string
85
-     */
86
-    public static function eventEditorDatetimeNameFieldSelector($row_number = 1)
87
-    {
88
-        return self::eventEditorDatetimeFieldSelectorForField('DTT_name', $row_number);
89
-    }
90
-
91
-
92
-    /**
93
-     * The selector for the DTT_EVT_start field for the given row in the event editor.d
94
-     * @param int $row_number
95
-     * @return string
96
-     */
97
-    public static function eventEditorDatetimeStartDateFieldSelector($row_number = 1)
98
-    {
99
-        return self::eventEditorDatetimeFieldSelectorForField('DTT_EVT_start', $row_number);
100
-    }
101
-
102
-
103
-    /**
104
-     * Wrapper for getting the selector for a given field and given row of a datetime in the event editor.
105
-     *
106
-     * @param string $field_name
107
-     * @param int    $row_number
108
-     * @return string
109
-     */
110
-    public static function eventEditorDatetimeFieldSelectorForField($field_name, $row_number = 1)
111
-    {
112
-        return "//input[@id='event-datetime-$field_name-$row_number']";
113
-    }
114
-
115
-
116
-    /**
117
-     * The selector for the TKT_name field for the given display row in the event editor.
118
-     * @param int $row_number
119
-     * @return string
120
-     */
121
-    public static function eventEditorTicketNameFieldSelector($row_number = 1)
122
-    {
123
-        return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_name', $row_number);
124
-    }
125
-
126
-
127
-    public static function eventEditorTicketPriceFieldSelector($row_number = 1)
128
-    {
129
-        return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_base_price', $row_number);
130
-    }
131
-
132
-
133
-    public static function eventEditorTicketAdvancedDetailsSelector($row_number = 1)
134
-    {
135
-        return "//tr[@id='display-ticketrow-$row_number']//span[contains(@class, 'gear-icon')]";
136
-    }
137
-
138
-
139
-    public static function eventEditorTicketAdvancedDetailsSubtotalSelector($row_number = 1)
140
-    {
141
-        return "//span[@id='price-total-amount-$row_number']";
142
-    }
143
-
144
-
145
-    public static function eventEditorTicketAdvancedDetailsTotalSelector($row_number = 1)
146
-    {
147
-        return "//span[@id='price-total-amount-$row_number']";
148
-    }
149
-
150
-
151
-    public static function eventEditorTicketTaxableCheckboxSelector($row_number = 1)
152
-    {
153
-        return "//input[@id='edit-ticket-TKT_taxable-$row_number']";
154
-    }
155
-
156
-
157
-    /**
158
-     * This returns the xpath locater for the Tax amount display container within the advanced settings view for the
159
-     * given ticket (row) and the given tax id (PRC_ID).
160
-     *
161
-     * @param int $tax_id     The PRC_ID for the tax you want the locater for.  Note, this defaults to the default tax
162
-     *                        setup on a fresh install.
163
-     * @param int $row_number What row representing the ticket you want the locator for.
164
-     * @return string
165
-     */
166
-    public static function eventEditorTicketTaxAmountDisplayForTaxIdAndTicketRowSelector($tax_id = 2, $row_number = 1)
167
-    {
168
-        return "//span[@id='TKT-tax-amount-display-$tax_id-$row_number']";
169
-    }
170
-
171
-
172
-    /**
173
-     * Wrapper for getting the selector for a given field and given display row of a ticket in the event editor.
174
-     * @param     $field_name
175
-     * @param int $row_number
176
-     * @return string
177
-     */
178
-    public static function eventEditorTicketFieldSelectorForFieldInDisplayRow($field_name, $row_number = 1)
179
-    {
180
-        return "//tr[@id='display-ticketrow-$row_number']//input[contains(@class, 'edit-ticket-$field_name')]";
181
-    }
182
-
183
-
184
-    /**
185
-     * Returns the selector for the event title edit link in the events list table for the given Event Title.
186
-     * @param string $event_title
187
-     * @return string
188
-     */
189
-    public static function eventListTableEventTitleEditLinkSelectorForTitle($event_title)
190
-    {
191
-        return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']";
192
-    }
193
-
194
-
195
-    /**
196
-     * Locator for for the ID column in the event list table for a given event title.
197
-     * @param string $event_title
198
-     * @return string
199
-     */
200
-    public static function eventListTableEventIdSelectorForTitle($event_title)
201
-    {
202
-        return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']"
203
-               . "//ancestor::tr/th[contains(@class, 'check-column')]/input";
204
-    }
205
-
206
-
207
-    /**
208
-     * Locator for the view link in the row of an event list table for the given event title.
209
-     * @param string $event_title
210
-     * @return string
211
-     */
212
-    public static function eventListTableEventTitleViewLinkSelectorForTitle($event_title)
213
-    {
214
-        return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']"
215
-               . "//ancestor::td//span[@class='view']/a";
216
-    }
217
-
218
-
219
-    /**
220
-     * Locator for the messenger tab in the Notifications metabox in the event editor.
221
-     * @param string $messenger_slug  The slug for the messenger (it's reference slug).
222
-     * @return string
223
-     */
224
-    public static function eventEditorNotificationsMetaBoxMessengerTabSelector($messenger_slug)
225
-    {
226
-        return "//div[@id='espresso_events_Messages_Hooks_Extend_messages_metabox_metabox']"
227
-               . "//a[@rel='ee-tab-$messenger_slug']";
228
-    }
229
-
230
-
231
-    /**
232
-     * Locator for the select input within the notifications metabox.
233
-     * Note, this assumes the tab content for the related messenger is already visible.
234
-     * @param string $message_type_label The message type label (visible string in the table) you want the selector for.
235
-     * @return string
236
-     */
237
-    public static function eventEditorNotificationsMetaBoxSelectSelectorForMessageType($message_type_label)
238
-    {
239
-        return "//div[@id='espresso_events_Messages_Hooks_Extend_messages_metabox_metabox']"
240
-               . "//table[@class='messages-custom-template-switcher']"
241
-               . "//tr/td[contains(.,'Registration Approved')]"
242
-               . "//ancestor::tr//select[contains(@class,'message-template-selector')]";
243
-    }
62
+	/**
63
+	 * Selector for the search input on the event list table page.
64
+	 * @var string
65
+	 */
66
+	const EVENT_LIST_TABLE_SEARCH_INPUT_SELECTOR = '#toplevel_page_espresso_events-search-input';
67
+
68
+
69
+
70
+
71
+	/**
72
+	 * @param string $additional_params
73
+	 * @return string
74
+	 */
75
+	public static function defaultEventsListTableUrl($additional_params = '')
76
+	{
77
+		return self::adminUrl('espresso_events', 'default', $additional_params);
78
+	}
79
+
80
+
81
+	/**
82
+	 * The selector for the DTTname field for the given row in the event editor.
83
+	 * @param int $row_number
84
+	 * @return string
85
+	 */
86
+	public static function eventEditorDatetimeNameFieldSelector($row_number = 1)
87
+	{
88
+		return self::eventEditorDatetimeFieldSelectorForField('DTT_name', $row_number);
89
+	}
90
+
91
+
92
+	/**
93
+	 * The selector for the DTT_EVT_start field for the given row in the event editor.d
94
+	 * @param int $row_number
95
+	 * @return string
96
+	 */
97
+	public static function eventEditorDatetimeStartDateFieldSelector($row_number = 1)
98
+	{
99
+		return self::eventEditorDatetimeFieldSelectorForField('DTT_EVT_start', $row_number);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Wrapper for getting the selector for a given field and given row of a datetime in the event editor.
105
+	 *
106
+	 * @param string $field_name
107
+	 * @param int    $row_number
108
+	 * @return string
109
+	 */
110
+	public static function eventEditorDatetimeFieldSelectorForField($field_name, $row_number = 1)
111
+	{
112
+		return "//input[@id='event-datetime-$field_name-$row_number']";
113
+	}
114
+
115
+
116
+	/**
117
+	 * The selector for the TKT_name field for the given display row in the event editor.
118
+	 * @param int $row_number
119
+	 * @return string
120
+	 */
121
+	public static function eventEditorTicketNameFieldSelector($row_number = 1)
122
+	{
123
+		return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_name', $row_number);
124
+	}
125
+
126
+
127
+	public static function eventEditorTicketPriceFieldSelector($row_number = 1)
128
+	{
129
+		return self::eventEditorTicketFieldSelectorForFieldInDisplayRow('TKT_base_price', $row_number);
130
+	}
131
+
132
+
133
+	public static function eventEditorTicketAdvancedDetailsSelector($row_number = 1)
134
+	{
135
+		return "//tr[@id='display-ticketrow-$row_number']//span[contains(@class, 'gear-icon')]";
136
+	}
137
+
138
+
139
+	public static function eventEditorTicketAdvancedDetailsSubtotalSelector($row_number = 1)
140
+	{
141
+		return "//span[@id='price-total-amount-$row_number']";
142
+	}
143
+
144
+
145
+	public static function eventEditorTicketAdvancedDetailsTotalSelector($row_number = 1)
146
+	{
147
+		return "//span[@id='price-total-amount-$row_number']";
148
+	}
149
+
150
+
151
+	public static function eventEditorTicketTaxableCheckboxSelector($row_number = 1)
152
+	{
153
+		return "//input[@id='edit-ticket-TKT_taxable-$row_number']";
154
+	}
155
+
156
+
157
+	/**
158
+	 * This returns the xpath locater for the Tax amount display container within the advanced settings view for the
159
+	 * given ticket (row) and the given tax id (PRC_ID).
160
+	 *
161
+	 * @param int $tax_id     The PRC_ID for the tax you want the locater for.  Note, this defaults to the default tax
162
+	 *                        setup on a fresh install.
163
+	 * @param int $row_number What row representing the ticket you want the locator for.
164
+	 * @return string
165
+	 */
166
+	public static function eventEditorTicketTaxAmountDisplayForTaxIdAndTicketRowSelector($tax_id = 2, $row_number = 1)
167
+	{
168
+		return "//span[@id='TKT-tax-amount-display-$tax_id-$row_number']";
169
+	}
170
+
171
+
172
+	/**
173
+	 * Wrapper for getting the selector for a given field and given display row of a ticket in the event editor.
174
+	 * @param     $field_name
175
+	 * @param int $row_number
176
+	 * @return string
177
+	 */
178
+	public static function eventEditorTicketFieldSelectorForFieldInDisplayRow($field_name, $row_number = 1)
179
+	{
180
+		return "//tr[@id='display-ticketrow-$row_number']//input[contains(@class, 'edit-ticket-$field_name')]";
181
+	}
182
+
183
+
184
+	/**
185
+	 * Returns the selector for the event title edit link in the events list table for the given Event Title.
186
+	 * @param string $event_title
187
+	 * @return string
188
+	 */
189
+	public static function eventListTableEventTitleEditLinkSelectorForTitle($event_title)
190
+	{
191
+		return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']";
192
+	}
193
+
194
+
195
+	/**
196
+	 * Locator for for the ID column in the event list table for a given event title.
197
+	 * @param string $event_title
198
+	 * @return string
199
+	 */
200
+	public static function eventListTableEventIdSelectorForTitle($event_title)
201
+	{
202
+		return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']"
203
+			   . "//ancestor::tr/th[contains(@class, 'check-column')]/input";
204
+	}
205
+
206
+
207
+	/**
208
+	 * Locator for the view link in the row of an event list table for the given event title.
209
+	 * @param string $event_title
210
+	 * @return string
211
+	 */
212
+	public static function eventListTableEventTitleViewLinkSelectorForTitle($event_title)
213
+	{
214
+		return "//td[contains(@class, 'column-name')]/strong/a[text()='$event_title']"
215
+			   . "//ancestor::td//span[@class='view']/a";
216
+	}
217
+
218
+
219
+	/**
220
+	 * Locator for the messenger tab in the Notifications metabox in the event editor.
221
+	 * @param string $messenger_slug  The slug for the messenger (it's reference slug).
222
+	 * @return string
223
+	 */
224
+	public static function eventEditorNotificationsMetaBoxMessengerTabSelector($messenger_slug)
225
+	{
226
+		return "//div[@id='espresso_events_Messages_Hooks_Extend_messages_metabox_metabox']"
227
+			   . "//a[@rel='ee-tab-$messenger_slug']";
228
+	}
229
+
230
+
231
+	/**
232
+	 * Locator for the select input within the notifications metabox.
233
+	 * Note, this assumes the tab content for the related messenger is already visible.
234
+	 * @param string $message_type_label The message type label (visible string in the table) you want the selector for.
235
+	 * @return string
236
+	 */
237
+	public static function eventEditorNotificationsMetaBoxSelectSelectorForMessageType($message_type_label)
238
+	{
239
+		return "//div[@id='espresso_events_Messages_Hooks_Extend_messages_metabox_metabox']"
240
+			   . "//table[@class='messages-custom-template-switcher']"
241
+			   . "//tr/td[contains(.,'Registration Approved')]"
242
+			   . "//ancestor::tr//select[contains(@class,'message-template-selector')]";
243
+	}
244 244
 }
Please login to merge, or discard this patch.
form_sections/strategies/layout/EE_Admin_Two_Column_Layout.strategy.php 2 patches
Indentation   +71 added lines, -71 removed lines patch added patch discarded remove patch
@@ -10,81 +10,81 @@
 block discarded – undo
10 10
 class EE_Admin_Two_Column_Layout extends EE_Two_Column_Layout
11 11
 {
12 12
 
13
-    /**
14
-     * Overriding the parent table layout to include <tbody> tags
15
-     *
16
-     * @param array $additional_args
17
-     * @return string
18
-     */
19
-    public function layout_form_begin($additional_args = array())
20
-    {
21
-        $this->_form_section->set_html_class('form-table');
22
-        return parent::layout_form_begin($additional_args);
23
-    }
13
+	/**
14
+	 * Overriding the parent table layout to include <tbody> tags
15
+	 *
16
+	 * @param array $additional_args
17
+	 * @return string
18
+	 */
19
+	public function layout_form_begin($additional_args = array())
20
+	{
21
+		$this->_form_section->set_html_class('form-table');
22
+		return parent::layout_form_begin($additional_args);
23
+	}
24 24
 
25 25
 
26 26
 
27
-    /**
28
-     * Lays out a row for the subsection
29
-     *
30
-     * @param EE_Form_Section_Proper $form_section
31
-     * @return string
32
-     */
33
-    public function layout_subsection($form_section)
34
-    {
35
-        if ($form_section instanceof EE_Form_Section_Proper) {
36
-            return EEH_HTML::no_row($form_section->get_html());
37
-        }
38
-        if ($form_section instanceof EE_Form_Section_HTML) {
39
-            return EEH_HTML::no_row($form_section->get_html());
40
-        }
41
-        return '';
42
-    }
27
+	/**
28
+	 * Lays out a row for the subsection
29
+	 *
30
+	 * @param EE_Form_Section_Proper $form_section
31
+	 * @return string
32
+	 */
33
+	public function layout_subsection($form_section)
34
+	{
35
+		if ($form_section instanceof EE_Form_Section_Proper) {
36
+			return EEH_HTML::no_row($form_section->get_html());
37
+		}
38
+		if ($form_section instanceof EE_Form_Section_HTML) {
39
+			return EEH_HTML::no_row($form_section->get_html());
40
+		}
41
+		return '';
42
+	}
43 43
 
44 44
 
45 45
 
46
-    /**
47
-     * Lays out the row for the input, including label and errors
48
-     *
49
-     * @param EE_Form_Input_Base $input
50
-     * @return string
51
-     * @throws EE_Error
52
-     */
53
-    public function layout_input($input)
54
-    {
55
-        if ($input->get_display_strategy() instanceof EE_Text_Area_Display_Strategy
56
-            || $input->get_display_strategy() instanceof EE_Text_Input_Display_Strategy
57
-            || $input->get_display_strategy() instanceof EE_Admin_File_Uploader_Display_Strategy
58
-        ) {
59
-            $input->set_html_class($input->html_class() . ' large-text');
60
-        }
61
-        if ($input instanceof EE_Text_Area_Input) {
62
-            $input->set_rows(4);
63
-            $input->set_cols(60);
64
-        }
65
-        $input_html = $input->get_html_for_input();
66
-        // maybe add errors and help text ?
67
-        $input_html .= $input->get_html_for_errors() !== ''
68
-            ? EEH_HTML::nl() . $input->get_html_for_errors()
69
-            : '';
70
-        $input_html .= $input->get_html_for_help() !== ''
71
-            ? EEH_HTML::nl() . $input->get_html_for_help()
72
-            : '';
73
-        //overriding parent to add wp admin specific things.
74
-        $html = '';
75
-        if ($input instanceof EE_Hidden_Input) {
76
-            $html .= EEH_HTML::no_row($input->get_html_for_input());
77
-        } else {
78
-            $html .= EEH_HTML::tr(
79
-                EEH_HTML::th(
80
-                    $input->get_html_for_label(),
81
-                    '',
82
-                    '',
83
-                    '',
84
-                    'scope="row"'
85
-                ) . EEH_HTML::td($input_html)
86
-            );
87
-        }
88
-        return $html;
89
-    }
46
+	/**
47
+	 * Lays out the row for the input, including label and errors
48
+	 *
49
+	 * @param EE_Form_Input_Base $input
50
+	 * @return string
51
+	 * @throws EE_Error
52
+	 */
53
+	public function layout_input($input)
54
+	{
55
+		if ($input->get_display_strategy() instanceof EE_Text_Area_Display_Strategy
56
+			|| $input->get_display_strategy() instanceof EE_Text_Input_Display_Strategy
57
+			|| $input->get_display_strategy() instanceof EE_Admin_File_Uploader_Display_Strategy
58
+		) {
59
+			$input->set_html_class($input->html_class() . ' large-text');
60
+		}
61
+		if ($input instanceof EE_Text_Area_Input) {
62
+			$input->set_rows(4);
63
+			$input->set_cols(60);
64
+		}
65
+		$input_html = $input->get_html_for_input();
66
+		// maybe add errors and help text ?
67
+		$input_html .= $input->get_html_for_errors() !== ''
68
+			? EEH_HTML::nl() . $input->get_html_for_errors()
69
+			: '';
70
+		$input_html .= $input->get_html_for_help() !== ''
71
+			? EEH_HTML::nl() . $input->get_html_for_help()
72
+			: '';
73
+		//overriding parent to add wp admin specific things.
74
+		$html = '';
75
+		if ($input instanceof EE_Hidden_Input) {
76
+			$html .= EEH_HTML::no_row($input->get_html_for_input());
77
+		} else {
78
+			$html .= EEH_HTML::tr(
79
+				EEH_HTML::th(
80
+					$input->get_html_for_label(),
81
+					'',
82
+					'',
83
+					'',
84
+					'scope="row"'
85
+				) . EEH_HTML::td($input_html)
86
+			);
87
+		}
88
+		return $html;
89
+	}
90 90
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
             || $input->get_display_strategy() instanceof EE_Text_Input_Display_Strategy
57 57
             || $input->get_display_strategy() instanceof EE_Admin_File_Uploader_Display_Strategy
58 58
         ) {
59
-            $input->set_html_class($input->html_class() . ' large-text');
59
+            $input->set_html_class($input->html_class().' large-text');
60 60
         }
61 61
         if ($input instanceof EE_Text_Area_Input) {
62 62
             $input->set_rows(4);
@@ -65,10 +65,10 @@  discard block
 block discarded – undo
65 65
         $input_html = $input->get_html_for_input();
66 66
         // maybe add errors and help text ?
67 67
         $input_html .= $input->get_html_for_errors() !== ''
68
-            ? EEH_HTML::nl() . $input->get_html_for_errors()
68
+            ? EEH_HTML::nl().$input->get_html_for_errors()
69 69
             : '';
70 70
         $input_html .= $input->get_html_for_help() !== ''
71
-            ? EEH_HTML::nl() . $input->get_html_for_help()
71
+            ? EEH_HTML::nl().$input->get_html_for_help()
72 72
             : '';
73 73
         //overriding parent to add wp admin specific things.
74 74
         $html = '';
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
                     '',
83 83
                     '',
84 84
                     'scope="row"'
85
-                ) . EEH_HTML::td($input_html)
85
+                ).EEH_HTML::td($input_html)
86 86
             );
87 87
         }
88 88
         return $html;
Please login to merge, or discard this patch.