Completed
Branch BUG/escape-localized-variables (d40cc7)
by
unknown
09:56 queued 08:24
created
admin/extend/transactions/Extend_Transactions_Admin_Page.core.php 2 patches
Indentation   +243 added lines, -243 removed lines patch added patch discarded remove patch
@@ -16,247 +16,247 @@
 block discarded – undo
16 16
 {
17 17
 
18 18
 
19
-    /**
20
-     * This is used to hold the reports template data which is setup early in the request.
21
-     *
22
-     * @type array
23
-     */
24
-    protected $_reports_template_data = array();
25
-
26
-    /**
27
-     * @Constructor
28
-     * @access public
29
-     *
30
-     * @param bool $routing
31
-     *
32
-     * @return \Extend_Transactions_Admin_Page
33
-     */
34
-    public function __construct($routing = true)
35
-    {
36
-        parent::__construct($routing);
37
-        define('TXN_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'transactions/templates/');
38
-        define('TXN_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'transactions/assets/');
39
-        define('TXN_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'transactions/assets/');
40
-    }
41
-
42
-
43
-    /**
44
-     *    _extend_page_config
45
-     *
46
-     * @access protected
47
-     * @return void
48
-     */
49
-    protected function _extend_page_config()
50
-    {
51
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'transactions';
52
-
53
-        $new_page_routes = array(
54
-            'reports' => array(
55
-                'func'       => '_transaction_reports',
56
-                'capability' => 'ee_read_transactions',
57
-            ),
58
-        );
59
-
60
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
61
-
62
-        $new_page_config = array(
63
-            'reports' => array(
64
-                'nav'           => array(
65
-                    'label' => __('Reports', 'event_espresso'),
66
-                    'order' => 20,
67
-                ),
68
-                'help_tabs'     => array(
69
-                    'transactions_reports_help_tab' => array(
70
-                        'title'    => __('Transaction Reports', 'event_espresso'),
71
-                        'filename' => 'transactions_reports',
72
-                    ),
73
-                ),
74
-                /*'help_tour' => array( 'Transaction_Reports_Help_Tour' ),*/
75
-                'require_nonce' => false,
76
-            ),
77
-        );
78
-        $this->_page_config = array_merge($this->_page_config, $new_page_config);
79
-    }
80
-
81
-
82
-    /**
83
-     *    load_scripts_styles_reports
84
-     *
85
-     * @access public
86
-     * @return void
87
-     */
88
-    public function load_scripts_styles_reports()
89
-    {
90
-        wp_register_script(
91
-            'ee-txn-reports-js',
92
-            TXN_CAF_ASSETS_URL . 'ee-transaction-admin-reports.js',
93
-            array('google-charts'),
94
-            EVENT_ESPRESSO_VERSION,
95
-            true
96
-        );
97
-        wp_enqueue_script('ee-txn-reports-js');
98
-        $this->_transaction_reports_js_setup();
99
-        EE_Registry::$i18n_js_strings['currency_format'] = EEH_Money::get_format_for_google_charts();
100
-    }
101
-
102
-
103
-    /**
104
-     * This is called when javascript is being enqueued to setup the various data needed for the reports js.
105
-     * Also $this->{$_reports_template_data} property is set for later usage by the _transaction_reports method.
106
-     */
107
-    protected function _transaction_reports_js_setup()
108
-    {
109
-        $this->_reports_template_data['admin_reports'][] = $this->_revenue_per_day_report();
110
-        $this->_reports_template_data['admin_reports'][] = $this->_revenue_per_event_report();
111
-    }
112
-
113
-
114
-    /**
115
-     * _transaction_reports
116
-     *    generates Business Reports regarding Transactions
117
-     *
118
-     * @return void
119
-     */
120
-    protected function _transaction_reports()
121
-    {
122
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
123
-        $this->_admin_page_title = __('Transactions', 'event_espresso');
124
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
125
-            $template_path,
126
-            $this->_reports_template_data,
127
-            true
128
-        );
129
-
130
-        // the final template wrapper
131
-        $this->display_admin_page_with_no_sidebar();
132
-    }
133
-
134
-
135
-    /**
136
-     * _revenue_per_day_report
137
-     * generates Business Report showing Total Revenue per Day.
138
-     *
139
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
140
-     *
141
-     * @return string
142
-     */
143
-    private function _revenue_per_day_report($period = '-1 month')
144
-    {
145
-
146
-        $report_ID = 'txn-admin-revenue-per-day-report-dv';
147
-
148
-        $TXN = EEM_Transaction::instance();
149
-
150
-        $results = $TXN->get_revenue_per_day_report($period);
151
-        $results = (array) $results;
152
-        $revenue = array();
153
-        $subtitle = '';
154
-
155
-        if ($results) {
156
-            $revenue[] = array(
157
-                __('Date (only shows dates that have a revenue greater than 1)', 'event_espresso'),
158
-                __('Total Revenue', 'event_espresso'),
159
-            );
160
-            foreach ($results as $result) {
161
-                $revenue[] = array($result->txnDate, (float) $result->revenue);
162
-            }
163
-
164
-            // setup the date range.
165
-            $beginning_date = new DateTime('now' . $period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
166
-            $ending_date = new DateTime('now', new DateTimeZone(EEH_DTT_Helper::get_timezone()));
167
-            $subtitle = sprintf(
168
-                wp_strip_all_tags(
169
-                    _x('For the period: %s to %s', 'Used to give date range', 'event_espresso')
170
-                ),
171
-                $beginning_date->format('Y-m-d'),
172
-                $ending_date->format('Y-m-d')
173
-            );
174
-        }
175
-
176
-        $report_title = wp_strip_all_tags(__('Total Revenue per Day', 'event_espresso'));
177
-
178
-        $report_params = array(
179
-            'title'     => $report_title,
180
-            'subtitle'  => $subtitle,
181
-            'id'        => $report_ID,
182
-            'revenue'   => $revenue,
183
-            'noResults' => empty($revenue) || count($revenue) === 1,
184
-            'noTxnMsg'  => sprintf(
185
-                wp_strip_all_tags(
186
-                    __('%sThere is no revenue to report for the last 30 days.%s', 'event_espresso')
187
-                ),
188
-                '<h2>' . $report_title . '</h2><p>',
189
-                '</p>'
190
-            ),
191
-        );
192
-        wp_localize_script('ee-txn-reports-js', 'txnRevPerDay', $report_params);
193
-
194
-        return $report_ID;
195
-    }
196
-
197
-
198
-    /**
199
-     * _revenue_per_event_report
200
-     * generates Business Report showing total revenue per event.
201
-     *
202
-     * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
203
-     *
204
-     * @return int
205
-     */
206
-    private function _revenue_per_event_report($period = '-1 month')
207
-    {
208
-
209
-        $report_ID = 'txn-admin-revenue-per-event-report-dv';
210
-
211
-        $TXN = EEM_Transaction::instance();
212
-        $results = $TXN->get_revenue_per_event_report($period);
213
-        $results = (array) $results;
214
-        $revenue = array();
215
-        $subtitle = '';
216
-
217
-        if ($results) {
218
-            $revenue[] = array(
219
-                __('Event (only events that have a revenue greater than 1 are shown)', 'event_espresso'),
220
-                __('Total Revenue', 'event_espresso'),
221
-            );
222
-            foreach ($results as $result) {
223
-                if ($result->revenue > 1) {
224
-                    $event_name = stripslashes(html_entity_decode($result->event_name, ENT_QUOTES, 'UTF-8'));
225
-                    $event_name = wp_trim_words($event_name, 5, '...');
226
-                    $revenue[] = array($event_name, (float) $result->revenue);
227
-                }
228
-            }
229
-
230
-            // setup the date range.
231
-            $beginning_date = new DateTime('now' . $period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
232
-            $ending_date = new DateTime('now', new DateTimeZone(EEH_DTT_Helper::get_timezone()));
233
-            $subtitle = sprintf(
234
-                wp_strip_all_tags(
235
-                    _x('For the period: %s to %s', 'Used to give date range', 'event_espresso')
236
-                ),
237
-                $beginning_date->format('Y-m-d'),
238
-                $ending_date->format('Y-m-d')
239
-            );
240
-        }
241
-
242
-        $report_title = wp_strip_all_tags(__('Total Revenue per Event', 'event_espresso'));
243
-
244
-        $report_params = array(
245
-            'title'     => $report_title,
246
-            'subtitle'  => $subtitle,
247
-            'id'        => $report_ID,
248
-            'revenue'   => $revenue,
249
-            'noResults' => empty($revenue),
250
-            'noTxnMsg'  => sprintf(
251
-                wp_strip_all_tags(
252
-                    __('%sThere is no revenue to report for the last 30 days.%s', 'event_espresso')
253
-                ),
254
-                '<h2>' . $report_title . '</h2><p>',
255
-                '</p>'
256
-            ),
257
-        );
258
-        wp_localize_script('ee-txn-reports-js', 'txnRevPerEvent', $report_params);
259
-
260
-        return $report_ID;
261
-    }
19
+	/**
20
+	 * This is used to hold the reports template data which is setup early in the request.
21
+	 *
22
+	 * @type array
23
+	 */
24
+	protected $_reports_template_data = array();
25
+
26
+	/**
27
+	 * @Constructor
28
+	 * @access public
29
+	 *
30
+	 * @param bool $routing
31
+	 *
32
+	 * @return \Extend_Transactions_Admin_Page
33
+	 */
34
+	public function __construct($routing = true)
35
+	{
36
+		parent::__construct($routing);
37
+		define('TXN_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'transactions/templates/');
38
+		define('TXN_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'transactions/assets/');
39
+		define('TXN_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'transactions/assets/');
40
+	}
41
+
42
+
43
+	/**
44
+	 *    _extend_page_config
45
+	 *
46
+	 * @access protected
47
+	 * @return void
48
+	 */
49
+	protected function _extend_page_config()
50
+	{
51
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'transactions';
52
+
53
+		$new_page_routes = array(
54
+			'reports' => array(
55
+				'func'       => '_transaction_reports',
56
+				'capability' => 'ee_read_transactions',
57
+			),
58
+		);
59
+
60
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
61
+
62
+		$new_page_config = array(
63
+			'reports' => array(
64
+				'nav'           => array(
65
+					'label' => __('Reports', 'event_espresso'),
66
+					'order' => 20,
67
+				),
68
+				'help_tabs'     => array(
69
+					'transactions_reports_help_tab' => array(
70
+						'title'    => __('Transaction Reports', 'event_espresso'),
71
+						'filename' => 'transactions_reports',
72
+					),
73
+				),
74
+				/*'help_tour' => array( 'Transaction_Reports_Help_Tour' ),*/
75
+				'require_nonce' => false,
76
+			),
77
+		);
78
+		$this->_page_config = array_merge($this->_page_config, $new_page_config);
79
+	}
80
+
81
+
82
+	/**
83
+	 *    load_scripts_styles_reports
84
+	 *
85
+	 * @access public
86
+	 * @return void
87
+	 */
88
+	public function load_scripts_styles_reports()
89
+	{
90
+		wp_register_script(
91
+			'ee-txn-reports-js',
92
+			TXN_CAF_ASSETS_URL . 'ee-transaction-admin-reports.js',
93
+			array('google-charts'),
94
+			EVENT_ESPRESSO_VERSION,
95
+			true
96
+		);
97
+		wp_enqueue_script('ee-txn-reports-js');
98
+		$this->_transaction_reports_js_setup();
99
+		EE_Registry::$i18n_js_strings['currency_format'] = EEH_Money::get_format_for_google_charts();
100
+	}
101
+
102
+
103
+	/**
104
+	 * This is called when javascript is being enqueued to setup the various data needed for the reports js.
105
+	 * Also $this->{$_reports_template_data} property is set for later usage by the _transaction_reports method.
106
+	 */
107
+	protected function _transaction_reports_js_setup()
108
+	{
109
+		$this->_reports_template_data['admin_reports'][] = $this->_revenue_per_day_report();
110
+		$this->_reports_template_data['admin_reports'][] = $this->_revenue_per_event_report();
111
+	}
112
+
113
+
114
+	/**
115
+	 * _transaction_reports
116
+	 *    generates Business Reports regarding Transactions
117
+	 *
118
+	 * @return void
119
+	 */
120
+	protected function _transaction_reports()
121
+	{
122
+		$template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
123
+		$this->_admin_page_title = __('Transactions', 'event_espresso');
124
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
125
+			$template_path,
126
+			$this->_reports_template_data,
127
+			true
128
+		);
129
+
130
+		// the final template wrapper
131
+		$this->display_admin_page_with_no_sidebar();
132
+	}
133
+
134
+
135
+	/**
136
+	 * _revenue_per_day_report
137
+	 * generates Business Report showing Total Revenue per Day.
138
+	 *
139
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
140
+	 *
141
+	 * @return string
142
+	 */
143
+	private function _revenue_per_day_report($period = '-1 month')
144
+	{
145
+
146
+		$report_ID = 'txn-admin-revenue-per-day-report-dv';
147
+
148
+		$TXN = EEM_Transaction::instance();
149
+
150
+		$results = $TXN->get_revenue_per_day_report($period);
151
+		$results = (array) $results;
152
+		$revenue = array();
153
+		$subtitle = '';
154
+
155
+		if ($results) {
156
+			$revenue[] = array(
157
+				__('Date (only shows dates that have a revenue greater than 1)', 'event_espresso'),
158
+				__('Total Revenue', 'event_espresso'),
159
+			);
160
+			foreach ($results as $result) {
161
+				$revenue[] = array($result->txnDate, (float) $result->revenue);
162
+			}
163
+
164
+			// setup the date range.
165
+			$beginning_date = new DateTime('now' . $period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
166
+			$ending_date = new DateTime('now', new DateTimeZone(EEH_DTT_Helper::get_timezone()));
167
+			$subtitle = sprintf(
168
+				wp_strip_all_tags(
169
+					_x('For the period: %s to %s', 'Used to give date range', 'event_espresso')
170
+				),
171
+				$beginning_date->format('Y-m-d'),
172
+				$ending_date->format('Y-m-d')
173
+			);
174
+		}
175
+
176
+		$report_title = wp_strip_all_tags(__('Total Revenue per Day', 'event_espresso'));
177
+
178
+		$report_params = array(
179
+			'title'     => $report_title,
180
+			'subtitle'  => $subtitle,
181
+			'id'        => $report_ID,
182
+			'revenue'   => $revenue,
183
+			'noResults' => empty($revenue) || count($revenue) === 1,
184
+			'noTxnMsg'  => sprintf(
185
+				wp_strip_all_tags(
186
+					__('%sThere is no revenue to report for the last 30 days.%s', 'event_espresso')
187
+				),
188
+				'<h2>' . $report_title . '</h2><p>',
189
+				'</p>'
190
+			),
191
+		);
192
+		wp_localize_script('ee-txn-reports-js', 'txnRevPerDay', $report_params);
193
+
194
+		return $report_ID;
195
+	}
196
+
197
+
198
+	/**
199
+	 * _revenue_per_event_report
200
+	 * generates Business Report showing total revenue per event.
201
+	 *
202
+	 * @param string $period The period (acceptable by PHP Datetime constructor) for which the report is generated.
203
+	 *
204
+	 * @return int
205
+	 */
206
+	private function _revenue_per_event_report($period = '-1 month')
207
+	{
208
+
209
+		$report_ID = 'txn-admin-revenue-per-event-report-dv';
210
+
211
+		$TXN = EEM_Transaction::instance();
212
+		$results = $TXN->get_revenue_per_event_report($period);
213
+		$results = (array) $results;
214
+		$revenue = array();
215
+		$subtitle = '';
216
+
217
+		if ($results) {
218
+			$revenue[] = array(
219
+				__('Event (only events that have a revenue greater than 1 are shown)', 'event_espresso'),
220
+				__('Total Revenue', 'event_espresso'),
221
+			);
222
+			foreach ($results as $result) {
223
+				if ($result->revenue > 1) {
224
+					$event_name = stripslashes(html_entity_decode($result->event_name, ENT_QUOTES, 'UTF-8'));
225
+					$event_name = wp_trim_words($event_name, 5, '...');
226
+					$revenue[] = array($event_name, (float) $result->revenue);
227
+				}
228
+			}
229
+
230
+			// setup the date range.
231
+			$beginning_date = new DateTime('now' . $period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
232
+			$ending_date = new DateTime('now', new DateTimeZone(EEH_DTT_Helper::get_timezone()));
233
+			$subtitle = sprintf(
234
+				wp_strip_all_tags(
235
+					_x('For the period: %s to %s', 'Used to give date range', 'event_espresso')
236
+				),
237
+				$beginning_date->format('Y-m-d'),
238
+				$ending_date->format('Y-m-d')
239
+			);
240
+		}
241
+
242
+		$report_title = wp_strip_all_tags(__('Total Revenue per Event', 'event_espresso'));
243
+
244
+		$report_params = array(
245
+			'title'     => $report_title,
246
+			'subtitle'  => $subtitle,
247
+			'id'        => $report_ID,
248
+			'revenue'   => $revenue,
249
+			'noResults' => empty($revenue),
250
+			'noTxnMsg'  => sprintf(
251
+				wp_strip_all_tags(
252
+					__('%sThere is no revenue to report for the last 30 days.%s', 'event_espresso')
253
+				),
254
+				'<h2>' . $report_title . '</h2><p>',
255
+				'</p>'
256
+			),
257
+		);
258
+		wp_localize_script('ee-txn-reports-js', 'txnRevPerEvent', $report_params);
259
+
260
+		return $report_ID;
261
+	}
262 262
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -34,9 +34,9 @@  discard block
 block discarded – undo
34 34
     public function __construct($routing = true)
35 35
     {
36 36
         parent::__construct($routing);
37
-        define('TXN_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'transactions/templates/');
38
-        define('TXN_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'transactions/assets/');
39
-        define('TXN_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'transactions/assets/');
37
+        define('TXN_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND.'transactions/templates/');
38
+        define('TXN_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND.'transactions/assets/');
39
+        define('TXN_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'transactions/assets/');
40 40
     }
41 41
 
42 42
 
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
      */
49 49
     protected function _extend_page_config()
50 50
     {
51
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'transactions';
51
+        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND.'transactions';
52 52
 
53 53
         $new_page_routes = array(
54 54
             'reports' => array(
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
     {
90 90
         wp_register_script(
91 91
             'ee-txn-reports-js',
92
-            TXN_CAF_ASSETS_URL . 'ee-transaction-admin-reports.js',
92
+            TXN_CAF_ASSETS_URL.'ee-transaction-admin-reports.js',
93 93
             array('google-charts'),
94 94
             EVENT_ESPRESSO_VERSION,
95 95
             true
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
      */
120 120
     protected function _transaction_reports()
121 121
     {
122
-        $template_path = EE_ADMIN_TEMPLATE . 'admin_reports.template.php';
122
+        $template_path = EE_ADMIN_TEMPLATE.'admin_reports.template.php';
123 123
         $this->_admin_page_title = __('Transactions', 'event_espresso');
124 124
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
125 125
             $template_path,
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
             }
163 163
 
164 164
             // setup the date range.
165
-            $beginning_date = new DateTime('now' . $period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
165
+            $beginning_date = new DateTime('now'.$period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
166 166
             $ending_date = new DateTime('now', new DateTimeZone(EEH_DTT_Helper::get_timezone()));
167 167
             $subtitle = sprintf(
168 168
                 wp_strip_all_tags(
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
                 wp_strip_all_tags(
186 186
                     __('%sThere is no revenue to report for the last 30 days.%s', 'event_espresso')
187 187
                 ),
188
-                '<h2>' . $report_title . '</h2><p>',
188
+                '<h2>'.$report_title.'</h2><p>',
189 189
                 '</p>'
190 190
             ),
191 191
         );
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
             }
229 229
 
230 230
             // setup the date range.
231
-            $beginning_date = new DateTime('now' . $period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
231
+            $beginning_date = new DateTime('now'.$period, new DateTimeZone(EEH_DTT_Helper::get_timezone()));
232 232
             $ending_date = new DateTime('now', new DateTimeZone(EEH_DTT_Helper::get_timezone()));
233 233
             $subtitle = sprintf(
234 234
                 wp_strip_all_tags(
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
                 wp_strip_all_tags(
252 252
                     __('%sThere is no revenue to report for the last 30 days.%s', 'event_espresso')
253 253
                 ),
254
-                '<h2>' . $report_title . '</h2><p>',
254
+                '<h2>'.$report_title.'</h2><p>',
255 255
                 '</p>'
256 256
             ),
257 257
         );
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT_Init.core.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -14,45 +14,45 @@
 block discarded – undo
14 14
 {
15 15
 
16 16
 
17
-    public function do_initial_loads()
18
-    {
19
-        // we want to use the corresponding admin page object (but not route it!).  To do this we just set _routing to false.  That way this page object is being loaded on all pages to make sure we hook into admin properly.  But note... we are ONLY doing this if the given page is NOT pages we WANT to load ;)
20
-        // This is important because we have hooks that help redirect custom post type saves
21
-        if (! isset($_REQUEST['page'])
22
-            || (isset($_REQUEST['page'])
23
-                && $_REQUEST['page']
24
-                   != $this->_menu_map->menu_slug)) {
25
-            $this->_routing = false;
26
-            $this->_initialize_admin_page();
27
-        } else {
28
-            // normal init loads
29
-            $this->_initialize_admin_page();
30
-            // added for 4.1 to completely disable autosave for our pages. This can be removed once we fully enable autosave functionality
31
-            remove_filter('wp_print_scripts', 'wp_just_in_time_script_localization');
32
-            add_filter('wp_print_scripts', array($this, 'wp_just_in_time_script_localization'), 100);
33
-            // end removal of autosave functionality.
34
-        }
35
-    }
17
+	public function do_initial_loads()
18
+	{
19
+		// we want to use the corresponding admin page object (but not route it!).  To do this we just set _routing to false.  That way this page object is being loaded on all pages to make sure we hook into admin properly.  But note... we are ONLY doing this if the given page is NOT pages we WANT to load ;)
20
+		// This is important because we have hooks that help redirect custom post type saves
21
+		if (! isset($_REQUEST['page'])
22
+			|| (isset($_REQUEST['page'])
23
+				&& $_REQUEST['page']
24
+				   != $this->_menu_map->menu_slug)) {
25
+			$this->_routing = false;
26
+			$this->_initialize_admin_page();
27
+		} else {
28
+			// normal init loads
29
+			$this->_initialize_admin_page();
30
+			// added for 4.1 to completely disable autosave for our pages. This can be removed once we fully enable autosave functionality
31
+			remove_filter('wp_print_scripts', 'wp_just_in_time_script_localization');
32
+			add_filter('wp_print_scripts', array($this, 'wp_just_in_time_script_localization'), 100);
33
+			// end removal of autosave functionality.
34
+		}
35
+	}
36 36
 
37 37
 
38
-    public function wp_just_in_time_script_localization()
39
-    {
40
-        wp_localize_script(
41
-            'autosave',
42
-            'autosaveL10n',
43
-            array(
44
-                'autosaveInterval' => 172800,
45
-                'savingText'       => wp_strip_all_tags(__('Saving Draft&#8230;', 'event_espresso')),
46
-                'saveAlert'        => wp_strip_all_tags(
47
-                    __('The changes you made will be lost if you navigate away from this page.', 'event_espresso')
48
-                ),
49
-            )
50
-        );
51
-    }
38
+	public function wp_just_in_time_script_localization()
39
+	{
40
+		wp_localize_script(
41
+			'autosave',
42
+			'autosaveL10n',
43
+			array(
44
+				'autosaveInterval' => 172800,
45
+				'savingText'       => wp_strip_all_tags(__('Saving Draft&#8230;', 'event_espresso')),
46
+				'saveAlert'        => wp_strip_all_tags(
47
+					__('The changes you made will be lost if you navigate away from this page.', 'event_espresso')
48
+				),
49
+			)
50
+		);
51
+	}
52 52
 
53 53
 
54
-    public function adjust_post_lock_window($interval)
55
-    {
56
-        return 172800;
57
-    }
54
+	public function adjust_post_lock_window($interval)
55
+	{
56
+		return 172800;
57
+	}
58 58
 }
Please login to merge, or discard this patch.
admin_pages/maintenance/Maintenance_Admin_Page.core.php 1 patch
Indentation   +882 added lines, -882 removed lines patch added patch discarded remove patch
@@ -17,886 +17,886 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * @var EE_Form_Section_Proper
22
-     */
23
-    protected $datetime_fix_offset_form;
24
-
25
-
26
-    protected function _init_page_props()
27
-    {
28
-        $this->page_slug = EE_MAINTENANCE_PG_SLUG;
29
-        $this->page_label = EE_MAINTENANCE_LABEL;
30
-        $this->_admin_base_url = EE_MAINTENANCE_ADMIN_URL;
31
-        $this->_admin_base_path = EE_MAINTENANCE_ADMIN;
32
-    }
33
-
34
-
35
-    protected function _ajax_hooks()
36
-    {
37
-        add_action('wp_ajax_migration_step', array($this, 'migration_step'));
38
-        add_action('wp_ajax_add_error_to_migrations_ran', array($this, 'add_error_to_migrations_ran'));
39
-    }
40
-
41
-
42
-    protected function _define_page_props()
43
-    {
44
-        $this->_admin_page_title = EE_MAINTENANCE_LABEL;
45
-        $this->_labels = array(
46
-            'buttons' => array(
47
-                'reset_reservations' => esc_html__('Reset Ticket and Datetime Reserved Counts', 'event_espresso'),
48
-                'reset_capabilities' => esc_html__('Reset Event Espresso Capabilities', 'event_espresso'),
49
-            ),
50
-        );
51
-    }
52
-
53
-
54
-    protected function _set_page_routes()
55
-    {
56
-        $this->_page_routes = array(
57
-            'default'                             => array(
58
-                'func'       => '_maintenance',
59
-                'capability' => 'manage_options',
60
-            ),
61
-            'change_maintenance_level'            => array(
62
-                'func'       => '_change_maintenance_level',
63
-                'capability' => 'manage_options',
64
-                'noheader'   => true,
65
-            ),
66
-            'system_status'                       => array(
67
-                'func'       => '_system_status',
68
-                'capability' => 'manage_options',
69
-            ),
70
-            'download_system_status'              => array(
71
-                'func'       => '_download_system_status',
72
-                'capability' => 'manage_options',
73
-                'noheader'   => true,
74
-            ),
75
-            'send_migration_crash_report'         => array(
76
-                'func'       => '_send_migration_crash_report',
77
-                'capability' => 'manage_options',
78
-                'noheader'   => true,
79
-            ),
80
-            'confirm_migration_crash_report_sent' => array(
81
-                'func'       => '_confirm_migration_crash_report_sent',
82
-                'capability' => 'manage_options',
83
-            ),
84
-            'data_reset'                          => array(
85
-                'func'       => '_data_reset_and_delete',
86
-                'capability' => 'manage_options',
87
-            ),
88
-            'reset_db'                            => array(
89
-                'func'       => '_reset_db',
90
-                'capability' => 'manage_options',
91
-                'noheader'   => true,
92
-                'args'       => array('nuke_old_ee4_data' => true),
93
-            ),
94
-            'start_with_fresh_ee4_db'             => array(
95
-                'func'       => '_reset_db',
96
-                'capability' => 'manage_options',
97
-                'noheader'   => true,
98
-                'args'       => array('nuke_old_ee4_data' => false),
99
-            ),
100
-            'delete_db'                           => array(
101
-                'func'       => '_delete_db',
102
-                'capability' => 'manage_options',
103
-                'noheader'   => true,
104
-            ),
105
-            'rerun_migration_from_ee3'            => array(
106
-                'func'       => '_rerun_migration_from_ee3',
107
-                'capability' => 'manage_options',
108
-                'noheader'   => true,
109
-            ),
110
-            'reset_reservations'                  => array(
111
-                'func'       => '_reset_reservations',
112
-                'capability' => 'manage_options',
113
-                'noheader'   => true,
114
-            ),
115
-            'reset_capabilities'                  => array(
116
-                'func'       => '_reset_capabilities',
117
-                'capability' => 'manage_options',
118
-                'noheader'   => true,
119
-            ),
120
-            'reattempt_migration'                 => array(
121
-                'func'       => '_reattempt_migration',
122
-                'capability' => 'manage_options',
123
-                'noheader'   => true,
124
-            ),
125
-            'datetime_tools'                      => array(
126
-                'func'       => '_datetime_tools',
127
-                'capability' => 'manage_options',
128
-            ),
129
-            'run_datetime_offset_fix'             => array(
130
-                'func'               => '_apply_datetime_offset',
131
-                'noheader'           => true,
132
-                'headers_sent_route' => 'datetime_tools',
133
-                'capability'         => 'manage_options',
134
-            ),
135
-        );
136
-    }
137
-
138
-
139
-    protected function _set_page_config()
140
-    {
141
-        $this->_page_config = array(
142
-            'default'        => array(
143
-                'nav'           => array(
144
-                    'label' => esc_html__('Maintenance', 'event_espresso'),
145
-                    'order' => 10,
146
-                ),
147
-                'require_nonce' => false,
148
-            ),
149
-            'data_reset'     => array(
150
-                'nav'           => array(
151
-                    'label' => esc_html__('Reset/Delete Data', 'event_espresso'),
152
-                    'order' => 20,
153
-                ),
154
-                'require_nonce' => false,
155
-            ),
156
-            'datetime_tools' => array(
157
-                'nav'           => array(
158
-                    'label' => esc_html__('Datetime Utilities', 'event_espresso'),
159
-                    'order' => 25,
160
-                ),
161
-                'require_nonce' => false,
162
-            ),
163
-            'system_status'  => array(
164
-                'nav'           => array(
165
-                    'label' => esc_html__("System Information", "event_espresso"),
166
-                    'order' => 30,
167
-                ),
168
-                'require_nonce' => false,
169
-            ),
170
-        );
171
-    }
172
-
173
-
174
-    /**
175
-     * default maintenance page. If we're in maintenance mode level 2, then we need to show
176
-     * the migration scripts and all that UI.
177
-     */
178
-    public function _maintenance()
179
-    {
180
-        // it all depends if we're in maintenance model level 1 (frontend-only) or
181
-        // level 2 (everything except maintenance page)
182
-        try {
183
-            // get the current maintenance level and check if
184
-            // we are removed
185
-            $mm = EE_Maintenance_Mode::instance()->level();
186
-            $placed_in_mm = EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
187
-            if ($mm == EE_Maintenance_Mode::level_2_complete_maintenance && ! $placed_in_mm) {
188
-                // we just took the site out of maintenance mode, so notify the user.
189
-                // unfortunately this message appears to be echoed on the NEXT page load...
190
-                // oh well, we should really be checking for this on addon deactivation anyways
191
-                EE_Error::add_attention(
192
-                    __(
193
-                        'Site taken out of maintenance mode because no data migration scripts are required',
194
-                        'event_espresso'
195
-                    )
196
-                );
197
-                $this->_process_notices(array('page' => 'espresso_maintenance_settings'), false);
198
-            }
199
-            // in case an exception is thrown while trying to handle migrations
200
-            switch (EE_Maintenance_Mode::instance()->level()) {
201
-                case EE_Maintenance_Mode::level_0_not_in_maintenance:
202
-                case EE_Maintenance_Mode::level_1_frontend_only_maintenance:
203
-                    $show_maintenance_switch = true;
204
-                    $show_backup_db_text = false;
205
-                    $show_migration_progress = false;
206
-                    $script_names = array();
207
-                    $addons_should_be_upgraded_first = false;
208
-                    break;
209
-                case EE_Maintenance_Mode::level_2_complete_maintenance:
210
-                    $show_maintenance_switch = false;
211
-                    $show_migration_progress = true;
212
-                    if (isset($this->_req_data['continue_migration'])) {
213
-                        $show_backup_db_text = false;
214
-                    } else {
215
-                        $show_backup_db_text = true;
216
-                    }
217
-                    $scripts_needing_to_run = EE_Data_Migration_Manager::instance()
218
-                                                                       ->check_for_applicable_data_migration_scripts();
219
-                    $addons_should_be_upgraded_first = EE_Data_Migration_Manager::instance()->addons_need_updating();
220
-                    $script_names = array();
221
-                    $current_script = null;
222
-                    foreach ($scripts_needing_to_run as $script) {
223
-                        if ($script instanceof EE_Data_Migration_Script_Base) {
224
-                            if (! $current_script) {
225
-                                $current_script = $script;
226
-                                $current_script->migration_page_hooks();
227
-                            }
228
-                            $script_names[] = $script->pretty_name();
229
-                        }
230
-                    }
231
-                    break;
232
-            }
233
-            $most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
234
-            $exception_thrown = false;
235
-        } catch (EE_Error $e) {
236
-            EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
237
-            // now, just so we can display the page correctly, make a error migration script stage object
238
-            // and also put the error on it. It only persists for the duration of this request
239
-            $most_recent_migration = new EE_DMS_Unknown_1_0_0();
240
-            $most_recent_migration->add_error($e->getMessage());
241
-            $exception_thrown = true;
242
-        }
243
-        $current_db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set();
244
-        $current_db_state = str_replace('.decaf', '', $current_db_state);
245
-        if ($exception_thrown
246
-            || ($most_recent_migration
247
-                && $most_recent_migration instanceof EE_Data_Migration_Script_Base
248
-                && $most_recent_migration->is_broken()
249
-            )
250
-        ) {
251
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
252
-            $this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
253
-            $this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(
254
-                array(
255
-                    'action'  => 'confirm_migration_crash_report_sent',
256
-                    'success' => '0',
257
-                ),
258
-                EE_MAINTENANCE_ADMIN_URL
259
-            );
260
-        } elseif ($addons_should_be_upgraded_first) {
261
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
262
-        } else {
263
-            if ($most_recent_migration
264
-                && $most_recent_migration instanceof EE_Data_Migration_Script_Base
265
-                && $most_recent_migration->can_continue()
266
-            ) {
267
-                $show_backup_db_text = false;
268
-                $show_continue_current_migration_script = true;
269
-                $show_most_recent_migration = true;
270
-            } elseif (isset($this->_req_data['continue_migration'])) {
271
-                $show_most_recent_migration = true;
272
-                $show_continue_current_migration_script = false;
273
-            } else {
274
-                $show_most_recent_migration = false;
275
-                $show_continue_current_migration_script = false;
276
-            }
277
-            if (isset($current_script)) {
278
-                $migrates_to = $current_script->migrates_to_version();
279
-                $plugin_slug = $migrates_to['slug'];
280
-                $new_version = $migrates_to['version'];
281
-                $this->_template_args = array_merge(
282
-                    $this->_template_args,
283
-                    array(
284
-                        'current_db_state' => sprintf(
285
-                            __("EE%s (%s)", "event_espresso"),
286
-                            isset($current_db_state[ $plugin_slug ]) ? $current_db_state[ $plugin_slug ] : 3,
287
-                            $plugin_slug
288
-                        ),
289
-                        'next_db_state'    => isset($current_script) ? sprintf(
290
-                            __("EE%s (%s)", 'event_espresso'),
291
-                            $new_version,
292
-                            $plugin_slug
293
-                        ) : null,
294
-                    )
295
-                );
296
-            } else {
297
-                $this->_template_args['current_db_state'] = null;
298
-                $this->_template_args['next_db_state'] = null;
299
-            }
300
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
301
-            $this->_template_args = array_merge(
302
-                $this->_template_args,
303
-                array(
304
-                    'show_most_recent_migration'             => $show_most_recent_migration,
305
-                    // flag for showing the most recent migration's status and/or errors
306
-                    'show_migration_progress'                => $show_migration_progress,
307
-                    // flag for showing the option to run migrations and see their progress
308
-                    'show_backup_db_text'                    => $show_backup_db_text,
309
-                    // flag for showing text telling the user to backup their DB
310
-                    'show_maintenance_switch'                => $show_maintenance_switch,
311
-                    // flag for showing the option to change maintenance mode between levels 0 and 1
312
-                    'script_names'                           => $script_names,
313
-                    // array of names of scripts that have run
314
-                    'show_continue_current_migration_script' => $show_continue_current_migration_script,
315
-                    // flag to change wording to indicating that we're only CONTINUING a migration script (somehow it got interrupted0
316
-                    'reset_db_page_link'                     => EE_Admin_Page::add_query_args_and_nonce(
317
-                        array('action' => 'reset_db'),
318
-                        EE_MAINTENANCE_ADMIN_URL
319
-                    ),
320
-                    'data_reset_page'                        => EE_Admin_Page::add_query_args_and_nonce(
321
-                        array('action' => 'data_reset'),
322
-                        EE_MAINTENANCE_ADMIN_URL
323
-                    ),
324
-                    'update_migration_script_page_link'      => EE_Admin_Page::add_query_args_and_nonce(
325
-                        array('action' => 'change_maintenance_level'),
326
-                        EE_MAINTENANCE_ADMIN_URL
327
-                    ),
328
-                    'ultimate_db_state'                      => sprintf(
329
-                        __("EE%s", 'event_espresso'),
330
-                        espresso_version()
331
-                    ),
332
-                )
333
-            );
334
-            // make sure we have the form fields helper available. It usually is, but sometimes it isn't
335
-        }
336
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;// the actual most recently ran migration
337
-        // now render the migration options part, and put it in a variable
338
-        $migration_options_template_file = apply_filters(
339
-            'FHEE__ee_migration_page__migration_options_template',
340
-            EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee4.template.php'
341
-        );
342
-        $migration_options_html = EEH_Template::display_template(
343
-            $migration_options_template_file,
344
-            $this->_template_args,
345
-            true
346
-        );
347
-        $this->_template_args['migration_options_html'] = $migration_options_html;
348
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
349
-            $this->_template_path,
350
-            $this->_template_args,
351
-            true
352
-        );
353
-        $this->display_admin_page_with_sidebar();
354
-    }
355
-
356
-
357
-    /**
358
-     * returns JSON and executes another step of the currently-executing data migration (called via ajax)
359
-     */
360
-    public function migration_step()
361
-    {
362
-        $this->_template_args['data'] = EE_Data_Migration_Manager::instance()->response_to_migration_ajax_request();
363
-        $this->_return_json();
364
-    }
365
-
366
-
367
-    /**
368
-     * Can be used by js when it notices a response with HTML in it in order
369
-     * to log the malformed response
370
-     */
371
-    public function add_error_to_migrations_ran()
372
-    {
373
-        EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($this->_req_data['message']);
374
-        $this->_template_args['data'] = array('ok' => true);
375
-        $this->_return_json();
376
-    }
377
-
378
-
379
-    /**
380
-     * changes the maintenance level, provided there are still no migration scripts that should run
381
-     */
382
-    public function _change_maintenance_level()
383
-    {
384
-        $new_level = absint($this->_req_data['maintenance_mode_level']);
385
-        if (! EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
386
-            EE_Maintenance_Mode::instance()->set_maintenance_level($new_level);
387
-            $success = true;
388
-        } else {
389
-            EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
390
-            $success = false;
391
-        }
392
-        $this->_redirect_after_action($success, 'Maintenance Mode', esc_html__("Updated", "event_espresso"));
393
-    }
394
-
395
-
396
-    /**
397
-     * a tab with options for resetting and/or deleting EE data
398
-     *
399
-     * @throws \EE_Error
400
-     * @throws \DomainException
401
-     */
402
-    public function _data_reset_and_delete()
403
-    {
404
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
405
-        $this->_template_args['reset_reservations_button'] = $this->get_action_link_or_button(
406
-            'reset_reservations',
407
-            'reset_reservations',
408
-            array(),
409
-            'button button-primary ee-confirm',
410
-            '',
411
-            false
412
-        );
413
-        $this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
414
-            'reset_capabilities',
415
-            'reset_capabilities',
416
-            array(),
417
-            'button button-primary ee-confirm',
418
-            '',
419
-            false
420
-        );
421
-        $this->_template_args['delete_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
422
-            array('action' => 'delete_db'),
423
-            EE_MAINTENANCE_ADMIN_URL
424
-        );
425
-        $this->_template_args['reset_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
426
-            array('action' => 'reset_db'),
427
-            EE_MAINTENANCE_ADMIN_URL
428
-        );
429
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
430
-            $this->_template_path,
431
-            $this->_template_args,
432
-            true
433
-        );
434
-        $this->display_admin_page_with_sidebar();
435
-    }
436
-
437
-
438
-    protected function _reset_reservations()
439
-    {
440
-        if (\EED_Ticket_Sales_Monitor::reset_reservation_counts()) {
441
-            EE_Error::add_success(
442
-                __(
443
-                    'Ticket and datetime reserved counts have been successfully reset.',
444
-                    'event_espresso'
445
-                )
446
-            );
447
-        } else {
448
-            EE_Error::add_success(
449
-                __(
450
-                    'Ticket and datetime reserved counts were correct and did not need resetting.',
451
-                    'event_espresso'
452
-                )
453
-            );
454
-        }
455
-        $this->_redirect_after_action(true, '', '', array('action' => 'data_reset'), true);
456
-    }
457
-
458
-
459
-    protected function _reset_capabilities()
460
-    {
461
-        EE_Registry::instance()->CAP->init_caps(true);
462
-        EE_Error::add_success(
463
-            __(
464
-                'Default Event Espresso capabilities have been restored for all current roles.',
465
-                'event_espresso'
466
-            )
467
-        );
468
-        $this->_redirect_after_action(false, '', '', array('action' => 'data_reset'), true);
469
-    }
470
-
471
-
472
-    /**
473
-     * resets the DMSs so we can attempt to continue migrating after a fatal error
474
-     * (only a good idea when someone has somehow tried ot fix whatever caused
475
-     * the fatal error in teh first place)
476
-     */
477
-    protected function _reattempt_migration()
478
-    {
479
-        EE_Data_Migration_Manager::instance()->reattempt();
480
-        $this->_redirect_after_action(false, '', '', array('action' => 'default'), true);
481
-    }
482
-
483
-
484
-    /**
485
-     * shows the big ol' System Information page
486
-     */
487
-    public function _system_status()
488
-    {
489
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
490
-        $this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
491
-        $this->_template_args['download_system_status_url'] = EE_Admin_Page::add_query_args_and_nonce(
492
-            array(
493
-                'action' => 'download_system_status',
494
-            ),
495
-            EE_MAINTENANCE_ADMIN_URL
496
-        );
497
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
498
-            $this->_template_path,
499
-            $this->_template_args,
500
-            true
501
-        );
502
-        $this->display_admin_page_with_sidebar();
503
-    }
504
-
505
-    /**
506
-     * Downloads an HTML file of the system status that can be easily stored or emailed
507
-     */
508
-    public function _download_system_status()
509
-    {
510
-        $status_info = EEM_System_Status::instance()->get_system_stati();
511
-        header('Content-Disposition: attachment');
512
-        header("Content-Disposition: attachment; filename=system_status_" . sanitize_key(site_url()) . ".html");
513
-        echo "<style>table{border:1px solid darkgrey;}td{vertical-align:top}</style>";
514
-        echo "<h1>System Information for " . site_url() . "</h1>";
515
-        echo EEH_Template::layout_array_as_table($status_info);
516
-        die;
517
-    }
518
-
519
-
520
-    public function _send_migration_crash_report()
521
-    {
522
-        $from = $this->_req_data['from'];
523
-        $from_name = $this->_req_data['from_name'];
524
-        $body = $this->_req_data['body'];
525
-        try {
526
-            $success = wp_mail(
527
-                EE_SUPPORT_EMAIL,
528
-                'Migration Crash Report',
529
-                $body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
530
-                array(
531
-                    "from:$from_name<$from>",
532
-                )
533
-            );
534
-        } catch (Exception $e) {
535
-            $success = false;
536
-        }
537
-        $this->_redirect_after_action(
538
-            $success,
539
-            esc_html__("Migration Crash Report", "event_espresso"),
540
-            esc_html__("sent", "event_espresso"),
541
-            array('success' => $success, 'action' => 'confirm_migration_crash_report_sent')
542
-        );
543
-    }
544
-
545
-
546
-    public function _confirm_migration_crash_report_sent()
547
-    {
548
-        try {
549
-            $most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
550
-        } catch (EE_Error $e) {
551
-            EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
552
-            // now, just so we can display the page correctly, make a error migration script stage object
553
-            // and also put the error on it. It only persists for the duration of this request
554
-            $most_recent_migration = new EE_DMS_Unknown_1_0_0();
555
-            $most_recent_migration->add_error($e->getMessage());
556
-        }
557
-        $success = $this->_req_data['success'] == '1' ? true : false;
558
-        $this->_template_args['success'] = $success;
559
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;
560
-        $this->_template_args['reset_db_action_url'] = EE_Admin_Page::add_query_args_and_nonce(
561
-            array('action' => 'reset_db'),
562
-            EE_MAINTENANCE_ADMIN_URL
563
-        );
564
-        $this->_template_args['reset_db_page_url'] = EE_Admin_Page::add_query_args_and_nonce(
565
-            array('action' => 'data_reset'),
566
-            EE_MAINTENANCE_ADMIN_URL
567
-        );
568
-        $this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(
569
-            array('action' => 'reattempt_migration'),
570
-            EE_MAINTENANCE_ADMIN_URL
571
-        );
572
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
573
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
574
-            $this->_template_path,
575
-            $this->_template_args,
576
-            true
577
-        );
578
-        $this->display_admin_page_with_sidebar();
579
-    }
580
-
581
-
582
-    /**
583
-     * Resets the entire EE4 database.
584
-     * Currently basically only sets up ee4 database for a fresh install- doesn't
585
-     * actually clean out the old wp options, or cpts (although does erase old ee table data)
586
-     *
587
-     * @param boolean $nuke_old_ee4_data controls whether or not we
588
-     *                                   destroy the old ee4 data, or just try initializing ee4 default data
589
-     */
590
-    public function _reset_db($nuke_old_ee4_data = true)
591
-    {
592
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
593
-        if ($nuke_old_ee4_data) {
594
-            EEH_Activation::delete_all_espresso_cpt_data();
595
-            EEH_Activation::delete_all_espresso_tables_and_data(false);
596
-            EEH_Activation::remove_cron_tasks();
597
-        }
598
-        // make sure when we reset the registry's config that it
599
-        // switches to using the new singleton
600
-        EE_Registry::instance()->CFG = EE_Registry::instance()->CFG->reset(true);
601
-        EE_System::instance()->initialize_db_if_no_migrations_required(true);
602
-        EE_System::instance()->redirect_to_about_ee();
603
-    }
604
-
605
-
606
-    /**
607
-     * Deletes ALL EE tables, Records, and Options from the database.
608
-     */
609
-    public function _delete_db()
610
-    {
611
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
612
-        EEH_Activation::delete_all_espresso_cpt_data();
613
-        EEH_Activation::delete_all_espresso_tables_and_data();
614
-        EEH_Activation::remove_cron_tasks();
615
-        EEH_Activation::deactivate_event_espresso();
616
-        wp_safe_redirect(admin_url('plugins.php'));
617
-        exit;
618
-    }
619
-
620
-
621
-    /**
622
-     * sets up EE4 to rerun the migrations from ee3 to ee4
623
-     */
624
-    public function _rerun_migration_from_ee3()
625
-    {
626
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
627
-        EEH_Activation::delete_all_espresso_cpt_data();
628
-        EEH_Activation::delete_all_espresso_tables_and_data(false);
629
-        // set the db state to something that will require migrations
630
-        update_option(EE_Data_Migration_Manager::current_database_state, '3.1.36.0');
631
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_2_complete_maintenance);
632
-        $this->_redirect_after_action(
633
-            true,
634
-            esc_html__("Database", 'event_espresso'),
635
-            esc_html__("reset", 'event_espresso')
636
-        );
637
-    }
638
-
639
-
640
-    // none of the below group are currently used for Gateway Settings
641
-    protected function _add_screen_options()
642
-    {
643
-    }
644
-
645
-
646
-    protected function _add_feature_pointers()
647
-    {
648
-    }
649
-
650
-
651
-    public function admin_init()
652
-    {
653
-    }
654
-
655
-
656
-    public function admin_notices()
657
-    {
658
-    }
659
-
660
-
661
-    public function admin_footer_scripts()
662
-    {
663
-    }
664
-
665
-
666
-    public function load_scripts_styles()
667
-    {
668
-        wp_enqueue_script('ee_admin_js');
669
-        wp_enqueue_script(
670
-            'ee-maintenance',
671
-            EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.js',
672
-            array('jquery'),
673
-            EVENT_ESPRESSO_VERSION,
674
-            true
675
-        );
676
-        wp_register_style(
677
-            'espresso_maintenance',
678
-            EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css',
679
-            array(),
680
-            EVENT_ESPRESSO_VERSION
681
-        );
682
-        wp_enqueue_style('espresso_maintenance');
683
-        // localize script stuff
684
-        wp_localize_script(
685
-            'ee-maintenance',
686
-            'ee_maintenance',
687
-            array(
688
-                'migrating'                        => wp_strip_all_tags(__("Updating Database...", "event_espresso")),
689
-                'next'                             => wp_strip_all_tags(__("Next", "event_espresso")),
690
-                'fatal_error'                      => wp_strip_all_tags(__("A Fatal Error Has Occurred", "event_espresso")),
691
-                'click_next_when_ready'            => wp_strip_all_tags(
692
-                    __(
693
-                        "The current Database Update has ended. Click 'next' when ready to proceed",
694
-                        "event_espresso"
695
-                    )
696
-                ),
697
-                'status_no_more_migration_scripts' => EE_Data_Migration_Manager::status_no_more_migration_scripts,
698
-                'status_fatal_error'               => EE_Data_Migration_Manager::status_fatal_error,
699
-                'status_completed'                 => EE_Data_Migration_Manager::status_completed,
700
-                'confirm'                          => wp_strip_all_tags(
701
-                    __(
702
-                        'Are you sure you want to do this? It CANNOT be undone!',
703
-                        'event_espresso'
704
-                    )
705
-                ),
706
-                'confirm_skip_migration'           => wp_strip_all_tags(
707
-                    __(
708
-                        'You have chosen to NOT migrate your existing data. Are you sure you want to continue?',
709
-                        'event_espresso'
710
-                    )
711
-                ),
712
-            )
713
-        );
714
-    }
715
-
716
-
717
-    public function load_scripts_styles_default()
718
-    {
719
-    }
720
-
721
-
722
-    /**
723
-     * Enqueue scripts and styles for the datetime tools page.
724
-     */
725
-    public function load_scripts_styles_datetime_tools()
726
-    {
727
-        EE_Datepicker_Input::enqueue_styles_and_scripts();
728
-    }
729
-
730
-
731
-    protected function _datetime_tools()
732
-    {
733
-        $form_action = EE_Admin_Page::add_query_args_and_nonce(
734
-            array(
735
-                'action'        => 'run_datetime_offset_fix',
736
-                'return_action' => $this->_req_action,
737
-            ),
738
-            EE_MAINTENANCE_ADMIN_URL
739
-        );
740
-        $form = $this->_get_datetime_offset_fix_form();
741
-        $this->_admin_page_title = esc_html__('Datetime Utilities', 'event_espresso');
742
-        $this->_template_args['admin_page_content'] = $form->form_open($form_action, 'post')
743
-                                                      . $form->get_html_and_js()
744
-                                                      . $form->form_close();
745
-        $this->display_admin_page_with_no_sidebar();
746
-    }
747
-
748
-
749
-    protected function _get_datetime_offset_fix_form()
750
-    {
751
-        if (! $this->datetime_fix_offset_form instanceof EE_Form_Section_Proper) {
752
-            $this->datetime_fix_offset_form = new EE_Form_Section_Proper(
753
-                array(
754
-                    'name'            => 'datetime_offset_fix_option',
755
-                    'layout_strategy' => new EE_Admin_Two_Column_Layout(),
756
-                    'subsections'     => array(
757
-                        'title'                  => new EE_Form_Section_HTML(
758
-                            EEH_HTML::h2(
759
-                                esc_html__('Datetime Offset Tool', 'event_espresso')
760
-                            )
761
-                        ),
762
-                        'explanation'            => new EE_Form_Section_HTML(
763
-                            EEH_HTML::p(
764
-                                esc_html__(
765
-                                    'Use this tool to automatically apply the provided offset to all Event Espresso records in your database that involve dates and times.',
766
-                                    'event_espresso'
767
-                                )
768
-                            )
769
-                            . EEH_HTML::p(
770
-                                esc_html__(
771
-                                    'Note: If you enter 1.25, that will result in the offset of 1 hour 15 minutes being applied.  Decimals represent the fraction of hours, not minutes.',
772
-                                    'event_espresso'
773
-                                )
774
-                            )
775
-                        ),
776
-                        'offset_input'           => new EE_Float_Input(
777
-                            array(
778
-                                'html_name'       => 'offset_for_datetimes',
779
-                                'html_label_text' => esc_html__(
780
-                                    'Offset to apply (in hours):',
781
-                                    'event_espresso'
782
-                                ),
783
-                                'min_value'       => '-12',
784
-                                'max_value'       => '14',
785
-                                'step_value'      => '.25',
786
-                                'default'         => DatetimeOffsetFix::getOffset(),
787
-                            )
788
-                        ),
789
-                        'date_range_explanation' => new EE_Form_Section_HTML(
790
-                            EEH_HTML::p(
791
-                                esc_html__(
792
-                                    'Leave the following fields blank if you want the offset to be applied to all dates. If however, you want to just apply the offset to a specific range of dates you can restrict the offset application using these fields.',
793
-                                    'event_espresso'
794
-                                )
795
-                            )
796
-                            . EEH_HTML::p(
797
-                                EEH_HTML::strong(
798
-                                    sprintf(
799
-                                        esc_html__(
800
-                                            'Note: please enter the dates in UTC (You can use %1$sthis online tool%2$s to assist with conversions).',
801
-                                            'event_espresso'
802
-                                        ),
803
-                                        '<a href="https://www.timeanddate.com/worldclock/converter.html">',
804
-                                        '</a>'
805
-                                    )
806
-                                )
807
-                            )
808
-                        ),
809
-                        'date_range_start_date'  => new EE_Datepicker_Input(
810
-                            array(
811
-                                'html_name'       => 'offset_date_start_range',
812
-                                'html_label_text' => esc_html__(
813
-                                    'Start Date for dates the offset applied to:',
814
-                                    'event_espresso'
815
-                                ),
816
-                            )
817
-                        ),
818
-                        'date_range_end_date'    => new EE_Datepicker_Input(
819
-                            array(
820
-                                'html_name'       => 'offset_date_end_range',
821
-                                'html_label_text' => esc_html__(
822
-                                    'End Date for dates the offset is applied to:',
823
-                                    'event_espresso'
824
-                                ),
825
-                            )
826
-                        ),
827
-                        'submit'                 => new EE_Submit_Input(
828
-                            array(
829
-                                'html_label_text' => '',
830
-                                'default'         => esc_html__('Apply Offset', 'event_espresso'),
831
-                            )
832
-                        ),
833
-                    ),
834
-                )
835
-            );
836
-        }
837
-        return $this->datetime_fix_offset_form;
838
-    }
839
-
840
-
841
-    /**
842
-     * Callback for the run_datetime_offset_fix route.
843
-     *
844
-     * @throws EE_Error
845
-     */
846
-    protected function _apply_datetime_offset()
847
-    {
848
-        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
849
-            $form = $this->_get_datetime_offset_fix_form();
850
-            $form->receive_form_submission($this->_req_data);
851
-            if ($form->is_valid()) {
852
-                // save offset data so batch processor can get it.
853
-                DatetimeOffsetFix::updateOffset($form->get_input_value('offset_input'));
854
-                $utc_timezone = new DateTimeZone('UTC');
855
-                $date_range_start_date = DateTime::createFromFormat(
856
-                    'm/d/Y H:i:s',
857
-                    $form->get_input_value('date_range_start_date') . ' 00:00:00',
858
-                    $utc_timezone
859
-                );
860
-                $date_range_end_date = DateTime::createFromFormat(
861
-                    'm/d/Y H:i:s',
862
-                    $form->get_input_value('date_range_end_date') . ' 23:59:59',
863
-                    $utc_timezone
864
-                );
865
-                if ($date_range_start_date instanceof DateTime) {
866
-                    DatetimeOffsetFix::updateStartDateRange(DbSafeDateTime::createFromDateTime($date_range_start_date));
867
-                }
868
-                if ($date_range_end_date instanceof DateTime) {
869
-                    DatetimeOffsetFix::updateEndDateRange(DbSafeDateTime::createFromDateTime($date_range_end_date));
870
-                }
871
-                // redirect to batch tool
872
-                wp_redirect(
873
-                    EE_Admin_Page::add_query_args_and_nonce(
874
-                        array(
875
-                            'page'        => 'espresso_batch',
876
-                            'batch'       => 'job',
877
-                            'label'       => esc_html__('Applying Offset', 'event_espresso'),
878
-                            'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\DatetimeOffsetFix'),
879
-                            'return_url'  => urlencode(
880
-                                add_query_arg(
881
-                                    array(
882
-                                        'action' => 'datetime_tools',
883
-                                    ),
884
-                                    EEH_URL::current_url_without_query_paramaters(
885
-                                        array(
886
-                                            'return_action',
887
-                                            'run_datetime_offset_fix_nonce',
888
-                                            'return',
889
-                                            'datetime_tools_nonce',
890
-                                        )
891
-                                    )
892
-                                )
893
-                            ),
894
-                        ),
895
-                        admin_url()
896
-                    )
897
-                );
898
-                exit;
899
-            }
900
-        }
901
-    }
20
+	/**
21
+	 * @var EE_Form_Section_Proper
22
+	 */
23
+	protected $datetime_fix_offset_form;
24
+
25
+
26
+	protected function _init_page_props()
27
+	{
28
+		$this->page_slug = EE_MAINTENANCE_PG_SLUG;
29
+		$this->page_label = EE_MAINTENANCE_LABEL;
30
+		$this->_admin_base_url = EE_MAINTENANCE_ADMIN_URL;
31
+		$this->_admin_base_path = EE_MAINTENANCE_ADMIN;
32
+	}
33
+
34
+
35
+	protected function _ajax_hooks()
36
+	{
37
+		add_action('wp_ajax_migration_step', array($this, 'migration_step'));
38
+		add_action('wp_ajax_add_error_to_migrations_ran', array($this, 'add_error_to_migrations_ran'));
39
+	}
40
+
41
+
42
+	protected function _define_page_props()
43
+	{
44
+		$this->_admin_page_title = EE_MAINTENANCE_LABEL;
45
+		$this->_labels = array(
46
+			'buttons' => array(
47
+				'reset_reservations' => esc_html__('Reset Ticket and Datetime Reserved Counts', 'event_espresso'),
48
+				'reset_capabilities' => esc_html__('Reset Event Espresso Capabilities', 'event_espresso'),
49
+			),
50
+		);
51
+	}
52
+
53
+
54
+	protected function _set_page_routes()
55
+	{
56
+		$this->_page_routes = array(
57
+			'default'                             => array(
58
+				'func'       => '_maintenance',
59
+				'capability' => 'manage_options',
60
+			),
61
+			'change_maintenance_level'            => array(
62
+				'func'       => '_change_maintenance_level',
63
+				'capability' => 'manage_options',
64
+				'noheader'   => true,
65
+			),
66
+			'system_status'                       => array(
67
+				'func'       => '_system_status',
68
+				'capability' => 'manage_options',
69
+			),
70
+			'download_system_status'              => array(
71
+				'func'       => '_download_system_status',
72
+				'capability' => 'manage_options',
73
+				'noheader'   => true,
74
+			),
75
+			'send_migration_crash_report'         => array(
76
+				'func'       => '_send_migration_crash_report',
77
+				'capability' => 'manage_options',
78
+				'noheader'   => true,
79
+			),
80
+			'confirm_migration_crash_report_sent' => array(
81
+				'func'       => '_confirm_migration_crash_report_sent',
82
+				'capability' => 'manage_options',
83
+			),
84
+			'data_reset'                          => array(
85
+				'func'       => '_data_reset_and_delete',
86
+				'capability' => 'manage_options',
87
+			),
88
+			'reset_db'                            => array(
89
+				'func'       => '_reset_db',
90
+				'capability' => 'manage_options',
91
+				'noheader'   => true,
92
+				'args'       => array('nuke_old_ee4_data' => true),
93
+			),
94
+			'start_with_fresh_ee4_db'             => array(
95
+				'func'       => '_reset_db',
96
+				'capability' => 'manage_options',
97
+				'noheader'   => true,
98
+				'args'       => array('nuke_old_ee4_data' => false),
99
+			),
100
+			'delete_db'                           => array(
101
+				'func'       => '_delete_db',
102
+				'capability' => 'manage_options',
103
+				'noheader'   => true,
104
+			),
105
+			'rerun_migration_from_ee3'            => array(
106
+				'func'       => '_rerun_migration_from_ee3',
107
+				'capability' => 'manage_options',
108
+				'noheader'   => true,
109
+			),
110
+			'reset_reservations'                  => array(
111
+				'func'       => '_reset_reservations',
112
+				'capability' => 'manage_options',
113
+				'noheader'   => true,
114
+			),
115
+			'reset_capabilities'                  => array(
116
+				'func'       => '_reset_capabilities',
117
+				'capability' => 'manage_options',
118
+				'noheader'   => true,
119
+			),
120
+			'reattempt_migration'                 => array(
121
+				'func'       => '_reattempt_migration',
122
+				'capability' => 'manage_options',
123
+				'noheader'   => true,
124
+			),
125
+			'datetime_tools'                      => array(
126
+				'func'       => '_datetime_tools',
127
+				'capability' => 'manage_options',
128
+			),
129
+			'run_datetime_offset_fix'             => array(
130
+				'func'               => '_apply_datetime_offset',
131
+				'noheader'           => true,
132
+				'headers_sent_route' => 'datetime_tools',
133
+				'capability'         => 'manage_options',
134
+			),
135
+		);
136
+	}
137
+
138
+
139
+	protected function _set_page_config()
140
+	{
141
+		$this->_page_config = array(
142
+			'default'        => array(
143
+				'nav'           => array(
144
+					'label' => esc_html__('Maintenance', 'event_espresso'),
145
+					'order' => 10,
146
+				),
147
+				'require_nonce' => false,
148
+			),
149
+			'data_reset'     => array(
150
+				'nav'           => array(
151
+					'label' => esc_html__('Reset/Delete Data', 'event_espresso'),
152
+					'order' => 20,
153
+				),
154
+				'require_nonce' => false,
155
+			),
156
+			'datetime_tools' => array(
157
+				'nav'           => array(
158
+					'label' => esc_html__('Datetime Utilities', 'event_espresso'),
159
+					'order' => 25,
160
+				),
161
+				'require_nonce' => false,
162
+			),
163
+			'system_status'  => array(
164
+				'nav'           => array(
165
+					'label' => esc_html__("System Information", "event_espresso"),
166
+					'order' => 30,
167
+				),
168
+				'require_nonce' => false,
169
+			),
170
+		);
171
+	}
172
+
173
+
174
+	/**
175
+	 * default maintenance page. If we're in maintenance mode level 2, then we need to show
176
+	 * the migration scripts and all that UI.
177
+	 */
178
+	public function _maintenance()
179
+	{
180
+		// it all depends if we're in maintenance model level 1 (frontend-only) or
181
+		// level 2 (everything except maintenance page)
182
+		try {
183
+			// get the current maintenance level and check if
184
+			// we are removed
185
+			$mm = EE_Maintenance_Mode::instance()->level();
186
+			$placed_in_mm = EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
187
+			if ($mm == EE_Maintenance_Mode::level_2_complete_maintenance && ! $placed_in_mm) {
188
+				// we just took the site out of maintenance mode, so notify the user.
189
+				// unfortunately this message appears to be echoed on the NEXT page load...
190
+				// oh well, we should really be checking for this on addon deactivation anyways
191
+				EE_Error::add_attention(
192
+					__(
193
+						'Site taken out of maintenance mode because no data migration scripts are required',
194
+						'event_espresso'
195
+					)
196
+				);
197
+				$this->_process_notices(array('page' => 'espresso_maintenance_settings'), false);
198
+			}
199
+			// in case an exception is thrown while trying to handle migrations
200
+			switch (EE_Maintenance_Mode::instance()->level()) {
201
+				case EE_Maintenance_Mode::level_0_not_in_maintenance:
202
+				case EE_Maintenance_Mode::level_1_frontend_only_maintenance:
203
+					$show_maintenance_switch = true;
204
+					$show_backup_db_text = false;
205
+					$show_migration_progress = false;
206
+					$script_names = array();
207
+					$addons_should_be_upgraded_first = false;
208
+					break;
209
+				case EE_Maintenance_Mode::level_2_complete_maintenance:
210
+					$show_maintenance_switch = false;
211
+					$show_migration_progress = true;
212
+					if (isset($this->_req_data['continue_migration'])) {
213
+						$show_backup_db_text = false;
214
+					} else {
215
+						$show_backup_db_text = true;
216
+					}
217
+					$scripts_needing_to_run = EE_Data_Migration_Manager::instance()
218
+																	   ->check_for_applicable_data_migration_scripts();
219
+					$addons_should_be_upgraded_first = EE_Data_Migration_Manager::instance()->addons_need_updating();
220
+					$script_names = array();
221
+					$current_script = null;
222
+					foreach ($scripts_needing_to_run as $script) {
223
+						if ($script instanceof EE_Data_Migration_Script_Base) {
224
+							if (! $current_script) {
225
+								$current_script = $script;
226
+								$current_script->migration_page_hooks();
227
+							}
228
+							$script_names[] = $script->pretty_name();
229
+						}
230
+					}
231
+					break;
232
+			}
233
+			$most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
234
+			$exception_thrown = false;
235
+		} catch (EE_Error $e) {
236
+			EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
237
+			// now, just so we can display the page correctly, make a error migration script stage object
238
+			// and also put the error on it. It only persists for the duration of this request
239
+			$most_recent_migration = new EE_DMS_Unknown_1_0_0();
240
+			$most_recent_migration->add_error($e->getMessage());
241
+			$exception_thrown = true;
242
+		}
243
+		$current_db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set();
244
+		$current_db_state = str_replace('.decaf', '', $current_db_state);
245
+		if ($exception_thrown
246
+			|| ($most_recent_migration
247
+				&& $most_recent_migration instanceof EE_Data_Migration_Script_Base
248
+				&& $most_recent_migration->is_broken()
249
+			)
250
+		) {
251
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
252
+			$this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
253
+			$this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(
254
+				array(
255
+					'action'  => 'confirm_migration_crash_report_sent',
256
+					'success' => '0',
257
+				),
258
+				EE_MAINTENANCE_ADMIN_URL
259
+			);
260
+		} elseif ($addons_should_be_upgraded_first) {
261
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
262
+		} else {
263
+			if ($most_recent_migration
264
+				&& $most_recent_migration instanceof EE_Data_Migration_Script_Base
265
+				&& $most_recent_migration->can_continue()
266
+			) {
267
+				$show_backup_db_text = false;
268
+				$show_continue_current_migration_script = true;
269
+				$show_most_recent_migration = true;
270
+			} elseif (isset($this->_req_data['continue_migration'])) {
271
+				$show_most_recent_migration = true;
272
+				$show_continue_current_migration_script = false;
273
+			} else {
274
+				$show_most_recent_migration = false;
275
+				$show_continue_current_migration_script = false;
276
+			}
277
+			if (isset($current_script)) {
278
+				$migrates_to = $current_script->migrates_to_version();
279
+				$plugin_slug = $migrates_to['slug'];
280
+				$new_version = $migrates_to['version'];
281
+				$this->_template_args = array_merge(
282
+					$this->_template_args,
283
+					array(
284
+						'current_db_state' => sprintf(
285
+							__("EE%s (%s)", "event_espresso"),
286
+							isset($current_db_state[ $plugin_slug ]) ? $current_db_state[ $plugin_slug ] : 3,
287
+							$plugin_slug
288
+						),
289
+						'next_db_state'    => isset($current_script) ? sprintf(
290
+							__("EE%s (%s)", 'event_espresso'),
291
+							$new_version,
292
+							$plugin_slug
293
+						) : null,
294
+					)
295
+				);
296
+			} else {
297
+				$this->_template_args['current_db_state'] = null;
298
+				$this->_template_args['next_db_state'] = null;
299
+			}
300
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
301
+			$this->_template_args = array_merge(
302
+				$this->_template_args,
303
+				array(
304
+					'show_most_recent_migration'             => $show_most_recent_migration,
305
+					// flag for showing the most recent migration's status and/or errors
306
+					'show_migration_progress'                => $show_migration_progress,
307
+					// flag for showing the option to run migrations and see their progress
308
+					'show_backup_db_text'                    => $show_backup_db_text,
309
+					// flag for showing text telling the user to backup their DB
310
+					'show_maintenance_switch'                => $show_maintenance_switch,
311
+					// flag for showing the option to change maintenance mode between levels 0 and 1
312
+					'script_names'                           => $script_names,
313
+					// array of names of scripts that have run
314
+					'show_continue_current_migration_script' => $show_continue_current_migration_script,
315
+					// flag to change wording to indicating that we're only CONTINUING a migration script (somehow it got interrupted0
316
+					'reset_db_page_link'                     => EE_Admin_Page::add_query_args_and_nonce(
317
+						array('action' => 'reset_db'),
318
+						EE_MAINTENANCE_ADMIN_URL
319
+					),
320
+					'data_reset_page'                        => EE_Admin_Page::add_query_args_and_nonce(
321
+						array('action' => 'data_reset'),
322
+						EE_MAINTENANCE_ADMIN_URL
323
+					),
324
+					'update_migration_script_page_link'      => EE_Admin_Page::add_query_args_and_nonce(
325
+						array('action' => 'change_maintenance_level'),
326
+						EE_MAINTENANCE_ADMIN_URL
327
+					),
328
+					'ultimate_db_state'                      => sprintf(
329
+						__("EE%s", 'event_espresso'),
330
+						espresso_version()
331
+					),
332
+				)
333
+			);
334
+			// make sure we have the form fields helper available. It usually is, but sometimes it isn't
335
+		}
336
+		$this->_template_args['most_recent_migration'] = $most_recent_migration;// the actual most recently ran migration
337
+		// now render the migration options part, and put it in a variable
338
+		$migration_options_template_file = apply_filters(
339
+			'FHEE__ee_migration_page__migration_options_template',
340
+			EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee4.template.php'
341
+		);
342
+		$migration_options_html = EEH_Template::display_template(
343
+			$migration_options_template_file,
344
+			$this->_template_args,
345
+			true
346
+		);
347
+		$this->_template_args['migration_options_html'] = $migration_options_html;
348
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
349
+			$this->_template_path,
350
+			$this->_template_args,
351
+			true
352
+		);
353
+		$this->display_admin_page_with_sidebar();
354
+	}
355
+
356
+
357
+	/**
358
+	 * returns JSON and executes another step of the currently-executing data migration (called via ajax)
359
+	 */
360
+	public function migration_step()
361
+	{
362
+		$this->_template_args['data'] = EE_Data_Migration_Manager::instance()->response_to_migration_ajax_request();
363
+		$this->_return_json();
364
+	}
365
+
366
+
367
+	/**
368
+	 * Can be used by js when it notices a response with HTML in it in order
369
+	 * to log the malformed response
370
+	 */
371
+	public function add_error_to_migrations_ran()
372
+	{
373
+		EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($this->_req_data['message']);
374
+		$this->_template_args['data'] = array('ok' => true);
375
+		$this->_return_json();
376
+	}
377
+
378
+
379
+	/**
380
+	 * changes the maintenance level, provided there are still no migration scripts that should run
381
+	 */
382
+	public function _change_maintenance_level()
383
+	{
384
+		$new_level = absint($this->_req_data['maintenance_mode_level']);
385
+		if (! EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
386
+			EE_Maintenance_Mode::instance()->set_maintenance_level($new_level);
387
+			$success = true;
388
+		} else {
389
+			EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
390
+			$success = false;
391
+		}
392
+		$this->_redirect_after_action($success, 'Maintenance Mode', esc_html__("Updated", "event_espresso"));
393
+	}
394
+
395
+
396
+	/**
397
+	 * a tab with options for resetting and/or deleting EE data
398
+	 *
399
+	 * @throws \EE_Error
400
+	 * @throws \DomainException
401
+	 */
402
+	public function _data_reset_and_delete()
403
+	{
404
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
405
+		$this->_template_args['reset_reservations_button'] = $this->get_action_link_or_button(
406
+			'reset_reservations',
407
+			'reset_reservations',
408
+			array(),
409
+			'button button-primary ee-confirm',
410
+			'',
411
+			false
412
+		);
413
+		$this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
414
+			'reset_capabilities',
415
+			'reset_capabilities',
416
+			array(),
417
+			'button button-primary ee-confirm',
418
+			'',
419
+			false
420
+		);
421
+		$this->_template_args['delete_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
422
+			array('action' => 'delete_db'),
423
+			EE_MAINTENANCE_ADMIN_URL
424
+		);
425
+		$this->_template_args['reset_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
426
+			array('action' => 'reset_db'),
427
+			EE_MAINTENANCE_ADMIN_URL
428
+		);
429
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
430
+			$this->_template_path,
431
+			$this->_template_args,
432
+			true
433
+		);
434
+		$this->display_admin_page_with_sidebar();
435
+	}
436
+
437
+
438
+	protected function _reset_reservations()
439
+	{
440
+		if (\EED_Ticket_Sales_Monitor::reset_reservation_counts()) {
441
+			EE_Error::add_success(
442
+				__(
443
+					'Ticket and datetime reserved counts have been successfully reset.',
444
+					'event_espresso'
445
+				)
446
+			);
447
+		} else {
448
+			EE_Error::add_success(
449
+				__(
450
+					'Ticket and datetime reserved counts were correct and did not need resetting.',
451
+					'event_espresso'
452
+				)
453
+			);
454
+		}
455
+		$this->_redirect_after_action(true, '', '', array('action' => 'data_reset'), true);
456
+	}
457
+
458
+
459
+	protected function _reset_capabilities()
460
+	{
461
+		EE_Registry::instance()->CAP->init_caps(true);
462
+		EE_Error::add_success(
463
+			__(
464
+				'Default Event Espresso capabilities have been restored for all current roles.',
465
+				'event_espresso'
466
+			)
467
+		);
468
+		$this->_redirect_after_action(false, '', '', array('action' => 'data_reset'), true);
469
+	}
470
+
471
+
472
+	/**
473
+	 * resets the DMSs so we can attempt to continue migrating after a fatal error
474
+	 * (only a good idea when someone has somehow tried ot fix whatever caused
475
+	 * the fatal error in teh first place)
476
+	 */
477
+	protected function _reattempt_migration()
478
+	{
479
+		EE_Data_Migration_Manager::instance()->reattempt();
480
+		$this->_redirect_after_action(false, '', '', array('action' => 'default'), true);
481
+	}
482
+
483
+
484
+	/**
485
+	 * shows the big ol' System Information page
486
+	 */
487
+	public function _system_status()
488
+	{
489
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
490
+		$this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
491
+		$this->_template_args['download_system_status_url'] = EE_Admin_Page::add_query_args_and_nonce(
492
+			array(
493
+				'action' => 'download_system_status',
494
+			),
495
+			EE_MAINTENANCE_ADMIN_URL
496
+		);
497
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
498
+			$this->_template_path,
499
+			$this->_template_args,
500
+			true
501
+		);
502
+		$this->display_admin_page_with_sidebar();
503
+	}
504
+
505
+	/**
506
+	 * Downloads an HTML file of the system status that can be easily stored or emailed
507
+	 */
508
+	public function _download_system_status()
509
+	{
510
+		$status_info = EEM_System_Status::instance()->get_system_stati();
511
+		header('Content-Disposition: attachment');
512
+		header("Content-Disposition: attachment; filename=system_status_" . sanitize_key(site_url()) . ".html");
513
+		echo "<style>table{border:1px solid darkgrey;}td{vertical-align:top}</style>";
514
+		echo "<h1>System Information for " . site_url() . "</h1>";
515
+		echo EEH_Template::layout_array_as_table($status_info);
516
+		die;
517
+	}
518
+
519
+
520
+	public function _send_migration_crash_report()
521
+	{
522
+		$from = $this->_req_data['from'];
523
+		$from_name = $this->_req_data['from_name'];
524
+		$body = $this->_req_data['body'];
525
+		try {
526
+			$success = wp_mail(
527
+				EE_SUPPORT_EMAIL,
528
+				'Migration Crash Report',
529
+				$body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
530
+				array(
531
+					"from:$from_name<$from>",
532
+				)
533
+			);
534
+		} catch (Exception $e) {
535
+			$success = false;
536
+		}
537
+		$this->_redirect_after_action(
538
+			$success,
539
+			esc_html__("Migration Crash Report", "event_espresso"),
540
+			esc_html__("sent", "event_espresso"),
541
+			array('success' => $success, 'action' => 'confirm_migration_crash_report_sent')
542
+		);
543
+	}
544
+
545
+
546
+	public function _confirm_migration_crash_report_sent()
547
+	{
548
+		try {
549
+			$most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
550
+		} catch (EE_Error $e) {
551
+			EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
552
+			// now, just so we can display the page correctly, make a error migration script stage object
553
+			// and also put the error on it. It only persists for the duration of this request
554
+			$most_recent_migration = new EE_DMS_Unknown_1_0_0();
555
+			$most_recent_migration->add_error($e->getMessage());
556
+		}
557
+		$success = $this->_req_data['success'] == '1' ? true : false;
558
+		$this->_template_args['success'] = $success;
559
+		$this->_template_args['most_recent_migration'] = $most_recent_migration;
560
+		$this->_template_args['reset_db_action_url'] = EE_Admin_Page::add_query_args_and_nonce(
561
+			array('action' => 'reset_db'),
562
+			EE_MAINTENANCE_ADMIN_URL
563
+		);
564
+		$this->_template_args['reset_db_page_url'] = EE_Admin_Page::add_query_args_and_nonce(
565
+			array('action' => 'data_reset'),
566
+			EE_MAINTENANCE_ADMIN_URL
567
+		);
568
+		$this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(
569
+			array('action' => 'reattempt_migration'),
570
+			EE_MAINTENANCE_ADMIN_URL
571
+		);
572
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
573
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
574
+			$this->_template_path,
575
+			$this->_template_args,
576
+			true
577
+		);
578
+		$this->display_admin_page_with_sidebar();
579
+	}
580
+
581
+
582
+	/**
583
+	 * Resets the entire EE4 database.
584
+	 * Currently basically only sets up ee4 database for a fresh install- doesn't
585
+	 * actually clean out the old wp options, or cpts (although does erase old ee table data)
586
+	 *
587
+	 * @param boolean $nuke_old_ee4_data controls whether or not we
588
+	 *                                   destroy the old ee4 data, or just try initializing ee4 default data
589
+	 */
590
+	public function _reset_db($nuke_old_ee4_data = true)
591
+	{
592
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
593
+		if ($nuke_old_ee4_data) {
594
+			EEH_Activation::delete_all_espresso_cpt_data();
595
+			EEH_Activation::delete_all_espresso_tables_and_data(false);
596
+			EEH_Activation::remove_cron_tasks();
597
+		}
598
+		// make sure when we reset the registry's config that it
599
+		// switches to using the new singleton
600
+		EE_Registry::instance()->CFG = EE_Registry::instance()->CFG->reset(true);
601
+		EE_System::instance()->initialize_db_if_no_migrations_required(true);
602
+		EE_System::instance()->redirect_to_about_ee();
603
+	}
604
+
605
+
606
+	/**
607
+	 * Deletes ALL EE tables, Records, and Options from the database.
608
+	 */
609
+	public function _delete_db()
610
+	{
611
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
612
+		EEH_Activation::delete_all_espresso_cpt_data();
613
+		EEH_Activation::delete_all_espresso_tables_and_data();
614
+		EEH_Activation::remove_cron_tasks();
615
+		EEH_Activation::deactivate_event_espresso();
616
+		wp_safe_redirect(admin_url('plugins.php'));
617
+		exit;
618
+	}
619
+
620
+
621
+	/**
622
+	 * sets up EE4 to rerun the migrations from ee3 to ee4
623
+	 */
624
+	public function _rerun_migration_from_ee3()
625
+	{
626
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
627
+		EEH_Activation::delete_all_espresso_cpt_data();
628
+		EEH_Activation::delete_all_espresso_tables_and_data(false);
629
+		// set the db state to something that will require migrations
630
+		update_option(EE_Data_Migration_Manager::current_database_state, '3.1.36.0');
631
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_2_complete_maintenance);
632
+		$this->_redirect_after_action(
633
+			true,
634
+			esc_html__("Database", 'event_espresso'),
635
+			esc_html__("reset", 'event_espresso')
636
+		);
637
+	}
638
+
639
+
640
+	// none of the below group are currently used for Gateway Settings
641
+	protected function _add_screen_options()
642
+	{
643
+	}
644
+
645
+
646
+	protected function _add_feature_pointers()
647
+	{
648
+	}
649
+
650
+
651
+	public function admin_init()
652
+	{
653
+	}
654
+
655
+
656
+	public function admin_notices()
657
+	{
658
+	}
659
+
660
+
661
+	public function admin_footer_scripts()
662
+	{
663
+	}
664
+
665
+
666
+	public function load_scripts_styles()
667
+	{
668
+		wp_enqueue_script('ee_admin_js');
669
+		wp_enqueue_script(
670
+			'ee-maintenance',
671
+			EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.js',
672
+			array('jquery'),
673
+			EVENT_ESPRESSO_VERSION,
674
+			true
675
+		);
676
+		wp_register_style(
677
+			'espresso_maintenance',
678
+			EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css',
679
+			array(),
680
+			EVENT_ESPRESSO_VERSION
681
+		);
682
+		wp_enqueue_style('espresso_maintenance');
683
+		// localize script stuff
684
+		wp_localize_script(
685
+			'ee-maintenance',
686
+			'ee_maintenance',
687
+			array(
688
+				'migrating'                        => wp_strip_all_tags(__("Updating Database...", "event_espresso")),
689
+				'next'                             => wp_strip_all_tags(__("Next", "event_espresso")),
690
+				'fatal_error'                      => wp_strip_all_tags(__("A Fatal Error Has Occurred", "event_espresso")),
691
+				'click_next_when_ready'            => wp_strip_all_tags(
692
+					__(
693
+						"The current Database Update has ended. Click 'next' when ready to proceed",
694
+						"event_espresso"
695
+					)
696
+				),
697
+				'status_no_more_migration_scripts' => EE_Data_Migration_Manager::status_no_more_migration_scripts,
698
+				'status_fatal_error'               => EE_Data_Migration_Manager::status_fatal_error,
699
+				'status_completed'                 => EE_Data_Migration_Manager::status_completed,
700
+				'confirm'                          => wp_strip_all_tags(
701
+					__(
702
+						'Are you sure you want to do this? It CANNOT be undone!',
703
+						'event_espresso'
704
+					)
705
+				),
706
+				'confirm_skip_migration'           => wp_strip_all_tags(
707
+					__(
708
+						'You have chosen to NOT migrate your existing data. Are you sure you want to continue?',
709
+						'event_espresso'
710
+					)
711
+				),
712
+			)
713
+		);
714
+	}
715
+
716
+
717
+	public function load_scripts_styles_default()
718
+	{
719
+	}
720
+
721
+
722
+	/**
723
+	 * Enqueue scripts and styles for the datetime tools page.
724
+	 */
725
+	public function load_scripts_styles_datetime_tools()
726
+	{
727
+		EE_Datepicker_Input::enqueue_styles_and_scripts();
728
+	}
729
+
730
+
731
+	protected function _datetime_tools()
732
+	{
733
+		$form_action = EE_Admin_Page::add_query_args_and_nonce(
734
+			array(
735
+				'action'        => 'run_datetime_offset_fix',
736
+				'return_action' => $this->_req_action,
737
+			),
738
+			EE_MAINTENANCE_ADMIN_URL
739
+		);
740
+		$form = $this->_get_datetime_offset_fix_form();
741
+		$this->_admin_page_title = esc_html__('Datetime Utilities', 'event_espresso');
742
+		$this->_template_args['admin_page_content'] = $form->form_open($form_action, 'post')
743
+													  . $form->get_html_and_js()
744
+													  . $form->form_close();
745
+		$this->display_admin_page_with_no_sidebar();
746
+	}
747
+
748
+
749
+	protected function _get_datetime_offset_fix_form()
750
+	{
751
+		if (! $this->datetime_fix_offset_form instanceof EE_Form_Section_Proper) {
752
+			$this->datetime_fix_offset_form = new EE_Form_Section_Proper(
753
+				array(
754
+					'name'            => 'datetime_offset_fix_option',
755
+					'layout_strategy' => new EE_Admin_Two_Column_Layout(),
756
+					'subsections'     => array(
757
+						'title'                  => new EE_Form_Section_HTML(
758
+							EEH_HTML::h2(
759
+								esc_html__('Datetime Offset Tool', 'event_espresso')
760
+							)
761
+						),
762
+						'explanation'            => new EE_Form_Section_HTML(
763
+							EEH_HTML::p(
764
+								esc_html__(
765
+									'Use this tool to automatically apply the provided offset to all Event Espresso records in your database that involve dates and times.',
766
+									'event_espresso'
767
+								)
768
+							)
769
+							. EEH_HTML::p(
770
+								esc_html__(
771
+									'Note: If you enter 1.25, that will result in the offset of 1 hour 15 minutes being applied.  Decimals represent the fraction of hours, not minutes.',
772
+									'event_espresso'
773
+								)
774
+							)
775
+						),
776
+						'offset_input'           => new EE_Float_Input(
777
+							array(
778
+								'html_name'       => 'offset_for_datetimes',
779
+								'html_label_text' => esc_html__(
780
+									'Offset to apply (in hours):',
781
+									'event_espresso'
782
+								),
783
+								'min_value'       => '-12',
784
+								'max_value'       => '14',
785
+								'step_value'      => '.25',
786
+								'default'         => DatetimeOffsetFix::getOffset(),
787
+							)
788
+						),
789
+						'date_range_explanation' => new EE_Form_Section_HTML(
790
+							EEH_HTML::p(
791
+								esc_html__(
792
+									'Leave the following fields blank if you want the offset to be applied to all dates. If however, you want to just apply the offset to a specific range of dates you can restrict the offset application using these fields.',
793
+									'event_espresso'
794
+								)
795
+							)
796
+							. EEH_HTML::p(
797
+								EEH_HTML::strong(
798
+									sprintf(
799
+										esc_html__(
800
+											'Note: please enter the dates in UTC (You can use %1$sthis online tool%2$s to assist with conversions).',
801
+											'event_espresso'
802
+										),
803
+										'<a href="https://www.timeanddate.com/worldclock/converter.html">',
804
+										'</a>'
805
+									)
806
+								)
807
+							)
808
+						),
809
+						'date_range_start_date'  => new EE_Datepicker_Input(
810
+							array(
811
+								'html_name'       => 'offset_date_start_range',
812
+								'html_label_text' => esc_html__(
813
+									'Start Date for dates the offset applied to:',
814
+									'event_espresso'
815
+								),
816
+							)
817
+						),
818
+						'date_range_end_date'    => new EE_Datepicker_Input(
819
+							array(
820
+								'html_name'       => 'offset_date_end_range',
821
+								'html_label_text' => esc_html__(
822
+									'End Date for dates the offset is applied to:',
823
+									'event_espresso'
824
+								),
825
+							)
826
+						),
827
+						'submit'                 => new EE_Submit_Input(
828
+							array(
829
+								'html_label_text' => '',
830
+								'default'         => esc_html__('Apply Offset', 'event_espresso'),
831
+							)
832
+						),
833
+					),
834
+				)
835
+			);
836
+		}
837
+		return $this->datetime_fix_offset_form;
838
+	}
839
+
840
+
841
+	/**
842
+	 * Callback for the run_datetime_offset_fix route.
843
+	 *
844
+	 * @throws EE_Error
845
+	 */
846
+	protected function _apply_datetime_offset()
847
+	{
848
+		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
849
+			$form = $this->_get_datetime_offset_fix_form();
850
+			$form->receive_form_submission($this->_req_data);
851
+			if ($form->is_valid()) {
852
+				// save offset data so batch processor can get it.
853
+				DatetimeOffsetFix::updateOffset($form->get_input_value('offset_input'));
854
+				$utc_timezone = new DateTimeZone('UTC');
855
+				$date_range_start_date = DateTime::createFromFormat(
856
+					'm/d/Y H:i:s',
857
+					$form->get_input_value('date_range_start_date') . ' 00:00:00',
858
+					$utc_timezone
859
+				);
860
+				$date_range_end_date = DateTime::createFromFormat(
861
+					'm/d/Y H:i:s',
862
+					$form->get_input_value('date_range_end_date') . ' 23:59:59',
863
+					$utc_timezone
864
+				);
865
+				if ($date_range_start_date instanceof DateTime) {
866
+					DatetimeOffsetFix::updateStartDateRange(DbSafeDateTime::createFromDateTime($date_range_start_date));
867
+				}
868
+				if ($date_range_end_date instanceof DateTime) {
869
+					DatetimeOffsetFix::updateEndDateRange(DbSafeDateTime::createFromDateTime($date_range_end_date));
870
+				}
871
+				// redirect to batch tool
872
+				wp_redirect(
873
+					EE_Admin_Page::add_query_args_and_nonce(
874
+						array(
875
+							'page'        => 'espresso_batch',
876
+							'batch'       => 'job',
877
+							'label'       => esc_html__('Applying Offset', 'event_espresso'),
878
+							'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\DatetimeOffsetFix'),
879
+							'return_url'  => urlencode(
880
+								add_query_arg(
881
+									array(
882
+										'action' => 'datetime_tools',
883
+									),
884
+									EEH_URL::current_url_without_query_paramaters(
885
+										array(
886
+											'return_action',
887
+											'run_datetime_offset_fix_nonce',
888
+											'return',
889
+											'datetime_tools_nonce',
890
+										)
891
+									)
892
+								)
893
+							),
894
+						),
895
+						admin_url()
896
+					)
897
+				);
898
+				exit;
899
+			}
900
+		}
901
+	}
902 902
 }
Please login to merge, or discard this patch.
caffeinated/modules/recaptcha_invisible/InvisibleRecaptcha.php 1 patch
Indentation   +240 added lines, -240 removed lines patch added patch discarded remove patch
@@ -27,270 +27,270 @@
 block discarded – undo
27 27
 class InvisibleRecaptcha
28 28
 {
29 29
 
30
-    const URL_GOOGLE_RECAPTCHA_API          = 'https://www.google.com/recaptcha/api/siteverify';
30
+	const URL_GOOGLE_RECAPTCHA_API          = 'https://www.google.com/recaptcha/api/siteverify';
31 31
 
32
-    const SESSION_DATA_KEY_RECAPTCHA_PASSED = 'recaptcha_passed';
32
+	const SESSION_DATA_KEY_RECAPTCHA_PASSED = 'recaptcha_passed';
33 33
 
34
-    /**
35
-     * @var EE_Registration_Config $config
36
-     */
37
-    private $config;
34
+	/**
35
+	 * @var EE_Registration_Config $config
36
+	 */
37
+	private $config;
38 38
 
39
-    /**
40
-     * @var EE_Session $session
41
-     */
42
-    private $session;
39
+	/**
40
+	 * @var EE_Session $session
41
+	 */
42
+	private $session;
43 43
 
44
-    /**
45
-     * @var boolean $recaptcha_passed
46
-     */
47
-    private $recaptcha_passed;
44
+	/**
45
+	 * @var boolean $recaptcha_passed
46
+	 */
47
+	private $recaptcha_passed;
48 48
 
49 49
 
50
-    /**
51
-     * InvisibleRecaptcha constructor.
52
-     *
53
-     * @param EE_Registration_Config $registration_config
54
-     * @param EE_Session             $session
55
-     */
56
-    public function __construct(EE_Registration_Config $registration_config, EE_Session $session)
57
-    {
58
-        $this->config = $registration_config;
59
-        $this->session = $session;
60
-    }
50
+	/**
51
+	 * InvisibleRecaptcha constructor.
52
+	 *
53
+	 * @param EE_Registration_Config $registration_config
54
+	 * @param EE_Session             $session
55
+	 */
56
+	public function __construct(EE_Registration_Config $registration_config, EE_Session $session)
57
+	{
58
+		$this->config = $registration_config;
59
+		$this->session = $session;
60
+	}
61 61
 
62 62
 
63
-    /**
64
-     * @return boolean
65
-     */
66
-    public function useInvisibleRecaptcha()
67
-    {
68
-        return $this->config->use_captcha && $this->config->recaptcha_theme === 'invisible';
69
-    }
63
+	/**
64
+	 * @return boolean
65
+	 */
66
+	public function useInvisibleRecaptcha()
67
+	{
68
+		return $this->config->use_captcha && $this->config->recaptcha_theme === 'invisible';
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * @param array $input_settings
74
-     * @return EE_Invisible_Recaptcha_Input
75
-     * @throws InvalidDataTypeException
76
-     * @throws InvalidInterfaceException
77
-     * @throws InvalidArgumentException
78
-     * @throws DomainException
79
-     */
80
-    public function getInput(array $input_settings = array())
81
-    {
82
-        return new EE_Invisible_Recaptcha_Input(
83
-            $input_settings,
84
-            $this->config
85
-        );
86
-    }
72
+	/**
73
+	 * @param array $input_settings
74
+	 * @return EE_Invisible_Recaptcha_Input
75
+	 * @throws InvalidDataTypeException
76
+	 * @throws InvalidInterfaceException
77
+	 * @throws InvalidArgumentException
78
+	 * @throws DomainException
79
+	 */
80
+	public function getInput(array $input_settings = array())
81
+	{
82
+		return new EE_Invisible_Recaptcha_Input(
83
+			$input_settings,
84
+			$this->config
85
+		);
86
+	}
87 87
 
88 88
 
89
-    /**
90
-     * @param array $input_settings
91
-     * @return string
92
-     * @throws EE_Error
93
-     * @throws InvalidDataTypeException
94
-     * @throws InvalidInterfaceException
95
-     * @throws InvalidArgumentException
96
-     * @throws DomainException
97
-     */
98
-    public function getInputHtml(array $input_settings = array())
99
-    {
100
-        return $this->getInput($input_settings)->get_html_for_input();
101
-    }
89
+	/**
90
+	 * @param array $input_settings
91
+	 * @return string
92
+	 * @throws EE_Error
93
+	 * @throws InvalidDataTypeException
94
+	 * @throws InvalidInterfaceException
95
+	 * @throws InvalidArgumentException
96
+	 * @throws DomainException
97
+	 */
98
+	public function getInputHtml(array $input_settings = array())
99
+	{
100
+		return $this->getInput($input_settings)->get_html_for_input();
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     * @param EE_Form_Section_Proper $form
106
-     * @param array                  $input_settings
107
-     * @throws EE_Error
108
-     * @throws InvalidArgumentException
109
-     * @throws InvalidDataTypeException
110
-     * @throws InvalidInterfaceException
111
-     * @throws DomainException
112
-     */
113
-    public function addToFormSection(EE_Form_Section_Proper $form, array $input_settings = array())
114
-    {
115
-        $form->add_subsections(
116
-            array(
117
-                'espresso_recaptcha' => $this->getInput($input_settings),
118
-            ),
119
-            null,
120
-            false
121
-        );
122
-    }
104
+	/**
105
+	 * @param EE_Form_Section_Proper $form
106
+	 * @param array                  $input_settings
107
+	 * @throws EE_Error
108
+	 * @throws InvalidArgumentException
109
+	 * @throws InvalidDataTypeException
110
+	 * @throws InvalidInterfaceException
111
+	 * @throws DomainException
112
+	 */
113
+	public function addToFormSection(EE_Form_Section_Proper $form, array $input_settings = array())
114
+	{
115
+		$form->add_subsections(
116
+			array(
117
+				'espresso_recaptcha' => $this->getInput($input_settings),
118
+			),
119
+			null,
120
+			false
121
+		);
122
+	}
123 123
 
124 124
 
125
-    /**
126
-     * @param RequestInterface $request
127
-     * @return boolean
128
-     * @throws InvalidArgumentException
129
-     * @throws InvalidDataTypeException
130
-     * @throws InvalidInterfaceException
131
-     * @throws RuntimeException
132
-     */
133
-    public function verifyToken(RequestInterface $request)
134
-    {
135
-        static $previous_recaptcha_response = array();
136
-        $grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137
-        // if this token has already been verified, then return previous response
138
-        if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
-            return $previous_recaptcha_response[ $grecaptcha_response ];
140
-        }
141
-        // still here but no g-recaptcha-response ? - verification failed
142
-        if (! $grecaptcha_response) {
143
-            EE_Error::add_error(
144
-                sprintf(
145
-                    /* translators: 1: missing parameter */
146
-                    esc_html__(
147
-                        // @codingStandardsIgnoreStart
148
-                        'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Missing "%1$s". Please try again.',
149
-                        // @codingStandardsIgnoreEnd
150
-                        'event_espresso'
151
-                    ),
152
-                    'g-recaptcha-response'
153
-                ),
154
-                __FILE__,
155
-                __FUNCTION__,
156
-                __LINE__
157
-            );
158
-            return false;
159
-        }
160
-        // will update to true if everything passes
161
-        $previous_recaptcha_response[ $grecaptcha_response ] = false;
162
-        $response                                            = wp_safe_remote_post(
163
-            InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164
-            array(
165
-                'body' => array(
166
-                    'secret'   => $this->config->recaptcha_privatekey,
167
-                    'response' => $grecaptcha_response,
168
-                    'remoteip' => $request->ipAddress(),
169
-                ),
170
-            )
171
-        );
172
-        if ($response instanceof WP_Error) {
173
-            $this->generateError($response->get_error_messages());
174
-            return false;
175
-        }
176
-        $results = json_decode(wp_remote_retrieve_body($response), true);
177
-        if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
-            $errors   = array_map(
179
-                array($this, 'getErrorCode'),
180
-                $results['error-codes']
181
-            );
182
-            if (isset($results['challenge_ts'])) {
183
-                $errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
184
-            }
185
-            $this->generateError(implode(' ', $errors), true);
186
-        }
187
-        $previous_recaptcha_response[ $grecaptcha_response ] = true;
188
-        add_action('shutdown', array($this, 'setSessionData'));
189
-        return true;
190
-    }
125
+	/**
126
+	 * @param RequestInterface $request
127
+	 * @return boolean
128
+	 * @throws InvalidArgumentException
129
+	 * @throws InvalidDataTypeException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws RuntimeException
132
+	 */
133
+	public function verifyToken(RequestInterface $request)
134
+	{
135
+		static $previous_recaptcha_response = array();
136
+		$grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137
+		// if this token has already been verified, then return previous response
138
+		if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
+			return $previous_recaptcha_response[ $grecaptcha_response ];
140
+		}
141
+		// still here but no g-recaptcha-response ? - verification failed
142
+		if (! $grecaptcha_response) {
143
+			EE_Error::add_error(
144
+				sprintf(
145
+					/* translators: 1: missing parameter */
146
+					esc_html__(
147
+						// @codingStandardsIgnoreStart
148
+						'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Missing "%1$s". Please try again.',
149
+						// @codingStandardsIgnoreEnd
150
+						'event_espresso'
151
+					),
152
+					'g-recaptcha-response'
153
+				),
154
+				__FILE__,
155
+				__FUNCTION__,
156
+				__LINE__
157
+			);
158
+			return false;
159
+		}
160
+		// will update to true if everything passes
161
+		$previous_recaptcha_response[ $grecaptcha_response ] = false;
162
+		$response                                            = wp_safe_remote_post(
163
+			InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164
+			array(
165
+				'body' => array(
166
+					'secret'   => $this->config->recaptcha_privatekey,
167
+					'response' => $grecaptcha_response,
168
+					'remoteip' => $request->ipAddress(),
169
+				),
170
+			)
171
+		);
172
+		if ($response instanceof WP_Error) {
173
+			$this->generateError($response->get_error_messages());
174
+			return false;
175
+		}
176
+		$results = json_decode(wp_remote_retrieve_body($response), true);
177
+		if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
+			$errors   = array_map(
179
+				array($this, 'getErrorCode'),
180
+				$results['error-codes']
181
+			);
182
+			if (isset($results['challenge_ts'])) {
183
+				$errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
184
+			}
185
+			$this->generateError(implode(' ', $errors), true);
186
+		}
187
+		$previous_recaptcha_response[ $grecaptcha_response ] = true;
188
+		add_action('shutdown', array($this, 'setSessionData'));
189
+		return true;
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * @param string $error_response
195
-     * @param bool   $show_errors
196
-     * @return void
197
-     * @throws RuntimeException
198
-     */
199
-    public function generateError($error_response = '', $show_errors = false)
200
-    {
201
-        throw new RuntimeException(
202
-            sprintf(
203
-                esc_html__(
204
-                    'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. %1$s %2$s Please try again.',
205
-                    'event_espresso'
206
-                ),
207
-                '<br />',
208
-                $show_errors || current_user_can('manage_options') ? $error_response : ''
209
-            )
210
-        );
211
-    }
193
+	/**
194
+	 * @param string $error_response
195
+	 * @param bool   $show_errors
196
+	 * @return void
197
+	 * @throws RuntimeException
198
+	 */
199
+	public function generateError($error_response = '', $show_errors = false)
200
+	{
201
+		throw new RuntimeException(
202
+			sprintf(
203
+				esc_html__(
204
+					'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. %1$s %2$s Please try again.',
205
+					'event_espresso'
206
+				),
207
+				'<br />',
208
+				$show_errors || current_user_can('manage_options') ? $error_response : ''
209
+			)
210
+		);
211
+	}
212 212
 
213 213
 
214
-    /**
215
-     * @param string $error_code
216
-     * @return string
217
-     */
218
-    public function getErrorCode(&$error_code)
219
-    {
220
-        $error_codes = array(
221
-            'missing-input-secret'   => 'The secret parameter is missing.',
222
-            'invalid-input-secret'   => 'The secret parameter is invalid or malformed.',
223
-            'missing-input-response' => 'The response parameter is missing.',
224
-            'invalid-input-response' => 'The response parameter is invalid or malformed.',
225
-            'bad-request'            => 'The request is invalid or malformed.',
226
-            'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227
-        );
228
-        return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
229
-    }
214
+	/**
215
+	 * @param string $error_code
216
+	 * @return string
217
+	 */
218
+	public function getErrorCode(&$error_code)
219
+	{
220
+		$error_codes = array(
221
+			'missing-input-secret'   => 'The secret parameter is missing.',
222
+			'invalid-input-secret'   => 'The secret parameter is invalid or malformed.',
223
+			'missing-input-response' => 'The response parameter is missing.',
224
+			'invalid-input-response' => 'The response parameter is invalid or malformed.',
225
+			'bad-request'            => 'The request is invalid or malformed.',
226
+			'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227
+		);
228
+		return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
229
+	}
230 230
 
231 231
 
232
-    /**
233
-     * @return array
234
-     * @throws InvalidInterfaceException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidArgumentException
237
-     */
238
-    public function getLocalizedVars()
239
-    {
240
-        return (array) apply_filters(
241
-            'FHEE__EventEspresso_caffeinated_modules_recaptcha_invisible_InvisibleRecaptcha__getLocalizedVars__localized_vars',
242
-            array(
243
-                'siteKey'          => $this->config->recaptcha_publickey,
244
-                'recaptcha_passed' => $this->recaptchaPassed(),
245
-                'wp_debug'         => WP_DEBUG,
246
-                'disable_submit'   => defined('EE_EVENT_QUEUE_BASE_URL'),
247
-                'failed_message'   => wp_strip_all_tags(
248
-                    __(
249
-                        'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Please try again.',
250
-                        'event_espresso'
251
-                    )
252
-                )
253
-            )
254
-        );
255
-    }
232
+	/**
233
+	 * @return array
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidArgumentException
237
+	 */
238
+	public function getLocalizedVars()
239
+	{
240
+		return (array) apply_filters(
241
+			'FHEE__EventEspresso_caffeinated_modules_recaptcha_invisible_InvisibleRecaptcha__getLocalizedVars__localized_vars',
242
+			array(
243
+				'siteKey'          => $this->config->recaptcha_publickey,
244
+				'recaptcha_passed' => $this->recaptchaPassed(),
245
+				'wp_debug'         => WP_DEBUG,
246
+				'disable_submit'   => defined('EE_EVENT_QUEUE_BASE_URL'),
247
+				'failed_message'   => wp_strip_all_tags(
248
+					__(
249
+						'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Please try again.',
250
+						'event_espresso'
251
+					)
252
+				)
253
+			)
254
+		);
255
+	}
256 256
 
257 257
 
258
-    /**
259
-     * @return boolean
260
-     * @throws InvalidInterfaceException
261
-     * @throws InvalidDataTypeException
262
-     * @throws InvalidArgumentException
263
-     */
264
-    public function recaptchaPassed()
265
-    {
266
-        if ($this->recaptcha_passed !== null) {
267
-            return $this->recaptcha_passed;
268
-        }
269
-        // logged in means you have already passed a turing test of sorts
270
-        if ($this->useInvisibleRecaptcha() === false || is_user_logged_in()) {
271
-            $this->recaptcha_passed = true;
272
-            return $this->recaptcha_passed;
273
-        }
274
-        // was test already passed?
275
-        $this->recaptcha_passed = filter_var(
276
-            $this->session->get_session_data(
277
-                InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED
278
-            ),
279
-            FILTER_VALIDATE_BOOLEAN
280
-        );
281
-        return $this->recaptcha_passed;
282
-    }
258
+	/**
259
+	 * @return boolean
260
+	 * @throws InvalidInterfaceException
261
+	 * @throws InvalidDataTypeException
262
+	 * @throws InvalidArgumentException
263
+	 */
264
+	public function recaptchaPassed()
265
+	{
266
+		if ($this->recaptcha_passed !== null) {
267
+			return $this->recaptcha_passed;
268
+		}
269
+		// logged in means you have already passed a turing test of sorts
270
+		if ($this->useInvisibleRecaptcha() === false || is_user_logged_in()) {
271
+			$this->recaptcha_passed = true;
272
+			return $this->recaptcha_passed;
273
+		}
274
+		// was test already passed?
275
+		$this->recaptcha_passed = filter_var(
276
+			$this->session->get_session_data(
277
+				InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED
278
+			),
279
+			FILTER_VALIDATE_BOOLEAN
280
+		);
281
+		return $this->recaptcha_passed;
282
+	}
283 283
 
284 284
 
285
-    /**
286
-     * @throws InvalidArgumentException
287
-     * @throws InvalidDataTypeException
288
-     * @throws InvalidInterfaceException
289
-     */
290
-    public function setSessionData()
291
-    {
292
-        $this->session->set_session_data(
293
-            array(InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED => true)
294
-        );
295
-    }
285
+	/**
286
+	 * @throws InvalidArgumentException
287
+	 * @throws InvalidDataTypeException
288
+	 * @throws InvalidInterfaceException
289
+	 */
290
+	public function setSessionData()
291
+	{
292
+		$this->session->set_session_data(
293
+			array(InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED => true)
294
+		);
295
+	}
296 296
 }
Please login to merge, or discard this patch.
core/services/notifications/PersistentAdminNoticeManager.php 1 patch
Indentation   +383 added lines, -383 removed lines patch added patch discarded remove patch
@@ -31,387 +31,387 @@
 block discarded – undo
31 31
 class PersistentAdminNoticeManager
32 32
 {
33 33
 
34
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
35
-
36
-    /**
37
-     * @var Collection|PersistentAdminNotice[] $notice_collection
38
-     */
39
-    private $notice_collection;
40
-
41
-    /**
42
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
43
-     * persistent admin notice was displayed, and ultimately dismissed from.
44
-     *
45
-     * @var string $return_url
46
-     */
47
-    private $return_url;
48
-
49
-    /**
50
-     * @var CapabilitiesChecker $capabilities_checker
51
-     */
52
-    private $capabilities_checker;
53
-
54
-    /**
55
-     * @var RequestInterface $request
56
-     */
57
-    private $request;
58
-
59
-
60
-    /**
61
-     * PersistentAdminNoticeManager constructor
62
-     *
63
-     * @param string              $return_url where to  redirect to after dismissing notices
64
-     * @param CapabilitiesChecker $capabilities_checker
65
-     * @param RequestInterface          $request
66
-     * @throws InvalidDataTypeException
67
-     */
68
-    public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, RequestInterface $request)
69
-    {
70
-        $this->setReturnUrl($return_url);
71
-        $this->capabilities_checker = $capabilities_checker;
72
-        $this->request = $request;
73
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
-        // and we want to retrieve and generate any nag notices at the last possible moment
75
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
76
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
-    }
80
-
81
-
82
-    /**
83
-     * @param string $return_url
84
-     * @throws InvalidDataTypeException
85
-     */
86
-    public function setReturnUrl($return_url)
87
-    {
88
-        if (! is_string($return_url)) {
89
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90
-        }
91
-        $this->return_url = $return_url;
92
-    }
93
-
94
-
95
-    /**
96
-     * @return Collection
97
-     * @throws InvalidEntityException
98
-     * @throws InvalidInterfaceException
99
-     * @throws InvalidDataTypeException
100
-     * @throws DomainException
101
-     * @throws DuplicateCollectionIdentifierException
102
-     */
103
-    protected function getPersistentAdminNoticeCollection()
104
-    {
105
-        if (! $this->notice_collection instanceof Collection) {
106
-            $this->notice_collection = new Collection(
107
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108
-            );
109
-            $this->retrieveStoredNotices();
110
-            $this->registerNotices();
111
-        }
112
-        return $this->notice_collection;
113
-    }
114
-
115
-
116
-    /**
117
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
118
-     *
119
-     * @return void
120
-     * @throws InvalidEntityException
121
-     * @throws DomainException
122
-     * @throws InvalidDataTypeException
123
-     * @throws DuplicateCollectionIdentifierException
124
-     */
125
-    protected function retrieveStoredNotices()
126
-    {
127
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
-        if (! empty($persistent_admin_notices)) {
129
-            foreach ($persistent_admin_notices as $name => $details) {
130
-                if (is_array($details)) {
131
-                    if (! isset(
132
-                        $details['message'],
133
-                        $details['capability'],
134
-                        $details['cap_context'],
135
-                        $details['dismissed']
136
-                    )) {
137
-                        throw new DomainException(
138
-                            sprintf(
139
-                                esc_html__(
140
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
141
-                                    'event_espresso'
142
-                                ),
143
-                                $name
144
-                            )
145
-                        );
146
-                    }
147
-                    // new format for nag notices
148
-                    $this->notice_collection->add(
149
-                        new PersistentAdminNotice(
150
-                            $name,
151
-                            $details['message'],
152
-                            false,
153
-                            $details['capability'],
154
-                            $details['cap_context'],
155
-                            $details['dismissed']
156
-                        ),
157
-                        sanitize_key($name)
158
-                    );
159
-                } else {
160
-                    try {
161
-                        // old nag notices, that we want to convert to the new format
162
-                        $this->notice_collection->add(
163
-                            new PersistentAdminNotice(
164
-                                $name,
165
-                                (string) $details,
166
-                                false,
167
-                                '',
168
-                                '',
169
-                                empty($details)
170
-                            ),
171
-                            sanitize_key($name)
172
-                        );
173
-                    } catch (Exception $e) {
174
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
175
-                    }
176
-                }
177
-                // each notice will self register when the action hook in registerNotices is triggered
178
-            }
179
-        }
180
-    }
181
-
182
-
183
-    /**
184
-     * exposes the Persistent Admin Notice Collection via an action
185
-     * so that PersistentAdminNotice objects can be added and/or removed
186
-     * without compromising the actual collection like a filter would
187
-     */
188
-    protected function registerNotices()
189
-    {
190
-        do_action(
191
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
192
-            $this->notice_collection
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * @throws DomainException
199
-     * @throws InvalidClassException
200
-     * @throws InvalidDataTypeException
201
-     * @throws InvalidInterfaceException
202
-     * @throws InvalidEntityException
203
-     * @throws DuplicateCollectionIdentifierException
204
-     */
205
-    public function displayNotices()
206
-    {
207
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
208
-        if ($this->notice_collection->hasObjects()) {
209
-            $enqueue_assets = false;
210
-            // and display notices
211
-            foreach ($this->notice_collection as $persistent_admin_notice) {
212
-                /** @var PersistentAdminNotice $persistent_admin_notice */
213
-                // don't display notices that have already been dismissed
214
-                if ($persistent_admin_notice->getDismissed()) {
215
-                    continue;
216
-                }
217
-                try {
218
-                    $this->capabilities_checker->processCapCheck(
219
-                        $persistent_admin_notice->getCapCheck()
220
-                    );
221
-                } catch (InsufficientPermissionsException $e) {
222
-                    // user does not have required cap, so skip to next notice
223
-                    // and just eat the exception - nom nom nom nom
224
-                    continue;
225
-                }
226
-                if ($persistent_admin_notice->getMessage() === '') {
227
-                    continue;
228
-                }
229
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
230
-                $enqueue_assets = true;
231
-            }
232
-            if ($enqueue_assets) {
233
-                $this->enqueueAssets();
234
-            }
235
-        }
236
-    }
237
-
238
-
239
-    /**
240
-     * does what it's named
241
-     *
242
-     * @return void
243
-     */
244
-    public function enqueueAssets()
245
-    {
246
-        wp_register_script(
247
-            'espresso_core',
248
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
249
-            array('jquery'),
250
-            EVENT_ESPRESSO_VERSION,
251
-            true
252
-        );
253
-        wp_register_script(
254
-            'ee_error_js',
255
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
256
-            array('espresso_core'),
257
-            EVENT_ESPRESSO_VERSION,
258
-            true
259
-        );
260
-        wp_localize_script(
261
-            'ee_error_js',
262
-            'ee_dismiss',
263
-            array(
264
-                'return_url'    => urlencode($this->return_url),
265
-                'ajax_url'      => WP_AJAX_URL,
266
-                'unknown_error' => wp_strip_all_tags(
267
-                    __(
268
-                        'An unknown error has occurred on the server while attempting to dismiss this notice.',
269
-                        'event_espresso'
270
-                    )
271
-                ),
272
-            )
273
-        );
274
-        wp_enqueue_script('ee_error_js');
275
-    }
276
-
277
-
278
-    /**
279
-     * displayPersistentAdminNoticeHtml
280
-     *
281
-     * @param  PersistentAdminNotice $persistent_admin_notice
282
-     */
283
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
284
-    {
285
-        // used in template
286
-        $persistent_admin_notice_name = $persistent_admin_notice->getName();
287
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
288
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
289
-    }
290
-
291
-
292
-    /**
293
-     * dismissNotice
294
-     *
295
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
296
-     * @param bool   $purge    if true, then delete it from the db
297
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
298
-     * @return void
299
-     * @throws InvalidEntityException
300
-     * @throws InvalidInterfaceException
301
-     * @throws InvalidDataTypeException
302
-     * @throws DomainException
303
-     * @throws InvalidArgumentException
304
-     * @throws InvalidArgumentException
305
-     * @throws InvalidArgumentException
306
-     * @throws InvalidArgumentException
307
-     * @throws DuplicateCollectionIdentifierException
308
-     */
309
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
310
-    {
311
-        $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
312
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
313
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
314
-            /** @var PersistentAdminNotice $persistent_admin_notice */
315
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
316
-            $persistent_admin_notice->setDismissed(true);
317
-            $persistent_admin_notice->setPurge($purge);
318
-            $this->saveNotices();
319
-        }
320
-        if ($return) {
321
-            return;
322
-        }
323
-        if ($this->request->isAjax()) {
324
-            // grab any notices and concatenate into string
325
-            echo wp_json_encode(
326
-                array(
327
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
328
-                )
329
-            );
330
-            exit();
331
-        }
332
-        // save errors to a transient to be displayed on next request (after redirect)
333
-        EE_Error::get_notices(false, true);
334
-        wp_safe_redirect(
335
-            urldecode(
336
-                $this->request->getRequestParam('return_url', '')
337
-            )
338
-        );
339
-    }
340
-
341
-
342
-    /**
343
-     * saveNotices
344
-     *
345
-     * @throws DomainException
346
-     * @throws InvalidDataTypeException
347
-     * @throws InvalidInterfaceException
348
-     * @throws InvalidEntityException
349
-     * @throws DuplicateCollectionIdentifierException
350
-     */
351
-    public function saveNotices()
352
-    {
353
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
354
-        if ($this->notice_collection->hasObjects()) {
355
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
356
-            // maybe initialize persistent_admin_notices
357
-            if (empty($persistent_admin_notices)) {
358
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
359
-            }
360
-            foreach ($this->notice_collection as $persistent_admin_notice) {
361
-                // are we deleting this notice ?
362
-                if ($persistent_admin_notice->getPurge()) {
363
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
364
-                } else {
365
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
366
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
367
-                        'message'     => $persistent_admin_notice->getMessage(),
368
-                        'capability'  => $persistent_admin_notice->getCapability(),
369
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
370
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
371
-                    );
372
-                }
373
-            }
374
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
375
-        }
376
-    }
377
-
378
-
379
-    /**
380
-     * @throws DomainException
381
-     * @throws InvalidDataTypeException
382
-     * @throws InvalidEntityException
383
-     * @throws InvalidInterfaceException
384
-     * @throws DuplicateCollectionIdentifierException
385
-     */
386
-    public function registerAndSaveNotices()
387
-    {
388
-        $this->getPersistentAdminNoticeCollection();
389
-        $this->registerNotices();
390
-        $this->saveNotices();
391
-        add_filter(
392
-            'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
393
-            '__return_true'
394
-        );
395
-    }
396
-
397
-
398
-    /**
399
-     * @throws DomainException
400
-     * @throws InvalidDataTypeException
401
-     * @throws InvalidEntityException
402
-     * @throws InvalidInterfaceException
403
-     * @throws InvalidArgumentException
404
-     * @throws DuplicateCollectionIdentifierException
405
-     */
406
-    public static function loadRegisterAndSaveNotices()
407
-    {
408
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
409
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
410
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
411
-        );
412
-        // if shutdown has already run, then call registerAndSaveNotices() manually
413
-        if (did_action('shutdown')) {
414
-            $persistent_admin_notice_manager->registerAndSaveNotices();
415
-        }
416
-    }
34
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
35
+
36
+	/**
37
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
38
+	 */
39
+	private $notice_collection;
40
+
41
+	/**
42
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
43
+	 * persistent admin notice was displayed, and ultimately dismissed from.
44
+	 *
45
+	 * @var string $return_url
46
+	 */
47
+	private $return_url;
48
+
49
+	/**
50
+	 * @var CapabilitiesChecker $capabilities_checker
51
+	 */
52
+	private $capabilities_checker;
53
+
54
+	/**
55
+	 * @var RequestInterface $request
56
+	 */
57
+	private $request;
58
+
59
+
60
+	/**
61
+	 * PersistentAdminNoticeManager constructor
62
+	 *
63
+	 * @param string              $return_url where to  redirect to after dismissing notices
64
+	 * @param CapabilitiesChecker $capabilities_checker
65
+	 * @param RequestInterface          $request
66
+	 * @throws InvalidDataTypeException
67
+	 */
68
+	public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, RequestInterface $request)
69
+	{
70
+		$this->setReturnUrl($return_url);
71
+		$this->capabilities_checker = $capabilities_checker;
72
+		$this->request = $request;
73
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
+		// and we want to retrieve and generate any nag notices at the last possible moment
75
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
76
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
+	}
80
+
81
+
82
+	/**
83
+	 * @param string $return_url
84
+	 * @throws InvalidDataTypeException
85
+	 */
86
+	public function setReturnUrl($return_url)
87
+	{
88
+		if (! is_string($return_url)) {
89
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90
+		}
91
+		$this->return_url = $return_url;
92
+	}
93
+
94
+
95
+	/**
96
+	 * @return Collection
97
+	 * @throws InvalidEntityException
98
+	 * @throws InvalidInterfaceException
99
+	 * @throws InvalidDataTypeException
100
+	 * @throws DomainException
101
+	 * @throws DuplicateCollectionIdentifierException
102
+	 */
103
+	protected function getPersistentAdminNoticeCollection()
104
+	{
105
+		if (! $this->notice_collection instanceof Collection) {
106
+			$this->notice_collection = new Collection(
107
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108
+			);
109
+			$this->retrieveStoredNotices();
110
+			$this->registerNotices();
111
+		}
112
+		return $this->notice_collection;
113
+	}
114
+
115
+
116
+	/**
117
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
118
+	 *
119
+	 * @return void
120
+	 * @throws InvalidEntityException
121
+	 * @throws DomainException
122
+	 * @throws InvalidDataTypeException
123
+	 * @throws DuplicateCollectionIdentifierException
124
+	 */
125
+	protected function retrieveStoredNotices()
126
+	{
127
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
+		if (! empty($persistent_admin_notices)) {
129
+			foreach ($persistent_admin_notices as $name => $details) {
130
+				if (is_array($details)) {
131
+					if (! isset(
132
+						$details['message'],
133
+						$details['capability'],
134
+						$details['cap_context'],
135
+						$details['dismissed']
136
+					)) {
137
+						throw new DomainException(
138
+							sprintf(
139
+								esc_html__(
140
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
141
+									'event_espresso'
142
+								),
143
+								$name
144
+							)
145
+						);
146
+					}
147
+					// new format for nag notices
148
+					$this->notice_collection->add(
149
+						new PersistentAdminNotice(
150
+							$name,
151
+							$details['message'],
152
+							false,
153
+							$details['capability'],
154
+							$details['cap_context'],
155
+							$details['dismissed']
156
+						),
157
+						sanitize_key($name)
158
+					);
159
+				} else {
160
+					try {
161
+						// old nag notices, that we want to convert to the new format
162
+						$this->notice_collection->add(
163
+							new PersistentAdminNotice(
164
+								$name,
165
+								(string) $details,
166
+								false,
167
+								'',
168
+								'',
169
+								empty($details)
170
+							),
171
+							sanitize_key($name)
172
+						);
173
+					} catch (Exception $e) {
174
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
175
+					}
176
+				}
177
+				// each notice will self register when the action hook in registerNotices is triggered
178
+			}
179
+		}
180
+	}
181
+
182
+
183
+	/**
184
+	 * exposes the Persistent Admin Notice Collection via an action
185
+	 * so that PersistentAdminNotice objects can be added and/or removed
186
+	 * without compromising the actual collection like a filter would
187
+	 */
188
+	protected function registerNotices()
189
+	{
190
+		do_action(
191
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
192
+			$this->notice_collection
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * @throws DomainException
199
+	 * @throws InvalidClassException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws InvalidInterfaceException
202
+	 * @throws InvalidEntityException
203
+	 * @throws DuplicateCollectionIdentifierException
204
+	 */
205
+	public function displayNotices()
206
+	{
207
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
208
+		if ($this->notice_collection->hasObjects()) {
209
+			$enqueue_assets = false;
210
+			// and display notices
211
+			foreach ($this->notice_collection as $persistent_admin_notice) {
212
+				/** @var PersistentAdminNotice $persistent_admin_notice */
213
+				// don't display notices that have already been dismissed
214
+				if ($persistent_admin_notice->getDismissed()) {
215
+					continue;
216
+				}
217
+				try {
218
+					$this->capabilities_checker->processCapCheck(
219
+						$persistent_admin_notice->getCapCheck()
220
+					);
221
+				} catch (InsufficientPermissionsException $e) {
222
+					// user does not have required cap, so skip to next notice
223
+					// and just eat the exception - nom nom nom nom
224
+					continue;
225
+				}
226
+				if ($persistent_admin_notice->getMessage() === '') {
227
+					continue;
228
+				}
229
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
230
+				$enqueue_assets = true;
231
+			}
232
+			if ($enqueue_assets) {
233
+				$this->enqueueAssets();
234
+			}
235
+		}
236
+	}
237
+
238
+
239
+	/**
240
+	 * does what it's named
241
+	 *
242
+	 * @return void
243
+	 */
244
+	public function enqueueAssets()
245
+	{
246
+		wp_register_script(
247
+			'espresso_core',
248
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
249
+			array('jquery'),
250
+			EVENT_ESPRESSO_VERSION,
251
+			true
252
+		);
253
+		wp_register_script(
254
+			'ee_error_js',
255
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
256
+			array('espresso_core'),
257
+			EVENT_ESPRESSO_VERSION,
258
+			true
259
+		);
260
+		wp_localize_script(
261
+			'ee_error_js',
262
+			'ee_dismiss',
263
+			array(
264
+				'return_url'    => urlencode($this->return_url),
265
+				'ajax_url'      => WP_AJAX_URL,
266
+				'unknown_error' => wp_strip_all_tags(
267
+					__(
268
+						'An unknown error has occurred on the server while attempting to dismiss this notice.',
269
+						'event_espresso'
270
+					)
271
+				),
272
+			)
273
+		);
274
+		wp_enqueue_script('ee_error_js');
275
+	}
276
+
277
+
278
+	/**
279
+	 * displayPersistentAdminNoticeHtml
280
+	 *
281
+	 * @param  PersistentAdminNotice $persistent_admin_notice
282
+	 */
283
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
284
+	{
285
+		// used in template
286
+		$persistent_admin_notice_name = $persistent_admin_notice->getName();
287
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
288
+		require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
289
+	}
290
+
291
+
292
+	/**
293
+	 * dismissNotice
294
+	 *
295
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
296
+	 * @param bool   $purge    if true, then delete it from the db
297
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
298
+	 * @return void
299
+	 * @throws InvalidEntityException
300
+	 * @throws InvalidInterfaceException
301
+	 * @throws InvalidDataTypeException
302
+	 * @throws DomainException
303
+	 * @throws InvalidArgumentException
304
+	 * @throws InvalidArgumentException
305
+	 * @throws InvalidArgumentException
306
+	 * @throws InvalidArgumentException
307
+	 * @throws DuplicateCollectionIdentifierException
308
+	 */
309
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
310
+	{
311
+		$pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
312
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
313
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
314
+			/** @var PersistentAdminNotice $persistent_admin_notice */
315
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
316
+			$persistent_admin_notice->setDismissed(true);
317
+			$persistent_admin_notice->setPurge($purge);
318
+			$this->saveNotices();
319
+		}
320
+		if ($return) {
321
+			return;
322
+		}
323
+		if ($this->request->isAjax()) {
324
+			// grab any notices and concatenate into string
325
+			echo wp_json_encode(
326
+				array(
327
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
328
+				)
329
+			);
330
+			exit();
331
+		}
332
+		// save errors to a transient to be displayed on next request (after redirect)
333
+		EE_Error::get_notices(false, true);
334
+		wp_safe_redirect(
335
+			urldecode(
336
+				$this->request->getRequestParam('return_url', '')
337
+			)
338
+		);
339
+	}
340
+
341
+
342
+	/**
343
+	 * saveNotices
344
+	 *
345
+	 * @throws DomainException
346
+	 * @throws InvalidDataTypeException
347
+	 * @throws InvalidInterfaceException
348
+	 * @throws InvalidEntityException
349
+	 * @throws DuplicateCollectionIdentifierException
350
+	 */
351
+	public function saveNotices()
352
+	{
353
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
354
+		if ($this->notice_collection->hasObjects()) {
355
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
356
+			// maybe initialize persistent_admin_notices
357
+			if (empty($persistent_admin_notices)) {
358
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
359
+			}
360
+			foreach ($this->notice_collection as $persistent_admin_notice) {
361
+				// are we deleting this notice ?
362
+				if ($persistent_admin_notice->getPurge()) {
363
+					unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
364
+				} else {
365
+					/** @var PersistentAdminNotice $persistent_admin_notice */
366
+					$persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
367
+						'message'     => $persistent_admin_notice->getMessage(),
368
+						'capability'  => $persistent_admin_notice->getCapability(),
369
+						'cap_context' => $persistent_admin_notice->getCapContext(),
370
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
371
+					);
372
+				}
373
+			}
374
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
375
+		}
376
+	}
377
+
378
+
379
+	/**
380
+	 * @throws DomainException
381
+	 * @throws InvalidDataTypeException
382
+	 * @throws InvalidEntityException
383
+	 * @throws InvalidInterfaceException
384
+	 * @throws DuplicateCollectionIdentifierException
385
+	 */
386
+	public function registerAndSaveNotices()
387
+	{
388
+		$this->getPersistentAdminNoticeCollection();
389
+		$this->registerNotices();
390
+		$this->saveNotices();
391
+		add_filter(
392
+			'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
393
+			'__return_true'
394
+		);
395
+	}
396
+
397
+
398
+	/**
399
+	 * @throws DomainException
400
+	 * @throws InvalidDataTypeException
401
+	 * @throws InvalidEntityException
402
+	 * @throws InvalidInterfaceException
403
+	 * @throws InvalidArgumentException
404
+	 * @throws DuplicateCollectionIdentifierException
405
+	 */
406
+	public static function loadRegisterAndSaveNotices()
407
+	{
408
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
409
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
410
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
411
+		);
412
+		// if shutdown has already run, then call registerAndSaveNotices() manually
413
+		if (did_action('shutdown')) {
414
+			$persistent_admin_notice_manager->registerAndSaveNotices();
415
+		}
416
+	}
417 417
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page_CPT.core.php 2 patches
Spacing   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
      */
165 165
     protected function getLoader()
166 166
     {
167
-        if (! $this->loader instanceof LoaderInterface) {
167
+        if ( ! $this->loader instanceof LoaderInterface) {
168 168
             $this->loader = LoaderFactory::getLoader();
169 169
         }
170 170
         return $this->loader;
@@ -188,11 +188,11 @@  discard block
 block discarded – undo
188 188
             $this->_cpt_routes
189 189
         );
190 190
         // let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
191
-        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[ $this->_req_data['action'] ])
192
-            ? get_post_type_object($this->_cpt_routes[ $this->_req_data['action'] ])
191
+        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[$this->_req_data['action']])
192
+            ? get_post_type_object($this->_cpt_routes[$this->_req_data['action']])
193 193
             : get_post_type_object($page);
194 194
         // tweak pagenow for page loading.
195
-        if (! $this->_pagenow_map) {
195
+        if ( ! $this->_pagenow_map) {
196 196
             $this->_pagenow_map = array(
197 197
                 'create_new' => 'post-new.php',
198 198
                 'edit'       => 'post.php',
@@ -226,12 +226,12 @@  discard block
 block discarded – undo
226 226
     {
227 227
         global $pagenow, $hook_suffix;
228 228
         // possibly reset pagenow.
229
-        if (! empty($this->_req_data['page'])
229
+        if ( ! empty($this->_req_data['page'])
230 230
             && $this->_req_data['page'] == $this->page_slug
231 231
             && ! empty($this->_req_data['action'])
232
-            && isset($this->_pagenow_map[ $this->_req_data['action'] ])
232
+            && isset($this->_pagenow_map[$this->_req_data['action']])
233 233
         ) {
234
-            $pagenow = $this->_pagenow_map[ $this->_req_data['action'] ];
234
+            $pagenow = $this->_pagenow_map[$this->_req_data['action']];
235 235
             $hook_suffix = $pagenow;
236 236
         }
237 237
     }
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
         if (empty($wp_meta_boxes)) {
264 264
             return;
265 265
         }
266
-        $current_metaboxes = isset($wp_meta_boxes[ $this->page_slug ]) ? $wp_meta_boxes[ $this->page_slug ] : array();
266
+        $current_metaboxes = isset($wp_meta_boxes[$this->page_slug]) ? $wp_meta_boxes[$this->page_slug] : array();
267 267
         foreach ($current_metaboxes as $box_context) {
268 268
             foreach ($box_context as $box_details) {
269 269
                 foreach ($box_details as $box) {
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
             $this
297 297
         );
298 298
         $containers = apply_filters(
299
-            'FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
299
+            'FHEE__EE_Admin_Page_CPT__'.get_class($this).'___load_autosave_scripts_styles__containers',
300 300
             $containers,
301 301
             $this
302 302
         );
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
     protected function _load_page_dependencies()
343 343
     {
344 344
         // we only add stuff if this is a cpt_route!
345
-        if (! $this->_cpt_route) {
345
+        if ( ! $this->_cpt_route) {
346 346
             parent::_load_page_dependencies();
347 347
             return;
348 348
         }
@@ -366,16 +366,16 @@  discard block
 block discarded – undo
366 366
         add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
367 367
         // This basically allows us to change the title of the "publish" metabox area
368 368
         // on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
369
-        if (! empty($this->_labels['publishbox'])) {
369
+        if ( ! empty($this->_labels['publishbox'])) {
370 370
             $box_label = is_array($this->_labels['publishbox'])
371
-                         && isset($this->_labels['publishbox'][ $this->_req_action ])
372
-                ? $this->_labels['publishbox'][ $this->_req_action ]
371
+                         && isset($this->_labels['publishbox'][$this->_req_action])
372
+                ? $this->_labels['publishbox'][$this->_req_action]
373 373
                 : $this->_labels['publishbox'];
374 374
             add_meta_box(
375 375
                 'submitdiv',
376 376
                 $box_label,
377 377
                 'post_submit_meta_box',
378
-                $this->_cpt_routes[ $this->_req_action ],
378
+                $this->_cpt_routes[$this->_req_action],
379 379
                 'side',
380 380
                 'core'
381 381
             );
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
                 'page_templates',
387 387
                 __('Page Template', 'event_espresso'),
388 388
                 array($this, 'page_template_meta_box'),
389
-                $this->_cpt_routes[ $this->_req_action ],
389
+                $this->_cpt_routes[$this->_req_action],
390 390
                 'side',
391 391
                 'default'
392 392
             );
@@ -418,8 +418,8 @@  discard block
 block discarded – undo
418 418
         // This is for any plugins that are doing things properly
419 419
         // and hooking into the load page hook for core wp cpt routes.
420 420
         global $pagenow;
421
-        add_action('load-' . $pagenow, array($this, 'modify_current_screen'), 20);
422
-        do_action('load-' . $pagenow);
421
+        add_action('load-'.$pagenow, array($this, 'modify_current_screen'), 20);
422
+        do_action('load-'.$pagenow);
423 423
         add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
424 424
         // we route REALLY early.
425 425
         try {
@@ -448,8 +448,8 @@  discard block
 block discarded – undo
448 448
                 'admin.php?page=espresso_registrations&action=contact_list',
449 449
             ),
450 450
             1 => array(
451
-                'edit.php?post_type=' . $this->_cpt_object->name,
452
-                'admin.php?page=' . $this->_cpt_object->name,
451
+                'edit.php?post_type='.$this->_cpt_object->name,
452
+                'admin.php?page='.$this->_cpt_object->name,
453 453
             ),
454 454
         );
455 455
         foreach ($routes_to_match as $route_matches) {
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
             'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
479 479
         );
480 480
         $cpt_args = $custom_post_types->getDefinitions();
481
-        $cpt_args = isset($cpt_args[ $cpt_name ]) ? $cpt_args[ $cpt_name ]['args'] : array();
481
+        $cpt_args = isset($cpt_args[$cpt_name]) ? $cpt_args[$cpt_name]['args'] : array();
482 482
         $cpt_has_support = ! empty($cpt_args['page_templates']);
483 483
 
484 484
         // if the installed version of WP is > 4.7 we do some additional checks.
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
             // if there are $post_templates for this cpt, then we return false for this method because
488 488
             // that means we aren't going to load our page template manager and leave that up to the native
489 489
             // cpt template manager.
490
-            $cpt_has_support = ! isset($post_templates[ $cpt_name ]) ? $cpt_has_support : false;
490
+            $cpt_has_support = ! isset($post_templates[$cpt_name]) ? $cpt_has_support : false;
491 491
         }
492 492
 
493 493
         return $cpt_has_support;
@@ -561,7 +561,7 @@  discard block
 block discarded – undo
561 561
 
562 562
         $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
563 563
         $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
564
-            ? $statuses[ $this->_cpt_model_obj->status() ]
564
+            ? $statuses[$this->_cpt_model_obj->status()]
565 565
             : '';
566 566
         $template_args = array(
567 567
             'cur_status'            => $this->_cpt_model_obj->status(),
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
             $template_args['statuses'] = $statuses;
577 577
         }
578 578
 
579
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
579
+        $template = EE_ADMIN_TEMPLATE.'status_dropdown.template.php';
580 580
         EEH_Template::display_template($template, $template_args);
581 581
     }
582 582
 
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
             : null;
618 618
         $this->_verify_nonce($nonce, 'autosave');
619 619
         // make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
620
-        if (! defined('DOING_AUTOSAVE')) {
620
+        if ( ! defined('DOING_AUTOSAVE')) {
621 621
             define('DOING_AUTOSAVE', true);
622 622
         }
623 623
         // if we made it here then the nonce checked out.  Let's run our methods and actions
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
             $this->_template_args['success'] = true;
629 629
         }
630 630
         do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
631
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
631
+        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_'.get_class($this), $this);
632 632
         // now let's return json
633 633
         $this->_return_json();
634 634
     }
@@ -650,7 +650,7 @@  discard block
 block discarded – undo
650 650
             return;
651 651
         }
652 652
         // set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
653
-        if (! empty($this->_cpt_object)) {
653
+        if ( ! empty($this->_cpt_object)) {
654 654
             $this->_page_routes = array_merge(
655 655
                 array(
656 656
                     'create_new' => '_create_new_cpt_item',
@@ -681,10 +681,10 @@  discard block
 block discarded – undo
681 681
             );
682 682
         }
683 683
         // load the next section only if this is a matching cpt route as set in the cpt routes array.
684
-        if (! isset($this->_cpt_routes[ $this->_req_action ])) {
684
+        if ( ! isset($this->_cpt_routes[$this->_req_action])) {
685 685
             return;
686 686
         }
687
-        $this->_cpt_route = isset($this->_cpt_routes[ $this->_req_action ]) ? true : false;
687
+        $this->_cpt_route = isset($this->_cpt_routes[$this->_req_action]) ? true : false;
688 688
         // add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
689 689
         if (empty($this->_cpt_object)) {
690 690
             $msg = sprintf(
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
         if (empty($this->_cpt_model_names)
725 725
             || (
726 726
                 ! $ignore_route_check
727
-                && ! isset($this->_cpt_routes[ $this->_req_action ])
727
+                && ! isset($this->_cpt_routes[$this->_req_action])
728 728
             ) || (
729 729
                 $this->_cpt_model_obj instanceof EE_CPT_Base
730 730
                 && $this->_cpt_model_obj->ID() === $id
@@ -741,11 +741,11 @@  discard block
 block discarded – undo
741 741
                 'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
742 742
             );
743 743
             $model_names = $custom_post_types->getCustomPostTypeModelNames($post_type);
744
-            if (isset($model_names[ $post_type ])) {
745
-                $model = EE_Registry::instance()->load_model($model_names[ $post_type ]);
744
+            if (isset($model_names[$post_type])) {
745
+                $model = EE_Registry::instance()->load_model($model_names[$post_type]);
746 746
             }
747 747
         } else {
748
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[ $this->_req_action ]);
748
+            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[$this->_req_action]);
749 749
         }
750 750
         if ($model instanceof EEM_Base) {
751 751
             $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
@@ -775,8 +775,8 @@  discard block
 block discarded – undo
775 775
         $current_route = isset($this->_req_data['current_route'])
776 776
             ? $this->_req_data['current_route']
777 777
             : 'shouldneverwork';
778
-        $route_to_check = $post_type && isset($this->_cpt_routes[ $current_route ])
779
-            ? $this->_cpt_routes[ $current_route ]
778
+        $route_to_check = $post_type && isset($this->_cpt_routes[$current_route])
779
+            ? $this->_cpt_routes[$current_route]
780 780
             : '';
781 781
         add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
782 782
         add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
@@ -785,10 +785,10 @@  discard block
 block discarded – undo
785 785
         }
786 786
         // now let's filter redirect if we're on a revision page and the revision is for an event CPT.
787 787
         $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
788
-        if (! empty($revision)) {
788
+        if ( ! empty($revision)) {
789 789
             $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
790 790
             // doing a restore?
791
-            if (! empty($action) && $action === 'restore') {
791
+            if ( ! empty($action) && $action === 'restore') {
792 792
                 // get post for revision
793 793
                 $rev_post = get_post($revision);
794 794
                 $rev_parent = get_post($rev_post->post_parent);
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
     {
825 825
         $this->_set_model_object($post_id, true, 'trash');
826 826
         // if our cpt object isn't existent then get out immediately.
827
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
827
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
828 828
             return;
829 829
         }
830 830
         $this->trash_cpt_item($post_id);
@@ -842,7 +842,7 @@  discard block
 block discarded – undo
842 842
     {
843 843
         $this->_set_model_object($post_id, true, 'restore');
844 844
         // if our cpt object isn't existent then get out immediately.
845
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
845
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
846 846
             return;
847 847
         }
848 848
         $this->restore_cpt_item($post_id);
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
     {
861 861
         $this->_set_model_object($post_id, true, 'delete');
862 862
         // if our cpt object isn't existent then get out immediately.
863
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
863
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
864 864
             return;
865 865
         }
866 866
         $this->delete_cpt_item($post_id);
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
     {
880 880
         $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
881 881
         // verify event object
882
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
882
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
883 883
             throw new EE_Error(
884 884
                 sprintf(
885 885
                     __(
@@ -935,13 +935,13 @@  discard block
 block discarded – undo
935 935
         if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
936 936
             // setup custom post status object for localize script but only if we've got a cpt object
937 937
             $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
938
-            if (! empty($statuses)) {
938
+            if ( ! empty($statuses)) {
939 939
                 // get ALL statuses!
940 940
                 $statuses = $this->_cpt_model_obj->get_all_post_statuses();
941 941
                 // setup object
942 942
                 $ee_cpt_statuses = array();
943 943
                 foreach ($statuses as $status => $label) {
944
-                    $ee_cpt_statuses[ $status ] = array(
944
+                    $ee_cpt_statuses[$status] = array(
945 945
                         'label'      => $label,
946 946
                         'save_label' => sprintf(
947 947
                             wp_strip_all_tags(__('Save as %s', 'event_espresso')),
@@ -1006,7 +1006,7 @@  discard block
 block discarded – undo
1006 1006
                 $post->page_template = $this->_req_data['page_template'];
1007 1007
                 $page_templates = wp_get_theme()->get_page_templates($post);
1008 1008
             }
1009
-            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[ $this->_req_data['page_template'] ])) {
1009
+            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[$this->_req_data['page_template']])) {
1010 1010
                 EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1011 1011
             } else {
1012 1012
                 update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
@@ -1031,7 +1031,7 @@  discard block
 block discarded – undo
1031 1031
     {
1032 1032
         // only do this if we're actually processing one of our CPTs
1033 1033
         // if our cpt object isn't existent then get out immediately.
1034
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1034
+        if ( ! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1035 1035
             return;
1036 1036
         }
1037 1037
         delete_post_meta($post_id, '_wp_trash_meta_status');
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
         // global action
1057 1057
         do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1058 1058
         // class specific action so you can limit hooking into a specific page.
1059
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1059
+        do_action('AHEE_EE_Admin_Page_CPT_'.get_class($this).'__restore_revision', $post_id, $revision_id);
1060 1060
     }
1061 1061
 
1062 1062
 
@@ -1083,11 +1083,11 @@  discard block
 block discarded – undo
1083 1083
     public function modify_current_screen()
1084 1084
     {
1085 1085
         // ONLY do this if the current page_route IS a cpt route
1086
-        if (! $this->_cpt_route) {
1086
+        if ( ! $this->_cpt_route) {
1087 1087
             return;
1088 1088
         }
1089 1089
         // routing things REALLY early b/c this is a cpt admin page
1090
-        set_current_screen($this->_cpt_routes[ $this->_req_action ]);
1090
+        set_current_screen($this->_cpt_routes[$this->_req_action]);
1091 1091
         $this->_current_screen = get_current_screen();
1092 1092
         $this->_current_screen->base = 'event-espresso';
1093 1093
         $this->_add_help_tabs(); // we make sure we add any help tabs back in!
@@ -1110,8 +1110,8 @@  discard block
 block discarded – undo
1110 1110
      */
1111 1111
     public function add_custom_editor_default_title($title)
1112 1112
     {
1113
-        return isset($this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ])
1114
-            ? $this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ]
1113
+        return isset($this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]])
1114
+            ? $this->_labels['editor_title'][$this->_cpt_routes[$this->_req_action]]
1115 1115
             : $title;
1116 1116
     }
1117 1117
 
@@ -1127,10 +1127,10 @@  discard block
 block discarded – undo
1127 1127
      */
1128 1128
     public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1129 1129
     {
1130
-        if (! empty($id) && get_option('permalink_structure') !== '') {
1130
+        if ( ! empty($id) && get_option('permalink_structure') !== '') {
1131 1131
             $post = get_post($id);
1132 1132
             if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1133
-                $shortlink = home_url('?p=' . $post->ID);
1133
+                $shortlink = home_url('?p='.$post->ID);
1134 1134
             }
1135 1135
         }
1136 1136
         return $shortlink;
@@ -1163,11 +1163,11 @@  discard block
 block discarded – undo
1163 1163
      */
1164 1164
     public function cpt_post_form_hidden_input()
1165 1165
     {
1166
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1166
+        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="'.$this->_admin_base_url.'" />';
1167 1167
         // we're also going to add the route value and the current page so we can direct autosave parsing correctly
1168 1168
         echo '<div id="ee-cpt-hidden-inputs">';
1169
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1170
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1169
+        echo '<input type="hidden" id="current_route" name="current_route" value="'.$this->_current_view.'" />';
1170
+        echo '<input type="hidden" id="current_page" name="current_page" value="'.$this->page_slug.'" />';
1171 1171
         echo '</div>';
1172 1172
     }
1173 1173
 
@@ -1212,15 +1212,15 @@  discard block
 block discarded – undo
1212 1212
     public function modify_edit_post_link($link, $id, $context)
1213 1213
     {
1214 1214
         $post = get_post($id);
1215
-        if (! isset($this->_req_data['action'])
1216
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1217
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1215
+        if ( ! isset($this->_req_data['action'])
1216
+            || ! isset($this->_cpt_routes[$this->_req_data['action']])
1217
+            || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1218 1218
         ) {
1219 1219
             return $link;
1220 1220
         }
1221 1221
         $query_args = array(
1222
-            'action' => isset($this->_cpt_edit_routes[ $post->post_type ])
1223
-                ? $this->_cpt_edit_routes[ $post->post_type ]
1222
+            'action' => isset($this->_cpt_edit_routes[$post->post_type])
1223
+                ? $this->_cpt_edit_routes[$post->post_type]
1224 1224
                 : 'edit',
1225 1225
             'post'   => $id,
1226 1226
         );
@@ -1243,16 +1243,16 @@  discard block
 block discarded – undo
1243 1243
         $post = get_post($post_id);
1244 1244
 
1245 1245
         if (empty($this->_req_data['action'])
1246
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1246
+            || ! isset($this->_cpt_routes[$this->_req_data['action']])
1247 1247
             || ! $post instanceof WP_Post
1248
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1248
+            || $post->post_type !== $this->_cpt_routes[$this->_req_data['action']]
1249 1249
         ) {
1250 1250
             return $delete_link;
1251 1251
         }
1252 1252
         $this->_set_model_object($post->ID, true);
1253 1253
 
1254 1254
         // returns something like `trash_event` or `trash_attendee` or `trash_venue`
1255
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1255
+        $action = 'trash_'.str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1256 1256
 
1257 1257
         return EE_Admin_Page::add_query_args_and_nonce(
1258 1258
             array(
@@ -1280,7 +1280,7 @@  discard block
 block discarded – undo
1280 1280
         // we DO have a match so let's setup the url
1281 1281
         // we have to get the post to determine our route
1282 1282
         $post = get_post($post_id);
1283
-        $edit_route = $this->_cpt_edit_routes[ $post->post_type ];
1283
+        $edit_route = $this->_cpt_edit_routes[$post->post_type];
1284 1284
         // shared query_args
1285 1285
         $query_args = array('action' => $edit_route, 'post' => $post_id);
1286 1286
         $admin_url = $this->_admin_base_url;
@@ -1352,12 +1352,12 @@  discard block
 block discarded – undo
1352 1352
         /*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1353 1353
 
1354 1354
         $route_to_check = $post_type && isset( $this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route] : '';/**/
1355
-        $messages[ $post->post_type ] = array(
1355
+        $messages[$post->post_type] = array(
1356 1356
             0  => '', // Unused. Messages start at index 1.
1357 1357
             1  => sprintf(
1358 1358
                 __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1359 1359
                 $this->_cpt_object->labels->singular_name,
1360
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1360
+                '<a href="'.esc_url(get_permalink($id)).'">',
1361 1361
                 '</a>'
1362 1362
             ),
1363 1363
             2  => __('Custom field updated', 'event_espresso'),
@@ -1372,27 +1372,27 @@  discard block
 block discarded – undo
1372 1372
             6  => sprintf(
1373 1373
                 __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1374 1374
                 $this->_cpt_object->labels->singular_name,
1375
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1375
+                '<a href="'.esc_url(get_permalink($id)).'">',
1376 1376
                 '</a>'
1377 1377
             ),
1378 1378
             7  => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1379 1379
             8  => sprintf(
1380 1380
                 __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1381 1381
                 $this->_cpt_object->labels->singular_name,
1382
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1382
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))).'">',
1383 1383
                 '</a>'
1384 1384
             ),
1385 1385
             9  => sprintf(
1386 1386
                 __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1387 1387
                 $this->_cpt_object->labels->singular_name,
1388
-                '<strong>' . date_i18n('M j, Y @ G:i', strtotime($post->post_date)) . '</strong>',
1389
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1388
+                '<strong>'.date_i18n('M j, Y @ G:i', strtotime($post->post_date)).'</strong>',
1389
+                '<a target="_blank" href="'.esc_url(get_permalink($id)),
1390 1390
                 '</a>'
1391 1391
             ),
1392 1392
             10 => sprintf(
1393 1393
                 __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1394 1394
                 $this->_cpt_object->labels->singular_name,
1395
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1395
+                '<a target="_blank" href="'.esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1396 1396
                 '</a>'
1397 1397
             ),
1398 1398
         );
@@ -1411,10 +1411,10 @@  discard block
 block discarded – undo
1411 1411
     {
1412 1412
         // gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1413 1413
         global $post, $title, $is_IE, $post_type, $post_type_object;
1414
-        $post_type = $this->_cpt_routes[ $this->_req_action ];
1414
+        $post_type = $this->_cpt_routes[$this->_req_action];
1415 1415
         $post_type_object = $this->_cpt_object;
1416 1416
         $title = $post_type_object->labels->add_new_item;
1417
-        $post = $post = get_default_post_to_edit($this->_cpt_routes[ $this->_req_action ], true);
1417
+        $post = $post = get_default_post_to_edit($this->_cpt_routes[$this->_req_action], true);
1418 1418
         add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1419 1419
         // modify the default editor title field with default title.
1420 1420
         add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
@@ -1439,8 +1439,8 @@  discard block
 block discarded – undo
1439 1439
             if ($creating) {
1440 1440
                 wp_enqueue_script('autosave');
1441 1441
             } else {
1442
-                if (isset($this->_cpt_routes[ $this->_req_data['action'] ])
1443
-                    && ! isset($this->_labels['hide_add_button_on_cpt_route'][ $this->_req_data['action'] ])
1442
+                if (isset($this->_cpt_routes[$this->_req_data['action']])
1443
+                    && ! isset($this->_labels['hide_add_button_on_cpt_route'][$this->_req_data['action']])
1444 1444
                 ) {
1445 1445
                     $create_new_action = apply_filters(
1446 1446
                         'FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
@@ -1456,7 +1456,7 @@  discard block
 block discarded – undo
1456 1456
                     );
1457 1457
                 }
1458 1458
             }
1459
-            include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1459
+            include_once WP_ADMIN_PATH.'edit-form-advanced.php';
1460 1460
         }
1461 1461
     }
1462 1462
 
@@ -1487,21 +1487,21 @@  discard block
 block discarded – undo
1487 1487
         if (empty($post)) {
1488 1488
             wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', 'event_espresso'));
1489 1489
         }
1490
-        if (! empty($_GET['get-post-lock'])) {
1490
+        if ( ! empty($_GET['get-post-lock'])) {
1491 1491
             wp_set_post_lock($post_id);
1492 1492
             wp_redirect(get_edit_post_link($post_id, 'url'));
1493 1493
             exit();
1494 1494
         }
1495 1495
 
1496 1496
         // template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1497
-        $post_type = $this->_cpt_routes[ $this->_req_action ];
1497
+        $post_type = $this->_cpt_routes[$this->_req_action];
1498 1498
         $post_type_object = $this->_cpt_object;
1499 1499
 
1500
-        if (! wp_check_post_lock($post->ID)) {
1500
+        if ( ! wp_check_post_lock($post->ID)) {
1501 1501
             wp_set_post_lock($post->ID);
1502 1502
         }
1503 1503
         add_action('admin_footer', '_admin_notice_post_locked');
1504
-        if (post_type_supports($this->_cpt_routes[ $this->_req_action ], 'comments')) {
1504
+        if (post_type_supports($this->_cpt_routes[$this->_req_action], 'comments')) {
1505 1505
             wp_enqueue_script('admin-comments');
1506 1506
             enqueue_comment_hotkeys_js();
1507 1507
         }
Please login to merge, or discard this patch.
Indentation   +1469 added lines, -1469 removed lines patch added patch discarded remove patch
@@ -28,494 +28,494 @@  discard block
 block discarded – undo
28 28
 {
29 29
 
30 30
 
31
-    /**
32
-     * This gets set in _setup_cpt
33
-     * It will contain the object for the custom post type.
34
-     *
35
-     * @var EE_CPT_Base
36
-     */
37
-    protected $_cpt_object;
38
-
39
-
40
-    /**
41
-     * a boolean flag to set whether the current route is a cpt route or not.
42
-     *
43
-     * @var bool
44
-     */
45
-    protected $_cpt_route = false;
46
-
47
-
48
-    /**
49
-     * This property allows cpt classes to define multiple routes as cpt routes.
50
-     * //in this array we define what the custom post type for this route is.
51
-     * array(
52
-     * 'route_name' => 'custom_post_type_slug'
53
-     * )
54
-     *
55
-     * @var array
56
-     */
57
-    protected $_cpt_routes = array();
58
-
59
-
60
-    /**
61
-     * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
62
-     * in this format:
63
-     * array(
64
-     * 'post_type_slug' => 'edit_route'
65
-     * )
66
-     *
67
-     * @var array
68
-     */
69
-    protected $_cpt_edit_routes = array();
70
-
71
-
72
-    /**
73
-     * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
-     * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
-     * _cpt_model_names property should be in the following format: array(
76
-     * 'route_defined_by_action_param' => 'Model_Name')
77
-     *
78
-     * @var array $_cpt_model_names
79
-     */
80
-    protected $_cpt_model_names = array();
81
-
82
-
83
-    /**
84
-     * @var EE_CPT_Base
85
-     */
86
-    protected $_cpt_model_obj = false;
87
-
88
-    /**
89
-     * @var LoaderInterface $loader ;
90
-     */
91
-    protected $loader;
92
-
93
-    /**
94
-     * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
95
-     * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
96
-     * the _register_autosave_containers() method so that we don't override any other containers already registered.
97
-     * Registration of containers should be done before load_page_dependencies() is run.
98
-     *
99
-     * @var array()
100
-     */
101
-    protected $_autosave_containers = array();
102
-    protected $_autosave_fields = array();
103
-
104
-    /**
105
-     * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
106
-     * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
107
-     *
108
-     * @var array
109
-     */
110
-    protected $_pagenow_map;
111
-
112
-
113
-    /**
114
-     * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
115
-     * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
116
-     * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
117
-     * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
118
-     * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
119
-     *
120
-     * @access protected
121
-     * @abstract
122
-     * @param  string      $post_id The ID of the cpt that was saved (so you can link relationally)
123
-     * @param  EE_CPT_Base $post    The post object of the cpt that was saved.
124
-     * @return void
125
-     */
126
-    abstract protected function _insert_update_cpt_item($post_id, $post);
127
-
128
-
129
-    /**
130
-     * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
131
-     *
132
-     * @abstract
133
-     * @access public
134
-     * @param  string $post_id The ID of the cpt that was trashed
135
-     * @return void
136
-     */
137
-    abstract public function trash_cpt_item($post_id);
138
-
139
-
140
-    /**
141
-     * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
-     *
143
-     * @param  string $post_id theID of the cpt that was untrashed
144
-     * @return void
145
-     */
146
-    abstract public function restore_cpt_item($post_id);
147
-
148
-
149
-    /**
150
-     * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
151
-     * from the db
152
-     *
153
-     * @param  string $post_id the ID of the cpt that was deleted
154
-     * @return void
155
-     */
156
-    abstract public function delete_cpt_item($post_id);
157
-
158
-
159
-    /**
160
-     * @return LoaderInterface
161
-     * @throws InvalidArgumentException
162
-     * @throws InvalidDataTypeException
163
-     * @throws InvalidInterfaceException
164
-     */
165
-    protected function getLoader()
166
-    {
167
-        if (! $this->loader instanceof LoaderInterface) {
168
-            $this->loader = LoaderFactory::getLoader();
169
-        }
170
-        return $this->loader;
171
-    }
172
-
173
-    /**
174
-     * Just utilizing the method EE_Admin exposes for doing things before page setup.
175
-     *
176
-     * @access protected
177
-     * @return void
178
-     */
179
-    protected function _before_page_setup()
180
-    {
181
-        $page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
182
-        $this->_cpt_routes = array_merge(
183
-            array(
184
-                'create_new' => $this->page_slug,
185
-                'edit'       => $this->page_slug,
186
-                'trash'      => $this->page_slug,
187
-            ),
188
-            $this->_cpt_routes
189
-        );
190
-        // let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
191
-        $this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[ $this->_req_data['action'] ])
192
-            ? get_post_type_object($this->_cpt_routes[ $this->_req_data['action'] ])
193
-            : get_post_type_object($page);
194
-        // tweak pagenow for page loading.
195
-        if (! $this->_pagenow_map) {
196
-            $this->_pagenow_map = array(
197
-                'create_new' => 'post-new.php',
198
-                'edit'       => 'post.php',
199
-                'trash'      => 'post.php',
200
-            );
201
-        }
202
-        add_action('current_screen', array($this, 'modify_pagenow'));
203
-        // TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
204
-        // get current page from autosave
205
-        $current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
206
-            ? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
207
-            : null;
208
-        $this->_current_page = isset($this->_req_data['current_page'])
209
-            ? $this->_req_data['current_page']
210
-            : $current_page;
211
-        // autosave... make sure its only for the correct page
212
-        // if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
213
-        // setup autosave ajax hook
214
-        // add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
215
-        // }
216
-    }
217
-
218
-
219
-    /**
220
-     * Simply ensure that we simulate the correct post route for cpt screens
221
-     *
222
-     * @param WP_Screen $current_screen
223
-     * @return void
224
-     */
225
-    public function modify_pagenow($current_screen)
226
-    {
227
-        global $pagenow, $hook_suffix;
228
-        // possibly reset pagenow.
229
-        if (! empty($this->_req_data['page'])
230
-            && $this->_req_data['page'] == $this->page_slug
231
-            && ! empty($this->_req_data['action'])
232
-            && isset($this->_pagenow_map[ $this->_req_data['action'] ])
233
-        ) {
234
-            $pagenow = $this->_pagenow_map[ $this->_req_data['action'] ];
235
-            $hook_suffix = $pagenow;
236
-        }
237
-    }
238
-
239
-
240
-    /**
241
-     * This method is used to register additional autosave containers to the _autosave_containers property.
242
-     *
243
-     * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
244
-     *       automatically register the id for the post metabox as a container.
245
-     * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
246
-     *                    you would send along the id of a metabox container.
247
-     * @return void
248
-     */
249
-    protected function _register_autosave_containers($ids)
250
-    {
251
-        $this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
252
-    }
253
-
254
-
255
-    /**
256
-     * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
257
-     * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
258
-     */
259
-    protected function _set_autosave_containers()
260
-    {
261
-        global $wp_meta_boxes;
262
-        $containers = array();
263
-        if (empty($wp_meta_boxes)) {
264
-            return;
265
-        }
266
-        $current_metaboxes = isset($wp_meta_boxes[ $this->page_slug ]) ? $wp_meta_boxes[ $this->page_slug ] : array();
267
-        foreach ($current_metaboxes as $box_context) {
268
-            foreach ($box_context as $box_details) {
269
-                foreach ($box_details as $box) {
270
-                    if (is_array($box) && is_array($box['callback'])
271
-                        && (
272
-                            $box['callback'][0] instanceof EE_Admin_Page
273
-                            || $box['callback'][0] instanceof EE_Admin_Hooks
274
-                        )
275
-                    ) {
276
-                        $containers[] = $box['id'];
277
-                    }
278
-                }
279
-            }
280
-        }
281
-        $this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
282
-        // add hidden inputs container
283
-        $this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
284
-    }
285
-
286
-
287
-    protected function _load_autosave_scripts_styles()
288
-    {
289
-        /*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
31
+	/**
32
+	 * This gets set in _setup_cpt
33
+	 * It will contain the object for the custom post type.
34
+	 *
35
+	 * @var EE_CPT_Base
36
+	 */
37
+	protected $_cpt_object;
38
+
39
+
40
+	/**
41
+	 * a boolean flag to set whether the current route is a cpt route or not.
42
+	 *
43
+	 * @var bool
44
+	 */
45
+	protected $_cpt_route = false;
46
+
47
+
48
+	/**
49
+	 * This property allows cpt classes to define multiple routes as cpt routes.
50
+	 * //in this array we define what the custom post type for this route is.
51
+	 * array(
52
+	 * 'route_name' => 'custom_post_type_slug'
53
+	 * )
54
+	 *
55
+	 * @var array
56
+	 */
57
+	protected $_cpt_routes = array();
58
+
59
+
60
+	/**
61
+	 * This simply defines what the corresponding routes WP will be redirected to after completing a post save/update.
62
+	 * in this format:
63
+	 * array(
64
+	 * 'post_type_slug' => 'edit_route'
65
+	 * )
66
+	 *
67
+	 * @var array
68
+	 */
69
+	protected $_cpt_edit_routes = array();
70
+
71
+
72
+	/**
73
+	 * If child classes set the name of their main model via the $_cpt_obj_models property, EE_Admin_Page_CPT will
74
+	 * attempt to retrieve the related object model for the edit pages and assign it to _cpt_page_object. the
75
+	 * _cpt_model_names property should be in the following format: array(
76
+	 * 'route_defined_by_action_param' => 'Model_Name')
77
+	 *
78
+	 * @var array $_cpt_model_names
79
+	 */
80
+	protected $_cpt_model_names = array();
81
+
82
+
83
+	/**
84
+	 * @var EE_CPT_Base
85
+	 */
86
+	protected $_cpt_model_obj = false;
87
+
88
+	/**
89
+	 * @var LoaderInterface $loader ;
90
+	 */
91
+	protected $loader;
92
+
93
+	/**
94
+	 * This will hold an array of autosave containers that will be used to obtain input values and hook into the WP
95
+	 * autosave so we can save our inputs on the save_post hook!  Children classes should add to this array by using
96
+	 * the _register_autosave_containers() method so that we don't override any other containers already registered.
97
+	 * Registration of containers should be done before load_page_dependencies() is run.
98
+	 *
99
+	 * @var array()
100
+	 */
101
+	protected $_autosave_containers = array();
102
+	protected $_autosave_fields = array();
103
+
104
+	/**
105
+	 * Array mapping from admin actions to their equivalent wp core pages for custom post types. So when a user visits
106
+	 * a page for an action, it will appear as if they were visiting the wp core page for that custom post type
107
+	 *
108
+	 * @var array
109
+	 */
110
+	protected $_pagenow_map;
111
+
112
+
113
+	/**
114
+	 * This is hooked into the WordPress do_action('save_post') hook and runs after the custom post type has been
115
+	 * saved.  Child classes are required to declare this method.  Typically you would use this to save any additional
116
+	 * data. Keep in mind also that "save_post" runs on EVERY post update to the database. ALSO very important.  When a
117
+	 * post transitions from scheduled to published, the save_post action is fired but you will NOT have any _POST data
118
+	 * containing any extra info you may have from other meta saves.  So MAKE sure that you handle this accordingly.
119
+	 *
120
+	 * @access protected
121
+	 * @abstract
122
+	 * @param  string      $post_id The ID of the cpt that was saved (so you can link relationally)
123
+	 * @param  EE_CPT_Base $post    The post object of the cpt that was saved.
124
+	 * @return void
125
+	 */
126
+	abstract protected function _insert_update_cpt_item($post_id, $post);
127
+
128
+
129
+	/**
130
+	 * This is hooked into the WordPress do_action('trashed_post') hook and runs after a cpt has been trashed.
131
+	 *
132
+	 * @abstract
133
+	 * @access public
134
+	 * @param  string $post_id The ID of the cpt that was trashed
135
+	 * @return void
136
+	 */
137
+	abstract public function trash_cpt_item($post_id);
138
+
139
+
140
+	/**
141
+	 * This is hooked into the WordPress do_action('untrashed_post') hook and runs after a cpt has been untrashed
142
+	 *
143
+	 * @param  string $post_id theID of the cpt that was untrashed
144
+	 * @return void
145
+	 */
146
+	abstract public function restore_cpt_item($post_id);
147
+
148
+
149
+	/**
150
+	 * This is hooked into the WordPress do_action('delete_cpt_item') hook and runs after a cpt has been fully deleted
151
+	 * from the db
152
+	 *
153
+	 * @param  string $post_id the ID of the cpt that was deleted
154
+	 * @return void
155
+	 */
156
+	abstract public function delete_cpt_item($post_id);
157
+
158
+
159
+	/**
160
+	 * @return LoaderInterface
161
+	 * @throws InvalidArgumentException
162
+	 * @throws InvalidDataTypeException
163
+	 * @throws InvalidInterfaceException
164
+	 */
165
+	protected function getLoader()
166
+	{
167
+		if (! $this->loader instanceof LoaderInterface) {
168
+			$this->loader = LoaderFactory::getLoader();
169
+		}
170
+		return $this->loader;
171
+	}
172
+
173
+	/**
174
+	 * Just utilizing the method EE_Admin exposes for doing things before page setup.
175
+	 *
176
+	 * @access protected
177
+	 * @return void
178
+	 */
179
+	protected function _before_page_setup()
180
+	{
181
+		$page = isset($this->_req_data['page']) ? $this->_req_data['page'] : $this->page_slug;
182
+		$this->_cpt_routes = array_merge(
183
+			array(
184
+				'create_new' => $this->page_slug,
185
+				'edit'       => $this->page_slug,
186
+				'trash'      => $this->page_slug,
187
+			),
188
+			$this->_cpt_routes
189
+		);
190
+		// let's see if the current route has a value for cpt_object_slug if it does we use that instead of the page
191
+		$this->_cpt_object = isset($this->_req_data['action']) && isset($this->_cpt_routes[ $this->_req_data['action'] ])
192
+			? get_post_type_object($this->_cpt_routes[ $this->_req_data['action'] ])
193
+			: get_post_type_object($page);
194
+		// tweak pagenow for page loading.
195
+		if (! $this->_pagenow_map) {
196
+			$this->_pagenow_map = array(
197
+				'create_new' => 'post-new.php',
198
+				'edit'       => 'post.php',
199
+				'trash'      => 'post.php',
200
+			);
201
+		}
202
+		add_action('current_screen', array($this, 'modify_pagenow'));
203
+		// TODO the below will need to be reworked to account for the cpt routes that are NOT based off of page but action param.
204
+		// get current page from autosave
205
+		$current_page = isset($this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page'])
206
+			? $this->_req_data['ee_autosave_data']['ee-cpt-hidden-inputs']['current_page']
207
+			: null;
208
+		$this->_current_page = isset($this->_req_data['current_page'])
209
+			? $this->_req_data['current_page']
210
+			: $current_page;
211
+		// autosave... make sure its only for the correct page
212
+		// if ( ! empty($this->_current_page) && $this->_current_page == $this->page_slug) {
213
+		// setup autosave ajax hook
214
+		// add_action('wp_ajax_ee-autosave', array( $this, 'do_extra_autosave_stuff' ), 10 ); //TODO reactivate when 4.2 autosave is implemented
215
+		// }
216
+	}
217
+
218
+
219
+	/**
220
+	 * Simply ensure that we simulate the correct post route for cpt screens
221
+	 *
222
+	 * @param WP_Screen $current_screen
223
+	 * @return void
224
+	 */
225
+	public function modify_pagenow($current_screen)
226
+	{
227
+		global $pagenow, $hook_suffix;
228
+		// possibly reset pagenow.
229
+		if (! empty($this->_req_data['page'])
230
+			&& $this->_req_data['page'] == $this->page_slug
231
+			&& ! empty($this->_req_data['action'])
232
+			&& isset($this->_pagenow_map[ $this->_req_data['action'] ])
233
+		) {
234
+			$pagenow = $this->_pagenow_map[ $this->_req_data['action'] ];
235
+			$hook_suffix = $pagenow;
236
+		}
237
+	}
238
+
239
+
240
+	/**
241
+	 * This method is used to register additional autosave containers to the _autosave_containers property.
242
+	 *
243
+	 * @todo We should automate this at some point by creating a wrapper for add_post_metabox and in our wrapper we
244
+	 *       automatically register the id for the post metabox as a container.
245
+	 * @param  array $ids an array of ids for containers that hold form inputs we want autosave to pickup.  Typically
246
+	 *                    you would send along the id of a metabox container.
247
+	 * @return void
248
+	 */
249
+	protected function _register_autosave_containers($ids)
250
+	{
251
+		$this->_autosave_containers = array_merge($this->_autosave_fields, (array) $ids);
252
+	}
253
+
254
+
255
+	/**
256
+	 * Something nifty.  We're going to loop through all the registered metaboxes and if the CALLBACK is an instance of
257
+	 * EE_Admin_Page OR EE_Admin_Hooks, then we'll add the id to our _autosave_containers array.
258
+	 */
259
+	protected function _set_autosave_containers()
260
+	{
261
+		global $wp_meta_boxes;
262
+		$containers = array();
263
+		if (empty($wp_meta_boxes)) {
264
+			return;
265
+		}
266
+		$current_metaboxes = isset($wp_meta_boxes[ $this->page_slug ]) ? $wp_meta_boxes[ $this->page_slug ] : array();
267
+		foreach ($current_metaboxes as $box_context) {
268
+			foreach ($box_context as $box_details) {
269
+				foreach ($box_details as $box) {
270
+					if (is_array($box) && is_array($box['callback'])
271
+						&& (
272
+							$box['callback'][0] instanceof EE_Admin_Page
273
+							|| $box['callback'][0] instanceof EE_Admin_Hooks
274
+						)
275
+					) {
276
+						$containers[] = $box['id'];
277
+					}
278
+				}
279
+			}
280
+		}
281
+		$this->_autosave_containers = array_merge($this->_autosave_containers, $containers);
282
+		// add hidden inputs container
283
+		$this->_autosave_containers[] = 'ee-cpt-hidden-inputs';
284
+	}
285
+
286
+
287
+	protected function _load_autosave_scripts_styles()
288
+	{
289
+		/*wp_register_script('cpt-autosave', EE_ADMIN_URL . 'assets/ee-cpt-autosave.js', array('ee-serialize-full-array', 'event_editor_js'), EVENT_ESPRESSO_VERSION, TRUE );
290 290
         wp_enqueue_script('cpt-autosave');/**/ // todo re-enable when we start doing autosave again in 4.2
291 291
 
292
-        // filter _autosave_containers
293
-        $containers = apply_filters(
294
-            'FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
295
-            $this->_autosave_containers,
296
-            $this
297
-        );
298
-        $containers = apply_filters(
299
-            'FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
300
-            $containers,
301
-            $this
302
-        );
303
-
304
-        wp_localize_script(
305
-            'event_editor_js',
306
-            'EE_AUTOSAVE_IDS',
307
-            $containers
308
-        ); // todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
309
-
310
-        $unsaved_data_msg = array(
311
-            'eventmsg'     => sprintf(
312
-                wp_strip_all_tags(
313
-                    __(
314
-                        "The changes you made to this %s will be lost if you navigate away from this page.",
315
-                        'event_espresso'
316
-                    )
317
-                ),
318
-                $this->_cpt_object->labels->singular_name
319
-            ),
320
-            'inputChanged' => 0,
321
-        );
322
-        wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
323
-    }
324
-
325
-
326
-    public function load_page_dependencies()
327
-    {
328
-        try {
329
-            $this->_load_page_dependencies();
330
-        } catch (EE_Error $e) {
331
-            $e->get_error();
332
-        }
333
-    }
334
-
335
-
336
-    /**
337
-     * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
338
-     *
339
-     * @access protected
340
-     * @return void
341
-     */
342
-    protected function _load_page_dependencies()
343
-    {
344
-        // we only add stuff if this is a cpt_route!
345
-        if (! $this->_cpt_route) {
346
-            parent::_load_page_dependencies();
347
-            return;
348
-        }
349
-        // now let's do some automatic filters into the wp_system
350
-        // and we'll check to make sure the CHILD class
351
-        // automatically has the required methods in place.
352
-        // the following filters are for setting all the redirects
353
-        // on DEFAULT WP custom post type actions
354
-        // let's add a hidden input to the post-edit form
355
-        // so we know when we have to trigger our custom redirects!
356
-        // Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
357
-        add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
358
-        // inject our Admin page nav tabs...
359
-        // let's make sure the nav tabs are set if they aren't already
360
-        // if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
361
-        add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
362
-        // modify the post_updated messages array
363
-        add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
364
-        // add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
365
-        // cpts use the same format for shortlinks as posts!
366
-        add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
367
-        // This basically allows us to change the title of the "publish" metabox area
368
-        // on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
369
-        if (! empty($this->_labels['publishbox'])) {
370
-            $box_label = is_array($this->_labels['publishbox'])
371
-                         && isset($this->_labels['publishbox'][ $this->_req_action ])
372
-                ? $this->_labels['publishbox'][ $this->_req_action ]
373
-                : $this->_labels['publishbox'];
374
-            add_meta_box(
375
-                'submitdiv',
376
-                $box_label,
377
-                'post_submit_meta_box',
378
-                $this->_cpt_routes[ $this->_req_action ],
379
-                'side',
380
-                'core'
381
-            );
382
-        }
383
-        // let's add page_templates metabox if this cpt added support for it.
384
-        if ($this->_supports_page_templates($this->_cpt_object->name)) {
385
-            add_meta_box(
386
-                'page_templates',
387
-                __('Page Template', 'event_espresso'),
388
-                array($this, 'page_template_meta_box'),
389
-                $this->_cpt_routes[ $this->_req_action ],
390
-                'side',
391
-                'default'
392
-            );
393
-        }
394
-        // this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
395
-        if (method_exists($this, 'extra_permalink_field_buttons')) {
396
-            add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
397
-        }
398
-        // add preview button
399
-        add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
400
-        // insert our own post_stati dropdown
401
-        add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
402
-        // This allows adding additional information to the publish post submitbox on the wp post edit form
403
-        if (method_exists($this, 'extra_misc_actions_publish_box')) {
404
-            add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
405
-        }
406
-        // This allows for adding additional stuff after the title field on the wp post edit form.
407
-        // This is also before the wp_editor for post description field.
408
-        if (method_exists($this, 'edit_form_after_title')) {
409
-            add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
410
-        }
411
-        /**
412
-         * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
413
-         */
414
-        add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
415
-        parent::_load_page_dependencies();
416
-        // notice we are ALSO going to load the pagenow hook set for this route
417
-        // (see _before_page_setup for the reset of the pagenow global ).
418
-        // This is for any plugins that are doing things properly
419
-        // and hooking into the load page hook for core wp cpt routes.
420
-        global $pagenow;
421
-        add_action('load-' . $pagenow, array($this, 'modify_current_screen'), 20);
422
-        do_action('load-' . $pagenow);
423
-        add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
424
-        // we route REALLY early.
425
-        try {
426
-            $this->_route_admin_request();
427
-        } catch (EE_Error $e) {
428
-            $e->get_error();
429
-        }
430
-    }
431
-
432
-
433
-    /**
434
-     * Since we don't want users going to default core wp routes, this will check any wp urls run through the
435
-     * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
436
-     * route instead.
437
-     *
438
-     * @param string $good_protocol_url The escaped url.
439
-     * @param string $original_url      The original url.
440
-     * @param string $_context          The context sent to the esc_url method.
441
-     * @return string possibly a new url for our route.
442
-     */
443
-    public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
444
-    {
445
-        $routes_to_match = array(
446
-            0 => array(
447
-                'edit.php?post_type=espresso_attendees',
448
-                'admin.php?page=espresso_registrations&action=contact_list',
449
-            ),
450
-            1 => array(
451
-                'edit.php?post_type=' . $this->_cpt_object->name,
452
-                'admin.php?page=' . $this->_cpt_object->name,
453
-            ),
454
-        );
455
-        foreach ($routes_to_match as $route_matches) {
456
-            if (strpos($good_protocol_url, $route_matches[0]) !== false) {
457
-                return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
458
-            }
459
-        }
460
-        return $good_protocol_url;
461
-    }
462
-
463
-
464
-    /**
465
-     * Determine whether the current cpt supports page templates or not.
466
-     *
467
-     * @since %VER%
468
-     * @param string $cpt_name The cpt slug we're checking on.
469
-     * @return bool True supported, false not.
470
-     * @throws InvalidArgumentException
471
-     * @throws InvalidDataTypeException
472
-     * @throws InvalidInterfaceException
473
-     */
474
-    private function _supports_page_templates($cpt_name)
475
-    {
476
-        /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
477
-        $custom_post_types = $this->getLoader()->getShared(
478
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
479
-        );
480
-        $cpt_args = $custom_post_types->getDefinitions();
481
-        $cpt_args = isset($cpt_args[ $cpt_name ]) ? $cpt_args[ $cpt_name ]['args'] : array();
482
-        $cpt_has_support = ! empty($cpt_args['page_templates']);
483
-
484
-        // if the installed version of WP is > 4.7 we do some additional checks.
485
-        if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
486
-            $post_templates = wp_get_theme()->get_post_templates();
487
-            // if there are $post_templates for this cpt, then we return false for this method because
488
-            // that means we aren't going to load our page template manager and leave that up to the native
489
-            // cpt template manager.
490
-            $cpt_has_support = ! isset($post_templates[ $cpt_name ]) ? $cpt_has_support : false;
491
-        }
492
-
493
-        return $cpt_has_support;
494
-    }
495
-
496
-
497
-    /**
498
-     * Callback for the page_templates metabox selector.
499
-     *
500
-     * @since %VER%
501
-     * @return void
502
-     */
503
-    public function page_template_meta_box()
504
-    {
505
-        global $post;
506
-        $template = '';
507
-
508
-        if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
509
-            $page_template_count = count(get_page_templates());
510
-        } else {
511
-            $page_template_count = count(get_page_templates($post));
512
-        };
513
-
514
-        if ($page_template_count) {
515
-            $page_template = get_post_meta($post->ID, '_wp_page_template', true);
516
-            $template = ! empty($page_template) ? $page_template : '';
517
-        }
518
-        ?>
292
+		// filter _autosave_containers
293
+		$containers = apply_filters(
294
+			'FHEE__EE_Admin_Page_CPT___load_autosave_scripts_styles__containers',
295
+			$this->_autosave_containers,
296
+			$this
297
+		);
298
+		$containers = apply_filters(
299
+			'FHEE__EE_Admin_Page_CPT__' . get_class($this) . '___load_autosave_scripts_styles__containers',
300
+			$containers,
301
+			$this
302
+		);
303
+
304
+		wp_localize_script(
305
+			'event_editor_js',
306
+			'EE_AUTOSAVE_IDS',
307
+			$containers
308
+		); // todo once we enable autosaves, this needs to be switched to localize with "cpt-autosave"
309
+
310
+		$unsaved_data_msg = array(
311
+			'eventmsg'     => sprintf(
312
+				wp_strip_all_tags(
313
+					__(
314
+						"The changes you made to this %s will be lost if you navigate away from this page.",
315
+						'event_espresso'
316
+					)
317
+				),
318
+				$this->_cpt_object->labels->singular_name
319
+			),
320
+			'inputChanged' => 0,
321
+		);
322
+		wp_localize_script('event_editor_js', 'UNSAVED_DATA_MSG', $unsaved_data_msg);
323
+	}
324
+
325
+
326
+	public function load_page_dependencies()
327
+	{
328
+		try {
329
+			$this->_load_page_dependencies();
330
+		} catch (EE_Error $e) {
331
+			$e->get_error();
332
+		}
333
+	}
334
+
335
+
336
+	/**
337
+	 * overloading the EE_Admin_Page parent load_page_dependencies so we can get the cpt stuff added in appropriately
338
+	 *
339
+	 * @access protected
340
+	 * @return void
341
+	 */
342
+	protected function _load_page_dependencies()
343
+	{
344
+		// we only add stuff if this is a cpt_route!
345
+		if (! $this->_cpt_route) {
346
+			parent::_load_page_dependencies();
347
+			return;
348
+		}
349
+		// now let's do some automatic filters into the wp_system
350
+		// and we'll check to make sure the CHILD class
351
+		// automatically has the required methods in place.
352
+		// the following filters are for setting all the redirects
353
+		// on DEFAULT WP custom post type actions
354
+		// let's add a hidden input to the post-edit form
355
+		// so we know when we have to trigger our custom redirects!
356
+		// Otherwise the redirects will happen on ALL post saves which wouldn't be good of course!
357
+		add_action('edit_form_after_title', array($this, 'cpt_post_form_hidden_input'));
358
+		// inject our Admin page nav tabs...
359
+		// let's make sure the nav tabs are set if they aren't already
360
+		// if ( empty( $this->_nav_tabs ) ) $this->_set_nav_tabs();
361
+		add_action('post_edit_form_tag', array($this, 'inject_nav_tabs'));
362
+		// modify the post_updated messages array
363
+		add_action('post_updated_messages', array($this, 'post_update_messages'), 10);
364
+		// add shortlink button to cpt edit screens.  We can do this as a universal thing BECAUSE,
365
+		// cpts use the same format for shortlinks as posts!
366
+		add_filter('pre_get_shortlink', array($this, 'add_shortlink_button_to_editor'), 10, 4);
367
+		// This basically allows us to change the title of the "publish" metabox area
368
+		// on CPT pages by setting a 'publishbox' value in the $_labels property array in the child class.
369
+		if (! empty($this->_labels['publishbox'])) {
370
+			$box_label = is_array($this->_labels['publishbox'])
371
+						 && isset($this->_labels['publishbox'][ $this->_req_action ])
372
+				? $this->_labels['publishbox'][ $this->_req_action ]
373
+				: $this->_labels['publishbox'];
374
+			add_meta_box(
375
+				'submitdiv',
376
+				$box_label,
377
+				'post_submit_meta_box',
378
+				$this->_cpt_routes[ $this->_req_action ],
379
+				'side',
380
+				'core'
381
+			);
382
+		}
383
+		// let's add page_templates metabox if this cpt added support for it.
384
+		if ($this->_supports_page_templates($this->_cpt_object->name)) {
385
+			add_meta_box(
386
+				'page_templates',
387
+				__('Page Template', 'event_espresso'),
388
+				array($this, 'page_template_meta_box'),
389
+				$this->_cpt_routes[ $this->_req_action ],
390
+				'side',
391
+				'default'
392
+			);
393
+		}
394
+		// this is a filter that allows the addition of extra html after the permalink field on the wp post edit-form
395
+		if (method_exists($this, 'extra_permalink_field_buttons')) {
396
+			add_filter('get_sample_permalink_html', array($this, 'extra_permalink_field_buttons'), 10, 4);
397
+		}
398
+		// add preview button
399
+		add_filter('get_sample_permalink_html', array($this, 'preview_button_html'), 5, 4);
400
+		// insert our own post_stati dropdown
401
+		add_action('post_submitbox_misc_actions', array($this, 'custom_post_stati_dropdown'), 10);
402
+		// This allows adding additional information to the publish post submitbox on the wp post edit form
403
+		if (method_exists($this, 'extra_misc_actions_publish_box')) {
404
+			add_action('post_submitbox_misc_actions', array($this, 'extra_misc_actions_publish_box'), 10);
405
+		}
406
+		// This allows for adding additional stuff after the title field on the wp post edit form.
407
+		// This is also before the wp_editor for post description field.
408
+		if (method_exists($this, 'edit_form_after_title')) {
409
+			add_action('edit_form_after_title', array($this, 'edit_form_after_title'), 10);
410
+		}
411
+		/**
412
+		 * Filtering WP's esc_url to capture urls pointing to core wp routes so they point to our route.
413
+		 */
414
+		add_filter('clean_url', array($this, 'switch_core_wp_urls_with_ours'), 10, 3);
415
+		parent::_load_page_dependencies();
416
+		// notice we are ALSO going to load the pagenow hook set for this route
417
+		// (see _before_page_setup for the reset of the pagenow global ).
418
+		// This is for any plugins that are doing things properly
419
+		// and hooking into the load page hook for core wp cpt routes.
420
+		global $pagenow;
421
+		add_action('load-' . $pagenow, array($this, 'modify_current_screen'), 20);
422
+		do_action('load-' . $pagenow);
423
+		add_action('admin_enqueue_scripts', array($this, 'setup_autosave_hooks'), 30);
424
+		// we route REALLY early.
425
+		try {
426
+			$this->_route_admin_request();
427
+		} catch (EE_Error $e) {
428
+			$e->get_error();
429
+		}
430
+	}
431
+
432
+
433
+	/**
434
+	 * Since we don't want users going to default core wp routes, this will check any wp urls run through the
435
+	 * esc_url() method and if we see a url matching a pattern for our routes, we'll modify it to point to OUR
436
+	 * route instead.
437
+	 *
438
+	 * @param string $good_protocol_url The escaped url.
439
+	 * @param string $original_url      The original url.
440
+	 * @param string $_context          The context sent to the esc_url method.
441
+	 * @return string possibly a new url for our route.
442
+	 */
443
+	public function switch_core_wp_urls_with_ours($good_protocol_url, $original_url, $_context)
444
+	{
445
+		$routes_to_match = array(
446
+			0 => array(
447
+				'edit.php?post_type=espresso_attendees',
448
+				'admin.php?page=espresso_registrations&action=contact_list',
449
+			),
450
+			1 => array(
451
+				'edit.php?post_type=' . $this->_cpt_object->name,
452
+				'admin.php?page=' . $this->_cpt_object->name,
453
+			),
454
+		);
455
+		foreach ($routes_to_match as $route_matches) {
456
+			if (strpos($good_protocol_url, $route_matches[0]) !== false) {
457
+				return str_replace($route_matches[0], $route_matches[1], $good_protocol_url);
458
+			}
459
+		}
460
+		return $good_protocol_url;
461
+	}
462
+
463
+
464
+	/**
465
+	 * Determine whether the current cpt supports page templates or not.
466
+	 *
467
+	 * @since %VER%
468
+	 * @param string $cpt_name The cpt slug we're checking on.
469
+	 * @return bool True supported, false not.
470
+	 * @throws InvalidArgumentException
471
+	 * @throws InvalidDataTypeException
472
+	 * @throws InvalidInterfaceException
473
+	 */
474
+	private function _supports_page_templates($cpt_name)
475
+	{
476
+		/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
477
+		$custom_post_types = $this->getLoader()->getShared(
478
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
479
+		);
480
+		$cpt_args = $custom_post_types->getDefinitions();
481
+		$cpt_args = isset($cpt_args[ $cpt_name ]) ? $cpt_args[ $cpt_name ]['args'] : array();
482
+		$cpt_has_support = ! empty($cpt_args['page_templates']);
483
+
484
+		// if the installed version of WP is > 4.7 we do some additional checks.
485
+		if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
486
+			$post_templates = wp_get_theme()->get_post_templates();
487
+			// if there are $post_templates for this cpt, then we return false for this method because
488
+			// that means we aren't going to load our page template manager and leave that up to the native
489
+			// cpt template manager.
490
+			$cpt_has_support = ! isset($post_templates[ $cpt_name ]) ? $cpt_has_support : false;
491
+		}
492
+
493
+		return $cpt_has_support;
494
+	}
495
+
496
+
497
+	/**
498
+	 * Callback for the page_templates metabox selector.
499
+	 *
500
+	 * @since %VER%
501
+	 * @return void
502
+	 */
503
+	public function page_template_meta_box()
504
+	{
505
+		global $post;
506
+		$template = '';
507
+
508
+		if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
509
+			$page_template_count = count(get_page_templates());
510
+		} else {
511
+			$page_template_count = count(get_page_templates($post));
512
+		};
513
+
514
+		if ($page_template_count) {
515
+			$page_template = get_post_meta($post->ID, '_wp_page_template', true);
516
+			$template = ! empty($page_template) ? $page_template : '';
517
+		}
518
+		?>
519 519
         <p><strong><?php _e('Template', 'event_espresso') ?></strong></p>
520 520
         <label class="screen-reader-text" for="page_template"><?php _e('Page Template', 'event_espresso') ?></label><select
521 521
         name="page_template" id="page_template">
@@ -523,471 +523,471 @@  discard block
 block discarded – undo
523 523
         <?php page_template_dropdown($template); ?>
524 524
     </select>
525 525
         <?php
526
-    }
527
-
528
-
529
-    /**
530
-     * if this post is a draft or scheduled post then we provide a preview button for user to click
531
-     * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
532
-     *
533
-     * @param  string $return    the current html
534
-     * @param  int    $id        the post id for the page
535
-     * @param  string $new_title What the title is
536
-     * @param  string $new_slug  what the slug is
537
-     * @return string            The new html string for the permalink area
538
-     */
539
-    public function preview_button_html($return, $id, $new_title, $new_slug)
540
-    {
541
-        $post = get_post($id);
542
-        if ('publish' !== get_post_status($post)) {
543
-            $return .= '<span_id="view-post-btn"><a target="_blank" href="'
544
-                       . get_preview_post_link($id)
545
-                       . '" class="button button-small">'
546
-                       . __('Preview', 'event_espresso')
547
-                       . '</a></span>'
548
-                       . "\n";
549
-        }
550
-        return $return;
551
-    }
552
-
553
-
554
-    /**
555
-     * add our custom post stati dropdown on the wp post page for this cpt
556
-     *
557
-     * @return void
558
-     */
559
-    public function custom_post_stati_dropdown()
560
-    {
561
-
562
-        $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
563
-        $cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
564
-            ? $statuses[ $this->_cpt_model_obj->status() ]
565
-            : '';
566
-        $template_args = array(
567
-            'cur_status'            => $this->_cpt_model_obj->status(),
568
-            'statuses'              => $statuses,
569
-            'cur_status_label'      => $cur_status_label,
570
-            'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
571
-        );
572
-        // we'll add a trash post status (WP doesn't add one for some reason)
573
-        if ($this->_cpt_model_obj->status() === 'trash') {
574
-            $template_args['cur_status_label'] = __('Trashed', 'event_espresso');
575
-            $statuses['trash'] = __('Trashed', 'event_espresso');
576
-            $template_args['statuses'] = $statuses;
577
-        }
578
-
579
-        $template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
580
-        EEH_Template::display_template($template, $template_args);
581
-    }
582
-
583
-
584
-    public function setup_autosave_hooks()
585
-    {
586
-        $this->_set_autosave_containers();
587
-        $this->_load_autosave_scripts_styles();
588
-    }
589
-
590
-
591
-    /**
592
-     * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
593
-     * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
594
-     * for the nonce in here, but then this method looks for two things:
595
-     * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
596
-     * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
597
-     * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
598
-     * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
599
-     * template args.
600
-     *    1. $template_args['error'] = IF there is an error you can add the message in here.
601
-     *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
602
-     *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
603
-     *    $this->_template_args['data']['items'] = array(
604
-     *        'event-datetime-ids' => '1,2,3';
605
-     *    );
606
-     *    Keep in mind the following things:
607
-     *    - "where" index is for the input with the id as that string.
608
-     *    - "what" index is what will be used for the value of that input.
609
-     *
610
-     * @return void
611
-     */
612
-    public function do_extra_autosave_stuff()
613
-    {
614
-        // next let's check for the autosave nonce (we'll use _verify_nonce )
615
-        $nonce = isset($this->_req_data['autosavenonce'])
616
-            ? $this->_req_data['autosavenonce']
617
-            : null;
618
-        $this->_verify_nonce($nonce, 'autosave');
619
-        // make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
620
-        if (! defined('DOING_AUTOSAVE')) {
621
-            define('DOING_AUTOSAVE', true);
622
-        }
623
-        // if we made it here then the nonce checked out.  Let's run our methods and actions
624
-        $autosave = "_ee_autosave_{$this->_current_view}";
625
-        if (method_exists($this, $autosave)) {
626
-            $this->$autosave();
627
-        } else {
628
-            $this->_template_args['success'] = true;
629
-        }
630
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
631
-        do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
632
-        // now let's return json
633
-        $this->_return_json();
634
-    }
635
-
636
-
637
-    /**
638
-     * This takes care of setting up default routes and pages that utilize the core WP admin pages.
639
-     * Child classes can override the defaults (in cases for adding metaboxes etc.)
640
-     * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
641
-     *
642
-     * @access protected
643
-     * @throws EE_Error
644
-     * @return void
645
-     */
646
-    protected function _extend_page_config_for_cpt()
647
-    {
648
-        // before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
649
-        if (isset($this->_req_data['page']) && $this->_req_data['page'] !== $this->page_slug) {
650
-            return;
651
-        }
652
-        // set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
653
-        if (! empty($this->_cpt_object)) {
654
-            $this->_page_routes = array_merge(
655
-                array(
656
-                    'create_new' => '_create_new_cpt_item',
657
-                    'edit'       => '_edit_cpt_item',
658
-                ),
659
-                $this->_page_routes
660
-            );
661
-            $this->_page_config = array_merge(
662
-                array(
663
-                    'create_new' => array(
664
-                        'nav'           => array(
665
-                            'label' => $this->_cpt_object->labels->add_new_item,
666
-                            'order' => 5,
667
-                        ),
668
-                        'require_nonce' => false,
669
-                    ),
670
-                    'edit'       => array(
671
-                        'nav'           => array(
672
-                            'label'      => $this->_cpt_object->labels->edit_item,
673
-                            'order'      => 5,
674
-                            'persistent' => false,
675
-                            'url'        => '',
676
-                        ),
677
-                        'require_nonce' => false,
678
-                    ),
679
-                ),
680
-                $this->_page_config
681
-            );
682
-        }
683
-        // load the next section only if this is a matching cpt route as set in the cpt routes array.
684
-        if (! isset($this->_cpt_routes[ $this->_req_action ])) {
685
-            return;
686
-        }
687
-        $this->_cpt_route = isset($this->_cpt_routes[ $this->_req_action ]) ? true : false;
688
-        // add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
689
-        if (empty($this->_cpt_object)) {
690
-            $msg = sprintf(
691
-                __(
692
-                    'This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).',
693
-                    'event_espresso'
694
-                ),
695
-                $this->page_slug,
696
-                $this->_req_action,
697
-                get_class($this)
698
-            );
699
-            throw new EE_Error($msg);
700
-        }
701
-        if ($this->_cpt_route) {
702
-            $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
703
-            $this->_set_model_object($id);
704
-        }
705
-    }
706
-
707
-
708
-    /**
709
-     * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
710
-     *
711
-     * @access protected
712
-     * @param int    $id       The id to retrieve the model object for. If empty we set a default object.
713
-     * @param bool   $ignore_route_check
714
-     * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
715
-     * @throws EE_Error
716
-     * @throws InvalidArgumentException
717
-     * @throws InvalidDataTypeException
718
-     * @throws InvalidInterfaceException
719
-     * @throws ReflectionException
720
-     */
721
-    protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
722
-    {
723
-        $model = null;
724
-        if (empty($this->_cpt_model_names)
725
-            || (
726
-                ! $ignore_route_check
727
-                && ! isset($this->_cpt_routes[ $this->_req_action ])
728
-            ) || (
729
-                $this->_cpt_model_obj instanceof EE_CPT_Base
730
-                && $this->_cpt_model_obj->ID() === $id
731
-            )
732
-        ) {
733
-            // get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
734
-            return;
735
-        }
736
-        // if ignore_route_check is true, then get the model name via CustomPostTypeDefinitions
737
-        if ($ignore_route_check) {
738
-            $post_type = get_post_type($id);
739
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
740
-            $custom_post_types = $this->getLoader()->getShared(
741
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
742
-            );
743
-            $model_names = $custom_post_types->getCustomPostTypeModelNames($post_type);
744
-            if (isset($model_names[ $post_type ])) {
745
-                $model = EE_Registry::instance()->load_model($model_names[ $post_type ]);
746
-            }
747
-        } else {
748
-            $model = EE_Registry::instance()->load_model($this->_cpt_model_names[ $this->_req_action ]);
749
-        }
750
-        if ($model instanceof EEM_Base) {
751
-            $this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
752
-        }
753
-        do_action(
754
-            'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
755
-            $this->_cpt_model_obj,
756
-            $req_type
757
-        );
758
-    }
759
-
760
-
761
-    /**
762
-     * admin_init_global
763
-     * This runs all the code that we want executed within the WP admin_init hook.
764
-     * This method executes for ALL EE Admin pages.
765
-     *
766
-     * @access public
767
-     * @return void
768
-     */
769
-    public function admin_init_global()
770
-    {
771
-        $post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
772
-        // its possible this is a new save so let's catch that instead
773
-        $post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
774
-        $post_type = $post ? $post->post_type : false;
775
-        $current_route = isset($this->_req_data['current_route'])
776
-            ? $this->_req_data['current_route']
777
-            : 'shouldneverwork';
778
-        $route_to_check = $post_type && isset($this->_cpt_routes[ $current_route ])
779
-            ? $this->_cpt_routes[ $current_route ]
780
-            : '';
781
-        add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
782
-        add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
783
-        if ($post_type === $route_to_check) {
784
-            add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
785
-        }
786
-        // now let's filter redirect if we're on a revision page and the revision is for an event CPT.
787
-        $revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
788
-        if (! empty($revision)) {
789
-            $action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
790
-            // doing a restore?
791
-            if (! empty($action) && $action === 'restore') {
792
-                // get post for revision
793
-                $rev_post = get_post($revision);
794
-                $rev_parent = get_post($rev_post->post_parent);
795
-                // only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
796
-                if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
797
-                    add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
798
-                    // restores of revisions
799
-                    add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
800
-                }
801
-            }
802
-        }
803
-        // NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
804
-        if ($post_type && $post_type === $route_to_check) {
805
-            // $post_id, $post
806
-            add_action('save_post', array($this, 'insert_update'), 10, 3);
807
-            // $post_id
808
-            add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
809
-            add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
810
-            add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
811
-            add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
812
-        }
813
-    }
814
-
815
-
816
-    /**
817
-     * Callback for the WordPress trashed_post hook.
818
-     * Execute some basic checks before calling the trash_cpt_item declared in the child class.
819
-     *
820
-     * @param int $post_id
821
-     * @throws \EE_Error
822
-     */
823
-    public function before_trash_cpt_item($post_id)
824
-    {
825
-        $this->_set_model_object($post_id, true, 'trash');
826
-        // if our cpt object isn't existent then get out immediately.
827
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
828
-            return;
829
-        }
830
-        $this->trash_cpt_item($post_id);
831
-    }
832
-
833
-
834
-    /**
835
-     * Callback for the WordPress untrashed_post hook.
836
-     * Execute some basic checks before calling the restore_cpt_method in the child class.
837
-     *
838
-     * @param $post_id
839
-     * @throws \EE_Error
840
-     */
841
-    public function before_restore_cpt_item($post_id)
842
-    {
843
-        $this->_set_model_object($post_id, true, 'restore');
844
-        // if our cpt object isn't existent then get out immediately.
845
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
846
-            return;
847
-        }
848
-        $this->restore_cpt_item($post_id);
849
-    }
850
-
851
-
852
-    /**
853
-     * Callback for the WordPress after_delete_post hook.
854
-     * Execute some basic checks before calling the delete_cpt_item method in the child class.
855
-     *
856
-     * @param $post_id
857
-     * @throws \EE_Error
858
-     */
859
-    public function before_delete_cpt_item($post_id)
860
-    {
861
-        $this->_set_model_object($post_id, true, 'delete');
862
-        // if our cpt object isn't existent then get out immediately.
863
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
864
-            return;
865
-        }
866
-        $this->delete_cpt_item($post_id);
867
-    }
868
-
869
-
870
-    /**
871
-     * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
872
-     * accordingly.
873
-     *
874
-     * @access public
875
-     * @throws EE_Error
876
-     * @return void
877
-     */
878
-    public function verify_cpt_object()
879
-    {
880
-        $label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
881
-        // verify event object
882
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
883
-            throw new EE_Error(
884
-                sprintf(
885
-                    __(
886
-                        'Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
887
-                        'event_espresso'
888
-                    ),
889
-                    $label
890
-                )
891
-            );
892
-        }
893
-        // if auto-draft then throw an error
894
-        if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
895
-            EE_Error::overwrite_errors();
896
-            EE_Error::add_error(
897
-                sprintf(
898
-                    __(
899
-                        'This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.',
900
-                        'event_espresso'
901
-                    ),
902
-                    $label
903
-                ),
904
-                __FILE__,
905
-                __FUNCTION__,
906
-                __LINE__
907
-            );
908
-        }
909
-    }
910
-
911
-
912
-    /**
913
-     * admin_footer_scripts_global
914
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
915
-     * will apply on ALL EE_Admin pages.
916
-     *
917
-     * @access public
918
-     * @return void
919
-     */
920
-    public function admin_footer_scripts_global()
921
-    {
922
-        $this->_add_admin_page_ajax_loading_img();
923
-        $this->_add_admin_page_overlay();
924
-    }
925
-
926
-
927
-    /**
928
-     * add in any global scripts for cpt routes
929
-     *
930
-     * @return void
931
-     */
932
-    public function load_global_scripts_styles()
933
-    {
934
-        parent::load_global_scripts_styles();
935
-        if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
936
-            // setup custom post status object for localize script but only if we've got a cpt object
937
-            $statuses = $this->_cpt_model_obj->get_custom_post_statuses();
938
-            if (! empty($statuses)) {
939
-                // get ALL statuses!
940
-                $statuses = $this->_cpt_model_obj->get_all_post_statuses();
941
-                // setup object
942
-                $ee_cpt_statuses = array();
943
-                foreach ($statuses as $status => $label) {
944
-                    $ee_cpt_statuses[ $status ] = array(
945
-                        'label'      => $label,
946
-                        'save_label' => sprintf(
947
-                            wp_strip_all_tags(__('Save as %s', 'event_espresso')),
948
-                            $label
949
-                        ),
950
-                    );
951
-                }
952
-                wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
953
-            }
954
-        }
955
-    }
956
-
957
-
958
-    /**
959
-     * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
960
-     * insert/updates
961
-     *
962
-     * @param  int     $post_id ID of post being updated
963
-     * @param  WP_Post $post    Post object from WP
964
-     * @param  bool    $update  Whether this is an update or a new save.
965
-     * @return void
966
-     * @throws \EE_Error
967
-     */
968
-    public function insert_update($post_id, $post, $update)
969
-    {
970
-        // make sure that if this is a revision OR trash action that we don't do any updates!
971
-        if (isset($this->_req_data['action'])
972
-            && (
973
-                $this->_req_data['action'] === 'restore'
974
-                || $this->_req_data['action'] === 'trash'
975
-            )
976
-        ) {
977
-            return;
978
-        }
979
-        $this->_set_model_object($post_id, true, 'insert_update');
980
-        // if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
981
-        if ($update
982
-            && (
983
-                ! $this->_cpt_model_obj instanceof EE_CPT_Base
984
-                || $this->_cpt_model_obj->ID() !== $post_id
985
-            )
986
-        ) {
987
-            return;
988
-        }
989
-        // check for autosave and update our req_data property accordingly.
990
-        /*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
526
+	}
527
+
528
+
529
+	/**
530
+	 * if this post is a draft or scheduled post then we provide a preview button for user to click
531
+	 * Method is called from parent and is hooked into the wp 'get_sample_permalink_html' filter.
532
+	 *
533
+	 * @param  string $return    the current html
534
+	 * @param  int    $id        the post id for the page
535
+	 * @param  string $new_title What the title is
536
+	 * @param  string $new_slug  what the slug is
537
+	 * @return string            The new html string for the permalink area
538
+	 */
539
+	public function preview_button_html($return, $id, $new_title, $new_slug)
540
+	{
541
+		$post = get_post($id);
542
+		if ('publish' !== get_post_status($post)) {
543
+			$return .= '<span_id="view-post-btn"><a target="_blank" href="'
544
+					   . get_preview_post_link($id)
545
+					   . '" class="button button-small">'
546
+					   . __('Preview', 'event_espresso')
547
+					   . '</a></span>'
548
+					   . "\n";
549
+		}
550
+		return $return;
551
+	}
552
+
553
+
554
+	/**
555
+	 * add our custom post stati dropdown on the wp post page for this cpt
556
+	 *
557
+	 * @return void
558
+	 */
559
+	public function custom_post_stati_dropdown()
560
+	{
561
+
562
+		$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
563
+		$cur_status_label = array_key_exists($this->_cpt_model_obj->status(), $statuses)
564
+			? $statuses[ $this->_cpt_model_obj->status() ]
565
+			: '';
566
+		$template_args = array(
567
+			'cur_status'            => $this->_cpt_model_obj->status(),
568
+			'statuses'              => $statuses,
569
+			'cur_status_label'      => $cur_status_label,
570
+			'localized_status_save' => sprintf(__('Save %s', 'event_espresso'), $cur_status_label),
571
+		);
572
+		// we'll add a trash post status (WP doesn't add one for some reason)
573
+		if ($this->_cpt_model_obj->status() === 'trash') {
574
+			$template_args['cur_status_label'] = __('Trashed', 'event_espresso');
575
+			$statuses['trash'] = __('Trashed', 'event_espresso');
576
+			$template_args['statuses'] = $statuses;
577
+		}
578
+
579
+		$template = EE_ADMIN_TEMPLATE . 'status_dropdown.template.php';
580
+		EEH_Template::display_template($template, $template_args);
581
+	}
582
+
583
+
584
+	public function setup_autosave_hooks()
585
+	{
586
+		$this->_set_autosave_containers();
587
+		$this->_load_autosave_scripts_styles();
588
+	}
589
+
590
+
591
+	/**
592
+	 * This is run on all WordPress autosaves AFTER the autosave is complete and sends along a $_POST object (available
593
+	 * in $this->_req_data) containing: post_ID of the saved post autosavenonce for the saved post We'll do the check
594
+	 * for the nonce in here, but then this method looks for two things:
595
+	 * 1. Execute a method (if exists) matching 'ee_autosave_' and appended with the given route. OR
596
+	 * 2. do_actions() for global or class specific actions that have been registered (for plugins/addons not in an
597
+	 * EE_Admin_Page class. PLEASE NOTE: Data will be returned using the _return_json() object and so the
598
+	 * $_template_args property should be used to hold the $data array.  We're expecting the following things set in
599
+	 * template args.
600
+	 *    1. $template_args['error'] = IF there is an error you can add the message in here.
601
+	 *    2. $template_args['data']['items'] = an array of items that are setup in key index pairs of 'where_values_go'
602
+	 *    => 'values_to_add'.  In other words, for the datetime metabox we'll have something like
603
+	 *    $this->_template_args['data']['items'] = array(
604
+	 *        'event-datetime-ids' => '1,2,3';
605
+	 *    );
606
+	 *    Keep in mind the following things:
607
+	 *    - "where" index is for the input with the id as that string.
608
+	 *    - "what" index is what will be used for the value of that input.
609
+	 *
610
+	 * @return void
611
+	 */
612
+	public function do_extra_autosave_stuff()
613
+	{
614
+		// next let's check for the autosave nonce (we'll use _verify_nonce )
615
+		$nonce = isset($this->_req_data['autosavenonce'])
616
+			? $this->_req_data['autosavenonce']
617
+			: null;
618
+		$this->_verify_nonce($nonce, 'autosave');
619
+		// make sure we define doing autosave (cause WP isn't triggering this we want to make sure we define it)
620
+		if (! defined('DOING_AUTOSAVE')) {
621
+			define('DOING_AUTOSAVE', true);
622
+		}
623
+		// if we made it here then the nonce checked out.  Let's run our methods and actions
624
+		$autosave = "_ee_autosave_{$this->_current_view}";
625
+		if (method_exists($this, $autosave)) {
626
+			$this->$autosave();
627
+		} else {
628
+			$this->_template_args['success'] = true;
629
+		}
630
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__global_after', $this);
631
+		do_action('AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_' . get_class($this), $this);
632
+		// now let's return json
633
+		$this->_return_json();
634
+	}
635
+
636
+
637
+	/**
638
+	 * This takes care of setting up default routes and pages that utilize the core WP admin pages.
639
+	 * Child classes can override the defaults (in cases for adding metaboxes etc.)
640
+	 * but take care that you include the defaults here otherwise your core WP admin pages for the cpt won't work!
641
+	 *
642
+	 * @access protected
643
+	 * @throws EE_Error
644
+	 * @return void
645
+	 */
646
+	protected function _extend_page_config_for_cpt()
647
+	{
648
+		// before doing anything we need to make sure this runs ONLY when the loaded page matches the set page_slug
649
+		if (isset($this->_req_data['page']) && $this->_req_data['page'] !== $this->page_slug) {
650
+			return;
651
+		}
652
+		// set page routes and page config but ONLY if we're not viewing a custom setup cpt route as defined in _cpt_routes
653
+		if (! empty($this->_cpt_object)) {
654
+			$this->_page_routes = array_merge(
655
+				array(
656
+					'create_new' => '_create_new_cpt_item',
657
+					'edit'       => '_edit_cpt_item',
658
+				),
659
+				$this->_page_routes
660
+			);
661
+			$this->_page_config = array_merge(
662
+				array(
663
+					'create_new' => array(
664
+						'nav'           => array(
665
+							'label' => $this->_cpt_object->labels->add_new_item,
666
+							'order' => 5,
667
+						),
668
+						'require_nonce' => false,
669
+					),
670
+					'edit'       => array(
671
+						'nav'           => array(
672
+							'label'      => $this->_cpt_object->labels->edit_item,
673
+							'order'      => 5,
674
+							'persistent' => false,
675
+							'url'        => '',
676
+						),
677
+						'require_nonce' => false,
678
+					),
679
+				),
680
+				$this->_page_config
681
+			);
682
+		}
683
+		// load the next section only if this is a matching cpt route as set in the cpt routes array.
684
+		if (! isset($this->_cpt_routes[ $this->_req_action ])) {
685
+			return;
686
+		}
687
+		$this->_cpt_route = isset($this->_cpt_routes[ $this->_req_action ]) ? true : false;
688
+		// add_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', array( $this, 'modify_current_screen') );
689
+		if (empty($this->_cpt_object)) {
690
+			$msg = sprintf(
691
+				__(
692
+					'This page has been set as being related to a registered custom post type, however, the custom post type object could not be retrieved. There are two possible reasons for this:  1. The "%s" does not match a registered post type. or 2. The custom post type is not registered for the "%s" action as indexed in the "$_cpt_routes" property on this class (%s).',
693
+					'event_espresso'
694
+				),
695
+				$this->page_slug,
696
+				$this->_req_action,
697
+				get_class($this)
698
+			);
699
+			throw new EE_Error($msg);
700
+		}
701
+		if ($this->_cpt_route) {
702
+			$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
703
+			$this->_set_model_object($id);
704
+		}
705
+	}
706
+
707
+
708
+	/**
709
+	 * Sets the _cpt_model_object property using what has been set for the _cpt_model_name and a given id.
710
+	 *
711
+	 * @access protected
712
+	 * @param int    $id       The id to retrieve the model object for. If empty we set a default object.
713
+	 * @param bool   $ignore_route_check
714
+	 * @param string $req_type whether the current route is for inserting, updating, or deleting the CPT
715
+	 * @throws EE_Error
716
+	 * @throws InvalidArgumentException
717
+	 * @throws InvalidDataTypeException
718
+	 * @throws InvalidInterfaceException
719
+	 * @throws ReflectionException
720
+	 */
721
+	protected function _set_model_object($id = null, $ignore_route_check = false, $req_type = '')
722
+	{
723
+		$model = null;
724
+		if (empty($this->_cpt_model_names)
725
+			|| (
726
+				! $ignore_route_check
727
+				&& ! isset($this->_cpt_routes[ $this->_req_action ])
728
+			) || (
729
+				$this->_cpt_model_obj instanceof EE_CPT_Base
730
+				&& $this->_cpt_model_obj->ID() === $id
731
+			)
732
+		) {
733
+			// get out cuz we either don't have a model name OR the object has already been set and it has the same id as what has been sent.
734
+			return;
735
+		}
736
+		// if ignore_route_check is true, then get the model name via CustomPostTypeDefinitions
737
+		if ($ignore_route_check) {
738
+			$post_type = get_post_type($id);
739
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
740
+			$custom_post_types = $this->getLoader()->getShared(
741
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
742
+			);
743
+			$model_names = $custom_post_types->getCustomPostTypeModelNames($post_type);
744
+			if (isset($model_names[ $post_type ])) {
745
+				$model = EE_Registry::instance()->load_model($model_names[ $post_type ]);
746
+			}
747
+		} else {
748
+			$model = EE_Registry::instance()->load_model($this->_cpt_model_names[ $this->_req_action ]);
749
+		}
750
+		if ($model instanceof EEM_Base) {
751
+			$this->_cpt_model_obj = ! empty($id) ? $model->get_one_by_ID($id) : $model->create_default_object();
752
+		}
753
+		do_action(
754
+			'AHEE__EE_Admin_Page_CPT__set_model_object__after_set_object',
755
+			$this->_cpt_model_obj,
756
+			$req_type
757
+		);
758
+	}
759
+
760
+
761
+	/**
762
+	 * admin_init_global
763
+	 * This runs all the code that we want executed within the WP admin_init hook.
764
+	 * This method executes for ALL EE Admin pages.
765
+	 *
766
+	 * @access public
767
+	 * @return void
768
+	 */
769
+	public function admin_init_global()
770
+	{
771
+		$post = isset($this->_req_data['post']) ? get_post($this->_req_data['post']) : null;
772
+		// its possible this is a new save so let's catch that instead
773
+		$post = isset($this->_req_data['post_ID']) ? get_post($this->_req_data['post_ID']) : $post;
774
+		$post_type = $post ? $post->post_type : false;
775
+		$current_route = isset($this->_req_data['current_route'])
776
+			? $this->_req_data['current_route']
777
+			: 'shouldneverwork';
778
+		$route_to_check = $post_type && isset($this->_cpt_routes[ $current_route ])
779
+			? $this->_cpt_routes[ $current_route ]
780
+			: '';
781
+		add_filter('get_delete_post_link', array($this, 'modify_delete_post_link'), 10, 3);
782
+		add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 3);
783
+		if ($post_type === $route_to_check) {
784
+			add_filter('redirect_post_location', array($this, 'cpt_post_location_redirect'), 10, 2);
785
+		}
786
+		// now let's filter redirect if we're on a revision page and the revision is for an event CPT.
787
+		$revision = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
788
+		if (! empty($revision)) {
789
+			$action = isset($this->_req_data['action']) ? $this->_req_data['action'] : null;
790
+			// doing a restore?
791
+			if (! empty($action) && $action === 'restore') {
792
+				// get post for revision
793
+				$rev_post = get_post($revision);
794
+				$rev_parent = get_post($rev_post->post_parent);
795
+				// only do our redirect filter AND our restore revision action if the post_type for the parent is one of our cpts.
796
+				if ($rev_parent && $rev_parent->post_type === $this->page_slug) {
797
+					add_filter('wp_redirect', array($this, 'revision_redirect'), 10, 2);
798
+					// restores of revisions
799
+					add_action('wp_restore_post_revision', array($this, 'restore_revision'), 10, 2);
800
+				}
801
+			}
802
+		}
803
+		// NOTE we ONLY want to run these hooks if we're on the right class for the given post type.  Otherwise we could see some really freaky things happen!
804
+		if ($post_type && $post_type === $route_to_check) {
805
+			// $post_id, $post
806
+			add_action('save_post', array($this, 'insert_update'), 10, 3);
807
+			// $post_id
808
+			add_action('trashed_post', array($this, 'before_trash_cpt_item'), 10);
809
+			add_action('trashed_post', array($this, 'dont_permanently_delete_ee_cpts'), 10);
810
+			add_action('untrashed_post', array($this, 'before_restore_cpt_item'), 10);
811
+			add_action('after_delete_post', array($this, 'before_delete_cpt_item'), 10);
812
+		}
813
+	}
814
+
815
+
816
+	/**
817
+	 * Callback for the WordPress trashed_post hook.
818
+	 * Execute some basic checks before calling the trash_cpt_item declared in the child class.
819
+	 *
820
+	 * @param int $post_id
821
+	 * @throws \EE_Error
822
+	 */
823
+	public function before_trash_cpt_item($post_id)
824
+	{
825
+		$this->_set_model_object($post_id, true, 'trash');
826
+		// if our cpt object isn't existent then get out immediately.
827
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
828
+			return;
829
+		}
830
+		$this->trash_cpt_item($post_id);
831
+	}
832
+
833
+
834
+	/**
835
+	 * Callback for the WordPress untrashed_post hook.
836
+	 * Execute some basic checks before calling the restore_cpt_method in the child class.
837
+	 *
838
+	 * @param $post_id
839
+	 * @throws \EE_Error
840
+	 */
841
+	public function before_restore_cpt_item($post_id)
842
+	{
843
+		$this->_set_model_object($post_id, true, 'restore');
844
+		// if our cpt object isn't existent then get out immediately.
845
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
846
+			return;
847
+		}
848
+		$this->restore_cpt_item($post_id);
849
+	}
850
+
851
+
852
+	/**
853
+	 * Callback for the WordPress after_delete_post hook.
854
+	 * Execute some basic checks before calling the delete_cpt_item method in the child class.
855
+	 *
856
+	 * @param $post_id
857
+	 * @throws \EE_Error
858
+	 */
859
+	public function before_delete_cpt_item($post_id)
860
+	{
861
+		$this->_set_model_object($post_id, true, 'delete');
862
+		// if our cpt object isn't existent then get out immediately.
863
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base || $this->_cpt_model_obj->ID() !== $post_id) {
864
+			return;
865
+		}
866
+		$this->delete_cpt_item($post_id);
867
+	}
868
+
869
+
870
+	/**
871
+	 * This simply verifies if the cpt_model_object is instantiated for the given page and throws an error message
872
+	 * accordingly.
873
+	 *
874
+	 * @access public
875
+	 * @throws EE_Error
876
+	 * @return void
877
+	 */
878
+	public function verify_cpt_object()
879
+	{
880
+		$label = ! empty($this->_cpt_object) ? $this->_cpt_object->labels->singular_name : $this->page_label;
881
+		// verify event object
882
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
883
+			throw new EE_Error(
884
+				sprintf(
885
+					__(
886
+						'Something has gone wrong with the page load because we are unable to set up the object for the %1$s.  This usually happens when the given id for the page route is NOT for the correct custom post type for this page',
887
+						'event_espresso'
888
+					),
889
+					$label
890
+				)
891
+			);
892
+		}
893
+		// if auto-draft then throw an error
894
+		if ($this->_cpt_model_obj->get('status') === 'auto-draft') {
895
+			EE_Error::overwrite_errors();
896
+			EE_Error::add_error(
897
+				sprintf(
898
+					__(
899
+						'This %1$s was saved without a title, description, or excerpt which means that none of the extra details you added were saved properly.  All autodrafts will show up in the "draft" view of your event list table.  You can delete them from there. Please click the "Add %1$s" button to refresh and restart.',
900
+						'event_espresso'
901
+					),
902
+					$label
903
+				),
904
+				__FILE__,
905
+				__FUNCTION__,
906
+				__LINE__
907
+			);
908
+		}
909
+	}
910
+
911
+
912
+	/**
913
+	 * admin_footer_scripts_global
914
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
915
+	 * will apply on ALL EE_Admin pages.
916
+	 *
917
+	 * @access public
918
+	 * @return void
919
+	 */
920
+	public function admin_footer_scripts_global()
921
+	{
922
+		$this->_add_admin_page_ajax_loading_img();
923
+		$this->_add_admin_page_overlay();
924
+	}
925
+
926
+
927
+	/**
928
+	 * add in any global scripts for cpt routes
929
+	 *
930
+	 * @return void
931
+	 */
932
+	public function load_global_scripts_styles()
933
+	{
934
+		parent::load_global_scripts_styles();
935
+		if ($this->_cpt_model_obj instanceof EE_CPT_Base) {
936
+			// setup custom post status object for localize script but only if we've got a cpt object
937
+			$statuses = $this->_cpt_model_obj->get_custom_post_statuses();
938
+			if (! empty($statuses)) {
939
+				// get ALL statuses!
940
+				$statuses = $this->_cpt_model_obj->get_all_post_statuses();
941
+				// setup object
942
+				$ee_cpt_statuses = array();
943
+				foreach ($statuses as $status => $label) {
944
+					$ee_cpt_statuses[ $status ] = array(
945
+						'label'      => $label,
946
+						'save_label' => sprintf(
947
+							wp_strip_all_tags(__('Save as %s', 'event_espresso')),
948
+							$label
949
+						),
950
+					);
951
+				}
952
+				wp_localize_script('ee_admin_js', 'eeCPTstatuses', $ee_cpt_statuses);
953
+			}
954
+		}
955
+	}
956
+
957
+
958
+	/**
959
+	 * This is a wrapper for the insert/update routes for cpt items so we can add things that are common to ALL
960
+	 * insert/updates
961
+	 *
962
+	 * @param  int     $post_id ID of post being updated
963
+	 * @param  WP_Post $post    Post object from WP
964
+	 * @param  bool    $update  Whether this is an update or a new save.
965
+	 * @return void
966
+	 * @throws \EE_Error
967
+	 */
968
+	public function insert_update($post_id, $post, $update)
969
+	{
970
+		// make sure that if this is a revision OR trash action that we don't do any updates!
971
+		if (isset($this->_req_data['action'])
972
+			&& (
973
+				$this->_req_data['action'] === 'restore'
974
+				|| $this->_req_data['action'] === 'trash'
975
+			)
976
+		) {
977
+			return;
978
+		}
979
+		$this->_set_model_object($post_id, true, 'insert_update');
980
+		// if our cpt object is not instantiated and its NOT the same post_id as what is triggering this callback, then exit.
981
+		if ($update
982
+			&& (
983
+				! $this->_cpt_model_obj instanceof EE_CPT_Base
984
+				|| $this->_cpt_model_obj->ID() !== $post_id
985
+			)
986
+		) {
987
+			return;
988
+		}
989
+		// check for autosave and update our req_data property accordingly.
990
+		/*if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE && isset( $this->_req_data['ee_autosave_data'] ) ) {
991 991
             foreach( (array) $this->_req_data['ee_autosave_data'] as $id => $values ) {
992 992
 
993 993
                 foreach ( (array) $values as $key => $value ) {
@@ -997,532 +997,532 @@  discard block
 block discarded – undo
997 997
 
998 998
         }/**/ // TODO reactivate after autosave is implemented in 4.2
999 999
 
1000
-        // take care of updating any selected page_template IF this cpt supports it.
1001
-        if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
1002
-            // wp version aware.
1003
-            if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
1004
-                $page_templates = wp_get_theme()->get_page_templates();
1005
-            } else {
1006
-                $post->page_template = $this->_req_data['page_template'];
1007
-                $page_templates = wp_get_theme()->get_page_templates($post);
1008
-            }
1009
-            if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[ $this->_req_data['page_template'] ])) {
1010
-                EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1011
-            } else {
1012
-                update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
1013
-            }
1014
-        }
1015
-        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
1016
-            return;
1017
-        } //TODO we'll remove this after reimplementing autosave in 4.2
1018
-        $this->_insert_update_cpt_item($post_id, $post);
1019
-    }
1020
-
1021
-
1022
-    /**
1023
-     * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
1024
-     * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
1025
-     * so we don't have to check for our CPT.
1026
-     *
1027
-     * @param  int $post_id ID of the post
1028
-     * @return void
1029
-     */
1030
-    public function dont_permanently_delete_ee_cpts($post_id)
1031
-    {
1032
-        // only do this if we're actually processing one of our CPTs
1033
-        // if our cpt object isn't existent then get out immediately.
1034
-        if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1035
-            return;
1036
-        }
1037
-        delete_post_meta($post_id, '_wp_trash_meta_status');
1038
-        delete_post_meta($post_id, '_wp_trash_meta_time');
1039
-        // our cpts may have comments so let's take care of that too
1040
-        delete_post_meta($post_id, '_wp_trash_meta_comments_status');
1041
-    }
1042
-
1043
-
1044
-    /**
1045
-     * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
1046
-     * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1047
-     * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1048
-     *
1049
-     * @param  int $post_id     ID of cpt item
1050
-     * @param  int $revision_id ID of revision being restored
1051
-     * @return void
1052
-     */
1053
-    public function restore_revision($post_id, $revision_id)
1054
-    {
1055
-        $this->_restore_cpt_item($post_id, $revision_id);
1056
-        // global action
1057
-        do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1058
-        // class specific action so you can limit hooking into a specific page.
1059
-        do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     * @see restore_revision() for details
1065
-     * @param  int $post_id     ID of cpt item
1066
-     * @param  int $revision_id ID of revision for item
1067
-     * @return void
1068
-     */
1069
-    abstract protected function _restore_cpt_item($post_id, $revision_id);
1070
-
1071
-
1072
-    /**
1073
-     * Execution of this method is added to the end of the load_page_dependencies method in the parent
1074
-     * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1075
-     * To fix we have to reset the current_screen using the page_slug
1076
-     * (which is identical - or should be - to our registered_post_type id.)
1077
-     * Also, since the core WP file loads the admin_header.php for WP
1078
-     * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1079
-     * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1080
-     *
1081
-     * @return void
1082
-     */
1083
-    public function modify_current_screen()
1084
-    {
1085
-        // ONLY do this if the current page_route IS a cpt route
1086
-        if (! $this->_cpt_route) {
1087
-            return;
1088
-        }
1089
-        // routing things REALLY early b/c this is a cpt admin page
1090
-        set_current_screen($this->_cpt_routes[ $this->_req_action ]);
1091
-        $this->_current_screen = get_current_screen();
1092
-        $this->_current_screen->base = 'event-espresso';
1093
-        $this->_add_help_tabs(); // we make sure we add any help tabs back in!
1094
-        /*try {
1000
+		// take care of updating any selected page_template IF this cpt supports it.
1001
+		if ($this->_supports_page_templates($post->post_type) && ! empty($this->_req_data['page_template'])) {
1002
+			// wp version aware.
1003
+			if (RecommendedVersions::compareWordPressVersion('4.7', '>=')) {
1004
+				$page_templates = wp_get_theme()->get_page_templates();
1005
+			} else {
1006
+				$post->page_template = $this->_req_data['page_template'];
1007
+				$page_templates = wp_get_theme()->get_page_templates($post);
1008
+			}
1009
+			if ('default' != $this->_req_data['page_template'] && ! isset($page_templates[ $this->_req_data['page_template'] ])) {
1010
+				EE_Error::add_error(__('Invalid Page Template.', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1011
+			} else {
1012
+				update_post_meta($post_id, '_wp_page_template', $this->_req_data['page_template']);
1013
+			}
1014
+		}
1015
+		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
1016
+			return;
1017
+		} //TODO we'll remove this after reimplementing autosave in 4.2
1018
+		$this->_insert_update_cpt_item($post_id, $post);
1019
+	}
1020
+
1021
+
1022
+	/**
1023
+	 * This hooks into the wp_trash_post() function and removes the `_wp_trash_meta_status` and `_wp_trash_meta_time`
1024
+	 * post meta IF the trashed post is one of our CPT's - note this method should only be called with our cpt routes
1025
+	 * so we don't have to check for our CPT.
1026
+	 *
1027
+	 * @param  int $post_id ID of the post
1028
+	 * @return void
1029
+	 */
1030
+	public function dont_permanently_delete_ee_cpts($post_id)
1031
+	{
1032
+		// only do this if we're actually processing one of our CPTs
1033
+		// if our cpt object isn't existent then get out immediately.
1034
+		if (! $this->_cpt_model_obj instanceof EE_CPT_Base) {
1035
+			return;
1036
+		}
1037
+		delete_post_meta($post_id, '_wp_trash_meta_status');
1038
+		delete_post_meta($post_id, '_wp_trash_meta_time');
1039
+		// our cpts may have comments so let's take care of that too
1040
+		delete_post_meta($post_id, '_wp_trash_meta_comments_status');
1041
+	}
1042
+
1043
+
1044
+	/**
1045
+	 * This is a wrapper for the restore_cpt_revision route for cpt items so we can make sure that when a revision is
1046
+	 * triggered that we restore related items.  In order to work cpt classes MUST have a restore_cpt_revision method
1047
+	 * in them. We also have our OWN action in here so addons can hook into the restore process easily.
1048
+	 *
1049
+	 * @param  int $post_id     ID of cpt item
1050
+	 * @param  int $revision_id ID of revision being restored
1051
+	 * @return void
1052
+	 */
1053
+	public function restore_revision($post_id, $revision_id)
1054
+	{
1055
+		$this->_restore_cpt_item($post_id, $revision_id);
1056
+		// global action
1057
+		do_action('AHEE_EE_Admin_Page_CPT__restore_revision', $post_id, $revision_id);
1058
+		// class specific action so you can limit hooking into a specific page.
1059
+		do_action('AHEE_EE_Admin_Page_CPT_' . get_class($this) . '__restore_revision', $post_id, $revision_id);
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 * @see restore_revision() for details
1065
+	 * @param  int $post_id     ID of cpt item
1066
+	 * @param  int $revision_id ID of revision for item
1067
+	 * @return void
1068
+	 */
1069
+	abstract protected function _restore_cpt_item($post_id, $revision_id);
1070
+
1071
+
1072
+	/**
1073
+	 * Execution of this method is added to the end of the load_page_dependencies method in the parent
1074
+	 * so that we can fix a bug where default core metaboxes were not being called in the sidebar.
1075
+	 * To fix we have to reset the current_screen using the page_slug
1076
+	 * (which is identical - or should be - to our registered_post_type id.)
1077
+	 * Also, since the core WP file loads the admin_header.php for WP
1078
+	 * (and there are a bunch of other things edit-form-advanced.php loads that need to happen really early)
1079
+	 * we need to load it NOW, hence our _route_admin_request in here. (Otherwise screen options won't be set).
1080
+	 *
1081
+	 * @return void
1082
+	 */
1083
+	public function modify_current_screen()
1084
+	{
1085
+		// ONLY do this if the current page_route IS a cpt route
1086
+		if (! $this->_cpt_route) {
1087
+			return;
1088
+		}
1089
+		// routing things REALLY early b/c this is a cpt admin page
1090
+		set_current_screen($this->_cpt_routes[ $this->_req_action ]);
1091
+		$this->_current_screen = get_current_screen();
1092
+		$this->_current_screen->base = 'event-espresso';
1093
+		$this->_add_help_tabs(); // we make sure we add any help tabs back in!
1094
+		/*try {
1095 1095
             $this->_route_admin_request();
1096 1096
         } catch ( EE_Error $e ) {
1097 1097
             $e->get_error();
1098 1098
         }/**/
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * This allows child classes to modify the default editor title that appears when people add a new or edit an
1104
-     * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1105
-     * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1106
-     * default to be.
1107
-     *
1108
-     * @param string $title The new title (or existing if there is no editor_title defined)
1109
-     * @return string
1110
-     */
1111
-    public function add_custom_editor_default_title($title)
1112
-    {
1113
-        return isset($this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ])
1114
-            ? $this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ]
1115
-            : $title;
1116
-    }
1117
-
1118
-
1119
-    /**
1120
-     * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1121
-     *
1122
-     * @param string $shortlink   The already generated shortlink
1123
-     * @param int    $id          Post ID for this item
1124
-     * @param string $context     The context for the link
1125
-     * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1126
-     * @return string
1127
-     */
1128
-    public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1129
-    {
1130
-        if (! empty($id) && get_option('permalink_structure') !== '') {
1131
-            $post = get_post($id);
1132
-            if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1133
-                $shortlink = home_url('?p=' . $post->ID);
1134
-            }
1135
-        }
1136
-        return $shortlink;
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1142
-     * already run in modify_current_screen())
1143
-     *
1144
-     * @return void
1145
-     */
1146
-    public function route_admin_request()
1147
-    {
1148
-        if ($this->_cpt_route) {
1149
-            return;
1150
-        }
1151
-        try {
1152
-            $this->_route_admin_request();
1153
-        } catch (EE_Error $e) {
1154
-            $e->get_error();
1155
-        }
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1161
-     *
1162
-     * @return void
1163
-     */
1164
-    public function cpt_post_form_hidden_input()
1165
-    {
1166
-        echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1167
-        // we're also going to add the route value and the current page so we can direct autosave parsing correctly
1168
-        echo '<div id="ee-cpt-hidden-inputs">';
1169
-        echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1170
-        echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1171
-        echo '</div>';
1172
-    }
1173
-
1174
-
1175
-    /**
1176
-     * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1177
-     *
1178
-     * @param  string $location Original location url
1179
-     * @param  int    $status   Status for http header
1180
-     * @return string           new (or original) url to redirect to.
1181
-     */
1182
-    public function revision_redirect($location, $status)
1183
-    {
1184
-        // get revision
1185
-        $rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1186
-        // can't do anything without revision so let's get out if not present
1187
-        if (empty($rev_id)) {
1188
-            return $location;
1189
-        }
1190
-        // get rev_post_data
1191
-        $rev = get_post($rev_id);
1192
-        $admin_url = $this->_admin_base_url;
1193
-        $query_args = array(
1194
-            'action'   => 'edit',
1195
-            'post'     => $rev->post_parent,
1196
-            'revision' => $rev_id,
1197
-            'message'  => 5,
1198
-        );
1199
-        $this->_process_notices($query_args, true);
1200
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1201
-    }
1202
-
1203
-
1204
-    /**
1205
-     * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1206
-     *
1207
-     * @param  string $link    the original generated link
1208
-     * @param  int    $id      post id
1209
-     * @param  string $context optional, defaults to display.  How to write the '&'
1210
-     * @return string          the link
1211
-     */
1212
-    public function modify_edit_post_link($link, $id, $context)
1213
-    {
1214
-        $post = get_post($id);
1215
-        if (! isset($this->_req_data['action'])
1216
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1217
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1218
-        ) {
1219
-            return $link;
1220
-        }
1221
-        $query_args = array(
1222
-            'action' => isset($this->_cpt_edit_routes[ $post->post_type ])
1223
-                ? $this->_cpt_edit_routes[ $post->post_type ]
1224
-                : 'edit',
1225
-            'post'   => $id,
1226
-        );
1227
-        return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1228
-    }
1229
-
1230
-
1231
-    /**
1232
-     * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1233
-     * our routes.
1234
-     *
1235
-     * @param  string $delete_link  original delete link
1236
-     * @param  int    $post_id      id of cpt object
1237
-     * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1238
-     * @return string new delete link
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1242
-    {
1243
-        $post = get_post($post_id);
1244
-
1245
-        if (empty($this->_req_data['action'])
1246
-            || ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1247
-            || ! $post instanceof WP_Post
1248
-            || $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1249
-        ) {
1250
-            return $delete_link;
1251
-        }
1252
-        $this->_set_model_object($post->ID, true);
1253
-
1254
-        // returns something like `trash_event` or `trash_attendee` or `trash_venue`
1255
-        $action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1256
-
1257
-        return EE_Admin_Page::add_query_args_and_nonce(
1258
-            array(
1259
-                'page'   => $this->_req_data['page'],
1260
-                'action' => $action,
1261
-                $this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1262
-                         => $post->ID,
1263
-            ),
1264
-            admin_url()
1265
-        );
1266
-    }
1267
-
1268
-
1269
-    /**
1270
-     * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1271
-     * so that we can hijack the default redirect locations for wp custom post types
1272
-     * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1273
-     *
1274
-     * @param  string $location This is the incoming currently set redirect location
1275
-     * @param  string $post_id  This is the 'ID' value of the wp_posts table
1276
-     * @return string           the new location to redirect to
1277
-     */
1278
-    public function cpt_post_location_redirect($location, $post_id)
1279
-    {
1280
-        // we DO have a match so let's setup the url
1281
-        // we have to get the post to determine our route
1282
-        $post = get_post($post_id);
1283
-        $edit_route = $this->_cpt_edit_routes[ $post->post_type ];
1284
-        // shared query_args
1285
-        $query_args = array('action' => $edit_route, 'post' => $post_id);
1286
-        $admin_url = $this->_admin_base_url;
1287
-        if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1288
-            $status = get_post_status($post_id);
1289
-            if (isset($this->_req_data['publish'])) {
1290
-                switch ($status) {
1291
-                    case 'pending':
1292
-                        $message = 8;
1293
-                        break;
1294
-                    case 'future':
1295
-                        $message = 9;
1296
-                        break;
1297
-                    default:
1298
-                        $message = 6;
1299
-                }
1300
-            } else {
1301
-                $message = 'draft' === $status ? 10 : 1;
1302
-            }
1303
-        } elseif (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1304
-            $message = 2;
1305
-        } elseif (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1306
-            $message = 3;
1307
-        } elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1308
-            $message = 7;
1309
-        } else {
1310
-            $message = 4;
1311
-        }
1312
-        // change the message if the post type is not viewable on the frontend
1313
-        $this->_cpt_object = get_post_type_object($post->post_type);
1314
-        $message = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1315
-        $query_args = array_merge(array('message' => $message), $query_args);
1316
-        $this->_process_notices($query_args, true);
1317
-        return self::add_query_args_and_nonce($query_args, $admin_url);
1318
-    }
1319
-
1320
-
1321
-    /**
1322
-     * This method is called to inject nav tabs on core WP cpt pages
1323
-     *
1324
-     * @access public
1325
-     * @return void
1326
-     */
1327
-    public function inject_nav_tabs()
1328
-    {
1329
-        // can we hijack and insert the nav_tabs?
1330
-        $nav_tabs = $this->_get_main_nav_tabs();
1331
-        // first close off existing form tag
1332
-        $html = '>';
1333
-        $html .= $nav_tabs;
1334
-        // now let's handle the remaining tag ( missing ">" is CORRECT )
1335
-        $html .= '<span></span';
1336
-        echo $html;
1337
-    }
1338
-
1339
-
1340
-    /**
1341
-     * This just sets up the post update messages when an update form is loaded
1342
-     *
1343
-     * @access public
1344
-     * @param  array $messages the original messages array
1345
-     * @return array           the new messages array
1346
-     */
1347
-    public function post_update_messages($messages)
1348
-    {
1349
-        global $post;
1350
-        $id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1351
-        $id = empty($id) && is_object($post) ? $post->ID : null;
1352
-        /*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * This allows child classes to modify the default editor title that appears when people add a new or edit an
1104
+	 * existing CPT item.     * This uses the _labels property set by the child class via _define_page_props. Just make
1105
+	 * sure you have a key in _labels property that equals 'editor_title' and the value can be whatever you want the
1106
+	 * default to be.
1107
+	 *
1108
+	 * @param string $title The new title (or existing if there is no editor_title defined)
1109
+	 * @return string
1110
+	 */
1111
+	public function add_custom_editor_default_title($title)
1112
+	{
1113
+		return isset($this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ])
1114
+			? $this->_labels['editor_title'][ $this->_cpt_routes[ $this->_req_action ] ]
1115
+			: $title;
1116
+	}
1117
+
1118
+
1119
+	/**
1120
+	 * hooks into the wp_get_shortlink button and makes sure that the shortlink gets generated
1121
+	 *
1122
+	 * @param string $shortlink   The already generated shortlink
1123
+	 * @param int    $id          Post ID for this item
1124
+	 * @param string $context     The context for the link
1125
+	 * @param bool   $allow_slugs Whether to allow post slugs in the shortlink.
1126
+	 * @return string
1127
+	 */
1128
+	public function add_shortlink_button_to_editor($shortlink, $id, $context, $allow_slugs)
1129
+	{
1130
+		if (! empty($id) && get_option('permalink_structure') !== '') {
1131
+			$post = get_post($id);
1132
+			if (isset($post->post_type) && $this->page_slug === $post->post_type) {
1133
+				$shortlink = home_url('?p=' . $post->ID);
1134
+			}
1135
+		}
1136
+		return $shortlink;
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * overriding the parent route_admin_request method so we DON'T run the route twice on cpt core page loads (it's
1142
+	 * already run in modify_current_screen())
1143
+	 *
1144
+	 * @return void
1145
+	 */
1146
+	public function route_admin_request()
1147
+	{
1148
+		if ($this->_cpt_route) {
1149
+			return;
1150
+		}
1151
+		try {
1152
+			$this->_route_admin_request();
1153
+		} catch (EE_Error $e) {
1154
+			$e->get_error();
1155
+		}
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * Add a hidden form input to cpt core pages so that we know to do redirects to our routes on saves
1161
+	 *
1162
+	 * @return void
1163
+	 */
1164
+	public function cpt_post_form_hidden_input()
1165
+	{
1166
+		echo '<input type="hidden" name="ee_cpt_item_redirect_url" value="' . $this->_admin_base_url . '" />';
1167
+		// we're also going to add the route value and the current page so we can direct autosave parsing correctly
1168
+		echo '<div id="ee-cpt-hidden-inputs">';
1169
+		echo '<input type="hidden" id="current_route" name="current_route" value="' . $this->_current_view . '" />';
1170
+		echo '<input type="hidden" id="current_page" name="current_page" value="' . $this->page_slug . '" />';
1171
+		echo '</div>';
1172
+	}
1173
+
1174
+
1175
+	/**
1176
+	 * This allows us to redirect the location of revision restores when they happen so it goes to our CPT routes.
1177
+	 *
1178
+	 * @param  string $location Original location url
1179
+	 * @param  int    $status   Status for http header
1180
+	 * @return string           new (or original) url to redirect to.
1181
+	 */
1182
+	public function revision_redirect($location, $status)
1183
+	{
1184
+		// get revision
1185
+		$rev_id = isset($this->_req_data['revision']) ? $this->_req_data['revision'] : null;
1186
+		// can't do anything without revision so let's get out if not present
1187
+		if (empty($rev_id)) {
1188
+			return $location;
1189
+		}
1190
+		// get rev_post_data
1191
+		$rev = get_post($rev_id);
1192
+		$admin_url = $this->_admin_base_url;
1193
+		$query_args = array(
1194
+			'action'   => 'edit',
1195
+			'post'     => $rev->post_parent,
1196
+			'revision' => $rev_id,
1197
+			'message'  => 5,
1198
+		);
1199
+		$this->_process_notices($query_args, true);
1200
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1201
+	}
1202
+
1203
+
1204
+	/**
1205
+	 * Modify the edit post link generated by wp core function so that EE CPTs get setup differently.
1206
+	 *
1207
+	 * @param  string $link    the original generated link
1208
+	 * @param  int    $id      post id
1209
+	 * @param  string $context optional, defaults to display.  How to write the '&'
1210
+	 * @return string          the link
1211
+	 */
1212
+	public function modify_edit_post_link($link, $id, $context)
1213
+	{
1214
+		$post = get_post($id);
1215
+		if (! isset($this->_req_data['action'])
1216
+			|| ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1217
+			|| $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1218
+		) {
1219
+			return $link;
1220
+		}
1221
+		$query_args = array(
1222
+			'action' => isset($this->_cpt_edit_routes[ $post->post_type ])
1223
+				? $this->_cpt_edit_routes[ $post->post_type ]
1224
+				: 'edit',
1225
+			'post'   => $id,
1226
+		);
1227
+		return self::add_query_args_and_nonce($query_args, $this->_admin_base_url);
1228
+	}
1229
+
1230
+
1231
+	/**
1232
+	 * Modify the trash link on our cpt edit pages so it has the required query var for triggering redirect properly on
1233
+	 * our routes.
1234
+	 *
1235
+	 * @param  string $delete_link  original delete link
1236
+	 * @param  int    $post_id      id of cpt object
1237
+	 * @param  bool   $force_delete whether this is forcing a hard delete instead of trash
1238
+	 * @return string new delete link
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function modify_delete_post_link($delete_link, $post_id, $force_delete)
1242
+	{
1243
+		$post = get_post($post_id);
1244
+
1245
+		if (empty($this->_req_data['action'])
1246
+			|| ! isset($this->_cpt_routes[ $this->_req_data['action'] ])
1247
+			|| ! $post instanceof WP_Post
1248
+			|| $post->post_type !== $this->_cpt_routes[ $this->_req_data['action'] ]
1249
+		) {
1250
+			return $delete_link;
1251
+		}
1252
+		$this->_set_model_object($post->ID, true);
1253
+
1254
+		// returns something like `trash_event` or `trash_attendee` or `trash_venue`
1255
+		$action = 'trash_' . str_replace('ee_', '', strtolower(get_class($this->_cpt_model_obj)));
1256
+
1257
+		return EE_Admin_Page::add_query_args_and_nonce(
1258
+			array(
1259
+				'page'   => $this->_req_data['page'],
1260
+				'action' => $action,
1261
+				$this->_cpt_model_obj->get_model()->get_primary_key_field()->get_name()
1262
+						 => $post->ID,
1263
+			),
1264
+			admin_url()
1265
+		);
1266
+	}
1267
+
1268
+
1269
+	/**
1270
+	 * This is the callback for the 'redirect_post_location' filter in wp-admin/post.php
1271
+	 * so that we can hijack the default redirect locations for wp custom post types
1272
+	 * that WE'RE using and send back to OUR routes.  This should only be hooked in on the right route.
1273
+	 *
1274
+	 * @param  string $location This is the incoming currently set redirect location
1275
+	 * @param  string $post_id  This is the 'ID' value of the wp_posts table
1276
+	 * @return string           the new location to redirect to
1277
+	 */
1278
+	public function cpt_post_location_redirect($location, $post_id)
1279
+	{
1280
+		// we DO have a match so let's setup the url
1281
+		// we have to get the post to determine our route
1282
+		$post = get_post($post_id);
1283
+		$edit_route = $this->_cpt_edit_routes[ $post->post_type ];
1284
+		// shared query_args
1285
+		$query_args = array('action' => $edit_route, 'post' => $post_id);
1286
+		$admin_url = $this->_admin_base_url;
1287
+		if (isset($this->_req_data['save']) || isset($this->_req_data['publish'])) {
1288
+			$status = get_post_status($post_id);
1289
+			if (isset($this->_req_data['publish'])) {
1290
+				switch ($status) {
1291
+					case 'pending':
1292
+						$message = 8;
1293
+						break;
1294
+					case 'future':
1295
+						$message = 9;
1296
+						break;
1297
+					default:
1298
+						$message = 6;
1299
+				}
1300
+			} else {
1301
+				$message = 'draft' === $status ? 10 : 1;
1302
+			}
1303
+		} elseif (isset($this->_req_data['addmeta']) && $this->_req_data['addmeta']) {
1304
+			$message = 2;
1305
+		} elseif (isset($this->_req_data['deletemeta']) && $this->_req_data['deletemeta']) {
1306
+			$message = 3;
1307
+		} elseif ($this->_req_data['action'] === 'post-quickpress-save-cont') {
1308
+			$message = 7;
1309
+		} else {
1310
+			$message = 4;
1311
+		}
1312
+		// change the message if the post type is not viewable on the frontend
1313
+		$this->_cpt_object = get_post_type_object($post->post_type);
1314
+		$message = $message === 1 && ! $this->_cpt_object->publicly_queryable ? 4 : $message;
1315
+		$query_args = array_merge(array('message' => $message), $query_args);
1316
+		$this->_process_notices($query_args, true);
1317
+		return self::add_query_args_and_nonce($query_args, $admin_url);
1318
+	}
1319
+
1320
+
1321
+	/**
1322
+	 * This method is called to inject nav tabs on core WP cpt pages
1323
+	 *
1324
+	 * @access public
1325
+	 * @return void
1326
+	 */
1327
+	public function inject_nav_tabs()
1328
+	{
1329
+		// can we hijack and insert the nav_tabs?
1330
+		$nav_tabs = $this->_get_main_nav_tabs();
1331
+		// first close off existing form tag
1332
+		$html = '>';
1333
+		$html .= $nav_tabs;
1334
+		// now let's handle the remaining tag ( missing ">" is CORRECT )
1335
+		$html .= '<span></span';
1336
+		echo $html;
1337
+	}
1338
+
1339
+
1340
+	/**
1341
+	 * This just sets up the post update messages when an update form is loaded
1342
+	 *
1343
+	 * @access public
1344
+	 * @param  array $messages the original messages array
1345
+	 * @return array           the new messages array
1346
+	 */
1347
+	public function post_update_messages($messages)
1348
+	{
1349
+		global $post;
1350
+		$id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1351
+		$id = empty($id) && is_object($post) ? $post->ID : null;
1352
+		/*$current_route = isset($this->_req_data['current_route']) ? $this->_req_data['current_route'] : 'shouldneverwork';
1353 1353
 
1354 1354
         $route_to_check = $post_type && isset( $this->_cpt_routes[$current_route]) ? $this->_cpt_routes[$current_route] : '';/**/
1355
-        $messages[ $post->post_type ] = array(
1356
-            0  => '', // Unused. Messages start at index 1.
1357
-            1  => sprintf(
1358
-                __('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1359
-                $this->_cpt_object->labels->singular_name,
1360
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1361
-                '</a>'
1362
-            ),
1363
-            2  => __('Custom field updated', 'event_espresso'),
1364
-            3  => __('Custom field deleted.', 'event_espresso'),
1365
-            4  => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1366
-            5  => isset($_GET['revision']) ? sprintf(
1367
-                __('%s restored to revision from %s', 'event_espresso'),
1368
-                $this->_cpt_object->labels->singular_name,
1369
-                wp_post_revision_title((int) $_GET['revision'], false)
1370
-            )
1371
-                : false,
1372
-            6  => sprintf(
1373
-                __('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1374
-                $this->_cpt_object->labels->singular_name,
1375
-                '<a href="' . esc_url(get_permalink($id)) . '">',
1376
-                '</a>'
1377
-            ),
1378
-            7  => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1379
-            8  => sprintf(
1380
-                __('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1381
-                $this->_cpt_object->labels->singular_name,
1382
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1383
-                '</a>'
1384
-            ),
1385
-            9  => sprintf(
1386
-                __('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1387
-                $this->_cpt_object->labels->singular_name,
1388
-                '<strong>' . date_i18n('M j, Y @ G:i', strtotime($post->post_date)) . '</strong>',
1389
-                '<a target="_blank" href="' . esc_url(get_permalink($id)),
1390
-                '</a>'
1391
-            ),
1392
-            10 => sprintf(
1393
-                __('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1394
-                $this->_cpt_object->labels->singular_name,
1395
-                '<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1396
-                '</a>'
1397
-            ),
1398
-        );
1399
-        return $messages;
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * default method for the 'create_new' route for cpt admin pages.
1405
-     * For reference what to include in here, see wp-admin/post-new.php
1406
-     *
1407
-     * @access  protected
1408
-     * @return void
1409
-     */
1410
-    protected function _create_new_cpt_item()
1411
-    {
1412
-        // gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1413
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1414
-        $post_type = $this->_cpt_routes[ $this->_req_action ];
1415
-        $post_type_object = $this->_cpt_object;
1416
-        $title = $post_type_object->labels->add_new_item;
1417
-        $post = $post = get_default_post_to_edit($this->_cpt_routes[ $this->_req_action ], true);
1418
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1419
-        // modify the default editor title field with default title.
1420
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1421
-        $this->loadEditorTemplate(true);
1422
-    }
1423
-
1424
-
1425
-    /**
1426
-     * Enqueues auto-save and loads the editor template
1427
-     *
1428
-     * @param bool $creating
1429
-     */
1430
-    private function loadEditorTemplate($creating = true)
1431
-    {
1432
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1433
-        // these vars are used by the template
1434
-        $editing = true;
1435
-        $post_ID = $post->ID;
1436
-        if (apply_filters('FHEE__EE_Admin_Page_CPT___create_new_cpt_item__replace_editor', false, $post) === false) {
1437
-            // only enqueue autosave when creating event (necessary to get permalink/url generated)
1438
-            // otherwise EE doesn't support autosave fully, so to prevent user confusion we disable it in edit context.
1439
-            if ($creating) {
1440
-                wp_enqueue_script('autosave');
1441
-            } else {
1442
-                if (isset($this->_cpt_routes[ $this->_req_data['action'] ])
1443
-                    && ! isset($this->_labels['hide_add_button_on_cpt_route'][ $this->_req_data['action'] ])
1444
-                ) {
1445
-                    $create_new_action = apply_filters(
1446
-                        'FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1447
-                        'create_new',
1448
-                        $this
1449
-                    );
1450
-                    $post_new_file = EE_Admin_Page::add_query_args_and_nonce(
1451
-                        array(
1452
-                            'action' => $create_new_action,
1453
-                            'page'   => $this->page_slug,
1454
-                        ),
1455
-                        'admin.php'
1456
-                    );
1457
-                }
1458
-            }
1459
-            include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1460
-        }
1461
-    }
1462
-
1463
-
1464
-    public function add_new_admin_page_global()
1465
-    {
1466
-        $admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1467
-        ?>
1355
+		$messages[ $post->post_type ] = array(
1356
+			0  => '', // Unused. Messages start at index 1.
1357
+			1  => sprintf(
1358
+				__('%1$s updated. %2$sView %1$s%3$s', 'event_espresso'),
1359
+				$this->_cpt_object->labels->singular_name,
1360
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1361
+				'</a>'
1362
+			),
1363
+			2  => __('Custom field updated', 'event_espresso'),
1364
+			3  => __('Custom field deleted.', 'event_espresso'),
1365
+			4  => sprintf(__('%1$s updated.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1366
+			5  => isset($_GET['revision']) ? sprintf(
1367
+				__('%s restored to revision from %s', 'event_espresso'),
1368
+				$this->_cpt_object->labels->singular_name,
1369
+				wp_post_revision_title((int) $_GET['revision'], false)
1370
+			)
1371
+				: false,
1372
+			6  => sprintf(
1373
+				__('%1$s published. %2$sView %1$s%3$s', 'event_espresso'),
1374
+				$this->_cpt_object->labels->singular_name,
1375
+				'<a href="' . esc_url(get_permalink($id)) . '">',
1376
+				'</a>'
1377
+			),
1378
+			7  => sprintf(__('%1$s saved.', 'event_espresso'), $this->_cpt_object->labels->singular_name),
1379
+			8  => sprintf(
1380
+				__('%1$s submitted. %2$sPreview %1$s%3$s', 'event_espresso'),
1381
+				$this->_cpt_object->labels->singular_name,
1382
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))) . '">',
1383
+				'</a>'
1384
+			),
1385
+			9  => sprintf(
1386
+				__('%1$s scheduled for: %2$s. %3$s">Preview %1$s%3$s', 'event_espresso'),
1387
+				$this->_cpt_object->labels->singular_name,
1388
+				'<strong>' . date_i18n('M j, Y @ G:i', strtotime($post->post_date)) . '</strong>',
1389
+				'<a target="_blank" href="' . esc_url(get_permalink($id)),
1390
+				'</a>'
1391
+			),
1392
+			10 => sprintf(
1393
+				__('%1$s draft updated. %2$s">Preview page%3$s', 'event_espresso'),
1394
+				$this->_cpt_object->labels->singular_name,
1395
+				'<a target="_blank" href="' . esc_url(add_query_arg('preview', 'true', get_permalink($id))),
1396
+				'</a>'
1397
+			),
1398
+		);
1399
+		return $messages;
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * default method for the 'create_new' route for cpt admin pages.
1405
+	 * For reference what to include in here, see wp-admin/post-new.php
1406
+	 *
1407
+	 * @access  protected
1408
+	 * @return void
1409
+	 */
1410
+	protected function _create_new_cpt_item()
1411
+	{
1412
+		// gather template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1413
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1414
+		$post_type = $this->_cpt_routes[ $this->_req_action ];
1415
+		$post_type_object = $this->_cpt_object;
1416
+		$title = $post_type_object->labels->add_new_item;
1417
+		$post = $post = get_default_post_to_edit($this->_cpt_routes[ $this->_req_action ], true);
1418
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1419
+		// modify the default editor title field with default title.
1420
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1421
+		$this->loadEditorTemplate(true);
1422
+	}
1423
+
1424
+
1425
+	/**
1426
+	 * Enqueues auto-save and loads the editor template
1427
+	 *
1428
+	 * @param bool $creating
1429
+	 */
1430
+	private function loadEditorTemplate($creating = true)
1431
+	{
1432
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1433
+		// these vars are used by the template
1434
+		$editing = true;
1435
+		$post_ID = $post->ID;
1436
+		if (apply_filters('FHEE__EE_Admin_Page_CPT___create_new_cpt_item__replace_editor', false, $post) === false) {
1437
+			// only enqueue autosave when creating event (necessary to get permalink/url generated)
1438
+			// otherwise EE doesn't support autosave fully, so to prevent user confusion we disable it in edit context.
1439
+			if ($creating) {
1440
+				wp_enqueue_script('autosave');
1441
+			} else {
1442
+				if (isset($this->_cpt_routes[ $this->_req_data['action'] ])
1443
+					&& ! isset($this->_labels['hide_add_button_on_cpt_route'][ $this->_req_data['action'] ])
1444
+				) {
1445
+					$create_new_action = apply_filters(
1446
+						'FHEE__EE_Admin_Page_CPT___edit_cpt_item__create_new_action',
1447
+						'create_new',
1448
+						$this
1449
+					);
1450
+					$post_new_file = EE_Admin_Page::add_query_args_and_nonce(
1451
+						array(
1452
+							'action' => $create_new_action,
1453
+							'page'   => $this->page_slug,
1454
+						),
1455
+						'admin.php'
1456
+					);
1457
+				}
1458
+			}
1459
+			include_once WP_ADMIN_PATH . 'edit-form-advanced.php';
1460
+		}
1461
+	}
1462
+
1463
+
1464
+	public function add_new_admin_page_global()
1465
+	{
1466
+		$admin_page = ! empty($this->_req_data['post']) ? 'post-php' : 'post-new-php';
1467
+		?>
1468 1468
         <script type="text/javascript">
1469 1469
             adminpage = '<?php echo $admin_page; ?>';
1470 1470
         </script>
1471 1471
         <?php
1472
-    }
1473
-
1474
-
1475
-    /**
1476
-     * default method for the 'edit' route for cpt admin pages
1477
-     * For reference on what to put in here, refer to wp-admin/post.php
1478
-     *
1479
-     * @access protected
1480
-     * @return string   template for edit cpt form
1481
-     */
1482
-    protected function _edit_cpt_item()
1483
-    {
1484
-        global $post, $title, $is_IE, $post_type, $post_type_object;
1485
-        $post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1486
-        $post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1487
-        if (empty($post)) {
1488
-            wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', 'event_espresso'));
1489
-        }
1490
-        if (! empty($_GET['get-post-lock'])) {
1491
-            wp_set_post_lock($post_id);
1492
-            wp_redirect(get_edit_post_link($post_id, 'url'));
1493
-            exit();
1494
-        }
1495
-
1496
-        // template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1497
-        $post_type = $this->_cpt_routes[ $this->_req_action ];
1498
-        $post_type_object = $this->_cpt_object;
1499
-
1500
-        if (! wp_check_post_lock($post->ID)) {
1501
-            wp_set_post_lock($post->ID);
1502
-        }
1503
-        add_action('admin_footer', '_admin_notice_post_locked');
1504
-        if (post_type_supports($this->_cpt_routes[ $this->_req_action ], 'comments')) {
1505
-            wp_enqueue_script('admin-comments');
1506
-            enqueue_comment_hotkeys_js();
1507
-        }
1508
-        add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1509
-        // modify the default editor title field with default title.
1510
-        add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1511
-        $this->loadEditorTemplate(false);
1512
-    }
1513
-
1514
-
1515
-
1516
-    /**
1517
-     * some getters
1518
-     */
1519
-    /**
1520
-     * This returns the protected _cpt_model_obj property
1521
-     *
1522
-     * @return EE_CPT_Base
1523
-     */
1524
-    public function get_cpt_model_obj()
1525
-    {
1526
-        return $this->_cpt_model_obj;
1527
-    }
1472
+	}
1473
+
1474
+
1475
+	/**
1476
+	 * default method for the 'edit' route for cpt admin pages
1477
+	 * For reference on what to put in here, refer to wp-admin/post.php
1478
+	 *
1479
+	 * @access protected
1480
+	 * @return string   template for edit cpt form
1481
+	 */
1482
+	protected function _edit_cpt_item()
1483
+	{
1484
+		global $post, $title, $is_IE, $post_type, $post_type_object;
1485
+		$post_id = isset($this->_req_data['post']) ? $this->_req_data['post'] : null;
1486
+		$post = ! empty($post_id) ? get_post($post_id, OBJECT, 'edit') : null;
1487
+		if (empty($post)) {
1488
+			wp_die(__('You attempted to edit an item that doesn&#8217;t exist. Perhaps it was deleted?', 'event_espresso'));
1489
+		}
1490
+		if (! empty($_GET['get-post-lock'])) {
1491
+			wp_set_post_lock($post_id);
1492
+			wp_redirect(get_edit_post_link($post_id, 'url'));
1493
+			exit();
1494
+		}
1495
+
1496
+		// template vars for WP_ADMIN_PATH . 'edit-form-advanced.php'
1497
+		$post_type = $this->_cpt_routes[ $this->_req_action ];
1498
+		$post_type_object = $this->_cpt_object;
1499
+
1500
+		if (! wp_check_post_lock($post->ID)) {
1501
+			wp_set_post_lock($post->ID);
1502
+		}
1503
+		add_action('admin_footer', '_admin_notice_post_locked');
1504
+		if (post_type_supports($this->_cpt_routes[ $this->_req_action ], 'comments')) {
1505
+			wp_enqueue_script('admin-comments');
1506
+			enqueue_comment_hotkeys_js();
1507
+		}
1508
+		add_action('admin_print_styles', array($this, 'add_new_admin_page_global'));
1509
+		// modify the default editor title field with default title.
1510
+		add_filter('enter_title_here', array($this, 'add_custom_editor_default_title'), 10);
1511
+		$this->loadEditorTemplate(false);
1512
+	}
1513
+
1514
+
1515
+
1516
+	/**
1517
+	 * some getters
1518
+	 */
1519
+	/**
1520
+	 * This returns the protected _cpt_model_obj property
1521
+	 *
1522
+	 * @return EE_CPT_Base
1523
+	 */
1524
+	public function get_cpt_model_obj()
1525
+	{
1526
+		return $this->_cpt_model_obj;
1527
+	}
1528 1528
 }
Please login to merge, or discard this patch.
modules/batch/EED_Batch.module.php 2 patches
Indentation   +332 added lines, -332 removed lines patch added patch discarded remove patch
@@ -29,360 +29,360 @@
 block discarded – undo
29 29
 class EED_Batch extends EED_Module
30 30
 {
31 31
 
32
-    /**
33
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
34
-     * processes data only
35
-     */
36
-    const batch_job = 'job';
37
-    /**
38
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
39
-     * produces a file for download
40
-     */
41
-    const batch_file_job = 'file';
42
-    /**
43
-     * Possibly value for $_REQUEST[ 'batch' ]. Indicates this request is NOT
44
-     * for a batch job. It's the same as not providing the $_REQUEST[ 'batch' ]
45
-     * at all
46
-     */
47
-    const batch_not_job = 'none';
32
+	/**
33
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
34
+	 * processes data only
35
+	 */
36
+	const batch_job = 'job';
37
+	/**
38
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates to run a job that
39
+	 * produces a file for download
40
+	 */
41
+	const batch_file_job = 'file';
42
+	/**
43
+	 * Possibly value for $_REQUEST[ 'batch' ]. Indicates this request is NOT
44
+	 * for a batch job. It's the same as not providing the $_REQUEST[ 'batch' ]
45
+	 * at all
46
+	 */
47
+	const batch_not_job = 'none';
48 48
 
49
-    /**
50
-     *
51
-     * @var string 'file', or 'job', or false to indicate its not a batch request at all
52
-     */
53
-    protected $_batch_request_type = null;
49
+	/**
50
+	 *
51
+	 * @var string 'file', or 'job', or false to indicate its not a batch request at all
52
+	 */
53
+	protected $_batch_request_type = null;
54 54
 
55
-    /**
56
-     * Because we want to use the response in both the localized JS and in the body
57
-     * we need to make this response available between method calls
58
-     *
59
-     * @var \EventEspressoBatchRequest\Helpers\JobStepResponse
60
-     */
61
-    protected $_job_step_response = null;
55
+	/**
56
+	 * Because we want to use the response in both the localized JS and in the body
57
+	 * we need to make this response available between method calls
58
+	 *
59
+	 * @var \EventEspressoBatchRequest\Helpers\JobStepResponse
60
+	 */
61
+	protected $_job_step_response = null;
62 62
 
63
-    /**
64
-     * @var LoaderInterface
65
-     */
66
-    protected $loader;
63
+	/**
64
+	 * @var LoaderInterface
65
+	 */
66
+	protected $loader;
67 67
 
68
-    /**
69
-     * Gets the batch instance
70
-     *
71
-     * @return EED_Batch
72
-     */
73
-    public static function instance()
74
-    {
75
-        return self::get_instance();
76
-    }
68
+	/**
69
+	 * Gets the batch instance
70
+	 *
71
+	 * @return EED_Batch
72
+	 */
73
+	public static function instance()
74
+	{
75
+		return self::get_instance();
76
+	}
77 77
 
78
-    /**
79
-     * Sets hooks to enable batch jobs on the frontend. Disabled by default
80
-     * because it's an attack vector and there are currently no implementations
81
-     */
82
-    public static function set_hooks()
83
-    {
84
-        // because this is a possibel attack vector, let's have this disabled until
85
-        // we at least have a real use for it on the frontend
86
-        if (apply_filters('FHEE__EED_Batch__set_hooks__enable_frontend_batch', false)) {
87
-            add_action('wp_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
88
-            add_filter('template_include', array(self::instance(), 'override_template'), 99);
89
-        }
90
-    }
78
+	/**
79
+	 * Sets hooks to enable batch jobs on the frontend. Disabled by default
80
+	 * because it's an attack vector and there are currently no implementations
81
+	 */
82
+	public static function set_hooks()
83
+	{
84
+		// because this is a possibel attack vector, let's have this disabled until
85
+		// we at least have a real use for it on the frontend
86
+		if (apply_filters('FHEE__EED_Batch__set_hooks__enable_frontend_batch', false)) {
87
+			add_action('wp_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
88
+			add_filter('template_include', array(self::instance(), 'override_template'), 99);
89
+		}
90
+	}
91 91
 
92
-    /**
93
-     * Initializes some hooks for the admin in order to run batch jobs
94
-     */
95
-    public static function set_hooks_admin()
96
-    {
97
-        add_action('admin_menu', array(self::instance(), 'register_admin_pages'));
98
-        add_action('admin_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
92
+	/**
93
+	 * Initializes some hooks for the admin in order to run batch jobs
94
+	 */
95
+	public static function set_hooks_admin()
96
+	{
97
+		add_action('admin_menu', array(self::instance(), 'register_admin_pages'));
98
+		add_action('admin_enqueue_scripts', array(self::instance(), 'enqueue_scripts'));
99 99
 
100
-        // ajax
101
-        add_action('wp_ajax_espresso_batch_continue', array(self::instance(), 'batch_continue'));
102
-        add_action('wp_ajax_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
103
-        add_action('wp_ajax_nopriv_espresso_batch_continue', array(self::instance(), 'batch_continue'));
104
-        add_action('wp_ajax_nopriv_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
105
-    }
100
+		// ajax
101
+		add_action('wp_ajax_espresso_batch_continue', array(self::instance(), 'batch_continue'));
102
+		add_action('wp_ajax_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
103
+		add_action('wp_ajax_nopriv_espresso_batch_continue', array(self::instance(), 'batch_continue'));
104
+		add_action('wp_ajax_nopriv_espresso_batch_cleanup', array(self::instance(), 'batch_cleanup'));
105
+	}
106 106
 
107
-    /**
108
-     * @since 4.9.80.p
109
-     * @return LoaderInterface
110
-     * @throws InvalidArgumentException
111
-     * @throws InvalidDataTypeException
112
-     * @throws InvalidInterfaceException
113
-     */
114
-    protected function getLoader()
115
-    {
116
-        if (!$this->loader instanceof LoaderInterface) {
117
-            $this->loader = LoaderFactory::getLoader();
118
-        }
119
-        return $this->loader;
120
-    }
107
+	/**
108
+	 * @since 4.9.80.p
109
+	 * @return LoaderInterface
110
+	 * @throws InvalidArgumentException
111
+	 * @throws InvalidDataTypeException
112
+	 * @throws InvalidInterfaceException
113
+	 */
114
+	protected function getLoader()
115
+	{
116
+		if (!$this->loader instanceof LoaderInterface) {
117
+			$this->loader = LoaderFactory::getLoader();
118
+		}
119
+		return $this->loader;
120
+	}
121 121
 
122
-    /**
123
-     * Enqueues batch scripts on the frontend or admin, and creates a job
124
-     */
125
-    public function enqueue_scripts()
126
-    {
127
-        if (isset($_REQUEST['espresso_batch'])
128
-            ||
129
-            (
130
-                isset($_REQUEST['page'])
131
-                && $_REQUEST['page'] == 'espresso_batch'
132
-            )
133
-        ) {
134
-            if (! isset($_REQUEST['default_nonce']) || ! wp_verify_nonce($_REQUEST['default_nonce'], 'default_nonce')) {
135
-                wp_die(esc_html__('The link you clicked to start the batch job has expired. Please go back and refresh the previous page.', 'event_espresso'));
136
-            }
137
-            switch ($this->batch_request_type()) {
138
-                case self::batch_job:
139
-                    $this->enqueue_scripts_styles_batch_create();
140
-                    break;
141
-                case self::batch_file_job:
142
-                    $this->enqueue_scripts_styles_batch_file_create();
143
-                    break;
144
-            }
145
-        }
146
-    }
122
+	/**
123
+	 * Enqueues batch scripts on the frontend or admin, and creates a job
124
+	 */
125
+	public function enqueue_scripts()
126
+	{
127
+		if (isset($_REQUEST['espresso_batch'])
128
+			||
129
+			(
130
+				isset($_REQUEST['page'])
131
+				&& $_REQUEST['page'] == 'espresso_batch'
132
+			)
133
+		) {
134
+			if (! isset($_REQUEST['default_nonce']) || ! wp_verify_nonce($_REQUEST['default_nonce'], 'default_nonce')) {
135
+				wp_die(esc_html__('The link you clicked to start the batch job has expired. Please go back and refresh the previous page.', 'event_espresso'));
136
+			}
137
+			switch ($this->batch_request_type()) {
138
+				case self::batch_job:
139
+					$this->enqueue_scripts_styles_batch_create();
140
+					break;
141
+				case self::batch_file_job:
142
+					$this->enqueue_scripts_styles_batch_file_create();
143
+					break;
144
+			}
145
+		}
146
+	}
147 147
 
148
-    /**
149
-     * Create a batch job, enqueues a script to run it, and localizes some data for it
150
-     */
151
-    public function enqueue_scripts_styles_batch_create()
152
-    {
153
-        $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
154
-        wp_enqueue_script(
155
-            'batch_runner_init',
156
-            BATCH_URL . 'assets/batch_runner_init.js',
157
-            array('batch_runner'),
158
-            EVENT_ESPRESSO_VERSION,
159
-            true
160
-        );
161
-        wp_localize_script('batch_runner_init', 'ee_job_response', $job_response->to_array());
162
-        wp_localize_script(
163
-            'batch_runner_init',
164
-            'ee_job_i18n',
165
-            array(
166
-                'return_url' => $_REQUEST['return_url'],
167
-            )
168
-        );
169
-    }
148
+	/**
149
+	 * Create a batch job, enqueues a script to run it, and localizes some data for it
150
+	 */
151
+	public function enqueue_scripts_styles_batch_create()
152
+	{
153
+		$job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
154
+		wp_enqueue_script(
155
+			'batch_runner_init',
156
+			BATCH_URL . 'assets/batch_runner_init.js',
157
+			array('batch_runner'),
158
+			EVENT_ESPRESSO_VERSION,
159
+			true
160
+		);
161
+		wp_localize_script('batch_runner_init', 'ee_job_response', $job_response->to_array());
162
+		wp_localize_script(
163
+			'batch_runner_init',
164
+			'ee_job_i18n',
165
+			array(
166
+				'return_url' => $_REQUEST['return_url'],
167
+			)
168
+		);
169
+	}
170 170
 
171
-    /**
172
-     * Creates a batch job which will download a file, enqueues a script to run the job, and localizes some data for it
173
-     */
174
-    public function enqueue_scripts_styles_batch_file_create()
175
-    {
176
-        // creates a job based on the request variable
177
-        $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
178
-        wp_enqueue_script(
179
-            'batch_file_runner_init',
180
-            BATCH_URL . 'assets/batch_file_runner_init.js',
181
-            array('batch_runner'),
182
-            EVENT_ESPRESSO_VERSION,
183
-            true
184
-        );
185
-        wp_localize_script('batch_file_runner_init', 'ee_job_response', $job_response->to_array());
186
-        wp_localize_script(
187
-            'batch_file_runner_init',
188
-            'ee_job_i18n',
189
-            array(
190
-                'download_and_redirecting' => sprintf(
191
-                    wp_strip_all_tags(
192
-                        __('File Generation complete. Downloading, and %1$sredirecting%2$s...', 'event_espresso')
193
-                    ),
194
-                    '<a href="' . $_REQUEST['return_url'] . '">',
195
-                    '</a>'
196
-                ),
197
-                'return_url'               => $_REQUEST['return_url'],
198
-            )
199
-        );
200
-    }
171
+	/**
172
+	 * Creates a batch job which will download a file, enqueues a script to run the job, and localizes some data for it
173
+	 */
174
+	public function enqueue_scripts_styles_batch_file_create()
175
+	{
176
+		// creates a job based on the request variable
177
+		$job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
178
+		wp_enqueue_script(
179
+			'batch_file_runner_init',
180
+			BATCH_URL . 'assets/batch_file_runner_init.js',
181
+			array('batch_runner'),
182
+			EVENT_ESPRESSO_VERSION,
183
+			true
184
+		);
185
+		wp_localize_script('batch_file_runner_init', 'ee_job_response', $job_response->to_array());
186
+		wp_localize_script(
187
+			'batch_file_runner_init',
188
+			'ee_job_i18n',
189
+			array(
190
+				'download_and_redirecting' => sprintf(
191
+					wp_strip_all_tags(
192
+						__('File Generation complete. Downloading, and %1$sredirecting%2$s...', 'event_espresso')
193
+					),
194
+					'<a href="' . $_REQUEST['return_url'] . '">',
195
+					'</a>'
196
+				),
197
+				'return_url'               => $_REQUEST['return_url'],
198
+			)
199
+		);
200
+	}
201 201
 
202
-    /**
203
-     * Enqueues scripts and styles common to any batch job, and creates
204
-     * a job from the request data, and stores the response in the
205
-     * $this->_job_step_response property
206
-     *
207
-     * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
208
-     */
209
-    protected function _enqueue_batch_job_scripts_and_styles_and_start_job()
210
-    {
211
-        // just copy the bits of EE admin's eei18n that we need in the JS
212
-        EE_Registry::$i18n_js_strings['batchJobError'] =  esc_html__(
213
-            'An error occurred and the job has been stopped. Please refresh the page to try again.',
214
-            'event_espresso'
215
-        );
216
-        wp_register_script(
217
-            'progress_bar',
218
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
219
-            array('jquery'),
220
-            EVENT_ESPRESSO_VERSION,
221
-            true
222
-        );
223
-        wp_enqueue_style(
224
-            'progress_bar',
225
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
226
-            array(),
227
-            EVENT_ESPRESSO_VERSION
228
-        );
229
-        wp_enqueue_script(
230
-            'batch_runner',
231
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
232
-            array('progress_bar', CoreAssetManager::JS_HANDLE_CORE),
233
-            EVENT_ESPRESSO_VERSION,
234
-            true
235
-        );
236
-        $job_handler_classname = stripslashes($_GET['job_handler']);
237
-        $request_data = array_diff_key(
238
-            $_REQUEST,
239
-            array_flip(array('action', 'page', 'ee', 'batch'))
240
-        );
241
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
242
-        // eg 'EventEspressoBatchRequest\JobHandlers\RegistrationsReport'
243
-        $job_response = $batch_runner->create_job($job_handler_classname, $request_data);
244
-        // remember the response for later. We need it to display the page body
245
-        $this->_job_step_response = $job_response;
246
-        return $job_response;
247
-    }
202
+	/**
203
+	 * Enqueues scripts and styles common to any batch job, and creates
204
+	 * a job from the request data, and stores the response in the
205
+	 * $this->_job_step_response property
206
+	 *
207
+	 * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
208
+	 */
209
+	protected function _enqueue_batch_job_scripts_and_styles_and_start_job()
210
+	{
211
+		// just copy the bits of EE admin's eei18n that we need in the JS
212
+		EE_Registry::$i18n_js_strings['batchJobError'] =  esc_html__(
213
+			'An error occurred and the job has been stopped. Please refresh the page to try again.',
214
+			'event_espresso'
215
+		);
216
+		wp_register_script(
217
+			'progress_bar',
218
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
219
+			array('jquery'),
220
+			EVENT_ESPRESSO_VERSION,
221
+			true
222
+		);
223
+		wp_enqueue_style(
224
+			'progress_bar',
225
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
226
+			array(),
227
+			EVENT_ESPRESSO_VERSION
228
+		);
229
+		wp_enqueue_script(
230
+			'batch_runner',
231
+			EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
232
+			array('progress_bar', CoreAssetManager::JS_HANDLE_CORE),
233
+			EVENT_ESPRESSO_VERSION,
234
+			true
235
+		);
236
+		$job_handler_classname = stripslashes($_GET['job_handler']);
237
+		$request_data = array_diff_key(
238
+			$_REQUEST,
239
+			array_flip(array('action', 'page', 'ee', 'batch'))
240
+		);
241
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
242
+		// eg 'EventEspressoBatchRequest\JobHandlers\RegistrationsReport'
243
+		$job_response = $batch_runner->create_job($job_handler_classname, $request_data);
244
+		// remember the response for later. We need it to display the page body
245
+		$this->_job_step_response = $job_response;
246
+		return $job_response;
247
+	}
248 248
 
249
-    /**
250
-     * If we are doing a frontend batch job, this makes it so WP shows our template's HTML
251
-     *
252
-     * @param string $template
253
-     * @return string
254
-     */
255
-    public function override_template($template)
256
-    {
257
-        if (isset($_REQUEST['espresso_batch']) && isset($_REQUEST['batch'])) {
258
-            return EE_MODULES . 'batch/templates/batch_frontend_wrapper.template.html';
259
-        }
260
-        return $template;
261
-    }
249
+	/**
250
+	 * If we are doing a frontend batch job, this makes it so WP shows our template's HTML
251
+	 *
252
+	 * @param string $template
253
+	 * @return string
254
+	 */
255
+	public function override_template($template)
256
+	{
257
+		if (isset($_REQUEST['espresso_batch']) && isset($_REQUEST['batch'])) {
258
+			return EE_MODULES . 'batch/templates/batch_frontend_wrapper.template.html';
259
+		}
260
+		return $template;
261
+	}
262 262
 
263
-    /**
264
-     * Adds an admin page which doesn't appear in the admin menu
265
-     */
266
-    public function register_admin_pages()
267
-    {
268
-        add_submenu_page(
269
-            '', // parent slug. we don't want this to actually appear in the menu
270
-            __('Batch Job', 'event_espresso'), // page title
271
-            'n/a', // menu title
272
-            'read', // we want this page to actually be accessible to anyone,
273
-            'espresso_batch', // menu slug
274
-            array(self::instance(), 'show_admin_page')
275
-        );
276
-    }
263
+	/**
264
+	 * Adds an admin page which doesn't appear in the admin menu
265
+	 */
266
+	public function register_admin_pages()
267
+	{
268
+		add_submenu_page(
269
+			'', // parent slug. we don't want this to actually appear in the menu
270
+			__('Batch Job', 'event_espresso'), // page title
271
+			'n/a', // menu title
272
+			'read', // we want this page to actually be accessible to anyone,
273
+			'espresso_batch', // menu slug
274
+			array(self::instance(), 'show_admin_page')
275
+		);
276
+	}
277 277
 
278
-    /**
279
-     * Renders the admin page, after most of the work was already done during enqueuing scripts
280
-     * of creating the job and localizing some data
281
-     */
282
-    public function show_admin_page()
283
-    {
284
-        echo EEH_Template::locate_template(
285
-            EE_MODULES . 'batch/templates/batch_wrapper.template.html',
286
-            array('batch_request_type' => $this->batch_request_type())
287
-        );
288
-    }
278
+	/**
279
+	 * Renders the admin page, after most of the work was already done during enqueuing scripts
280
+	 * of creating the job and localizing some data
281
+	 */
282
+	public function show_admin_page()
283
+	{
284
+		echo EEH_Template::locate_template(
285
+			EE_MODULES . 'batch/templates/batch_wrapper.template.html',
286
+			array('batch_request_type' => $this->batch_request_type())
287
+		);
288
+	}
289 289
 
290
-    /**
291
-     * Receives ajax calls for continuing a job
292
-     */
293
-    public function batch_continue()
294
-    {
295
-        $job_id = sanitize_text_field($_REQUEST['job_id']);
296
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
297
-        $response_obj = $batch_runner->continue_job($job_id);
298
-        $this->_return_json($response_obj->to_array());
299
-    }
290
+	/**
291
+	 * Receives ajax calls for continuing a job
292
+	 */
293
+	public function batch_continue()
294
+	{
295
+		$job_id = sanitize_text_field($_REQUEST['job_id']);
296
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
297
+		$response_obj = $batch_runner->continue_job($job_id);
298
+		$this->_return_json($response_obj->to_array());
299
+	}
300 300
 
301
-    /**
302
-     * Receives the ajax call to cleanup a job
303
-     *
304
-     * @return type
305
-     */
306
-    public function batch_cleanup()
307
-    {
308
-        $job_id = sanitize_text_field($_REQUEST['job_id']);
309
-        $batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
310
-        $response_obj = $batch_runner->cleanup_job($job_id);
311
-        $this->_return_json($response_obj->to_array());
312
-    }
301
+	/**
302
+	 * Receives the ajax call to cleanup a job
303
+	 *
304
+	 * @return type
305
+	 */
306
+	public function batch_cleanup()
307
+	{
308
+		$job_id = sanitize_text_field($_REQUEST['job_id']);
309
+		$batch_runner = $this->getLoader()->getShared('EventEspressoBatchRequest\BatchRequestProcessor');
310
+		$response_obj = $batch_runner->cleanup_job($job_id);
311
+		$this->_return_json($response_obj->to_array());
312
+	}
313 313
 
314 314
 
315
-    /**
316
-     * Returns a json response
317
-     *
318
-     * @param array $data The data we want to send echo via in the JSON response's "data" element
319
-     *
320
-     * The returned json object is created from an array in the following format:
321
-     * array(
322
-     *    'notices' => '', // - contains any EE_Error formatted notices
323
-     *    'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
324
-     *    We're also going to include the template args with every package (so js can pick out any specific template
325
-     *    args that might be included in here)
326
-     *    'isEEajax' => true,//indicates this is a response from EE
327
-     * )
328
-     */
329
-    protected function _return_json($data)
330
-    {
331
-        $json = array(
332
-            'notices'  => EE_Error::get_notices(),
333
-            'data'     => $data,
334
-            'isEEajax' => true
335
-            // special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
336
-        );
315
+	/**
316
+	 * Returns a json response
317
+	 *
318
+	 * @param array $data The data we want to send echo via in the JSON response's "data" element
319
+	 *
320
+	 * The returned json object is created from an array in the following format:
321
+	 * array(
322
+	 *    'notices' => '', // - contains any EE_Error formatted notices
323
+	 *    'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
324
+	 *    We're also going to include the template args with every package (so js can pick out any specific template
325
+	 *    args that might be included in here)
326
+	 *    'isEEajax' => true,//indicates this is a response from EE
327
+	 * )
328
+	 */
329
+	protected function _return_json($data)
330
+	{
331
+		$json = array(
332
+			'notices'  => EE_Error::get_notices(),
333
+			'data'     => $data,
334
+			'isEEajax' => true
335
+			// special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
336
+		);
337 337
 
338 338
 
339
-        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
340
-        if (null === error_get_last() || ! headers_sent()) {
341
-            header('Content-Type: application/json; charset=UTF-8');
342
-        }
343
-        echo wp_json_encode($json);
344
-        exit();
345
-    }
339
+		// make sure there are no php errors or headers_sent.  Then we can set correct json header.
340
+		if (null === error_get_last() || ! headers_sent()) {
341
+			header('Content-Type: application/json; charset=UTF-8');
342
+		}
343
+		echo wp_json_encode($json);
344
+		exit();
345
+	}
346 346
 
347
-    /**
348
-     * Gets the job step response which was done during the enqueuing of scripts
349
-     *
350
-     * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
351
-     */
352
-    public function job_step_response()
353
-    {
354
-        return $this->_job_step_response;
355
-    }
347
+	/**
348
+	 * Gets the job step response which was done during the enqueuing of scripts
349
+	 *
350
+	 * @return \EventEspressoBatchRequest\Helpers\JobStepResponse
351
+	 */
352
+	public function job_step_response()
353
+	{
354
+		return $this->_job_step_response;
355
+	}
356 356
 
357
-    /**
358
-     * Gets the batch request type indicated in the $_REQUEST
359
-     *
360
-     * @return string: EED_Batch::batch_job, EED_Batch::batch_file_job, EED_Batch::batch_not_job
361
-     */
362
-    public function batch_request_type()
363
-    {
364
-        if ($this->_batch_request_type === null) {
365
-            if (isset($_GET['batch'])) {
366
-                if ($_GET['batch'] == self::batch_job) {
367
-                    $this->_batch_request_type = self::batch_job;
368
-                } elseif ($_GET['batch'] == self::batch_file_job) {
369
-                    $this->_batch_request_type = self::batch_file_job;
370
-                }
371
-            }
372
-            // if we didn't find that it was a batch request, indicate it wasn't
373
-            if ($this->_batch_request_type === null) {
374
-                $this->_batch_request_type = self::batch_not_job;
375
-            }
376
-        }
377
-        return $this->_batch_request_type;
378
-    }
357
+	/**
358
+	 * Gets the batch request type indicated in the $_REQUEST
359
+	 *
360
+	 * @return string: EED_Batch::batch_job, EED_Batch::batch_file_job, EED_Batch::batch_not_job
361
+	 */
362
+	public function batch_request_type()
363
+	{
364
+		if ($this->_batch_request_type === null) {
365
+			if (isset($_GET['batch'])) {
366
+				if ($_GET['batch'] == self::batch_job) {
367
+					$this->_batch_request_type = self::batch_job;
368
+				} elseif ($_GET['batch'] == self::batch_file_job) {
369
+					$this->_batch_request_type = self::batch_file_job;
370
+				}
371
+			}
372
+			// if we didn't find that it was a batch request, indicate it wasn't
373
+			if ($this->_batch_request_type === null) {
374
+				$this->_batch_request_type = self::batch_not_job;
375
+			}
376
+		}
377
+		return $this->_batch_request_type;
378
+	}
379 379
 
380
-    /**
381
-     * Unnecessary
382
-     *
383
-     * @param type $WP
384
-     */
385
-    public function run($WP)
386
-    {
387
-    }
380
+	/**
381
+	 * Unnecessary
382
+	 *
383
+	 * @param type $WP
384
+	 */
385
+	public function run($WP)
386
+	{
387
+	}
388 388
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
      */
114 114
     protected function getLoader()
115 115
     {
116
-        if (!$this->loader instanceof LoaderInterface) {
116
+        if ( ! $this->loader instanceof LoaderInterface) {
117 117
             $this->loader = LoaderFactory::getLoader();
118 118
         }
119 119
         return $this->loader;
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
                 && $_REQUEST['page'] == 'espresso_batch'
132 132
             )
133 133
         ) {
134
-            if (! isset($_REQUEST['default_nonce']) || ! wp_verify_nonce($_REQUEST['default_nonce'], 'default_nonce')) {
134
+            if ( ! isset($_REQUEST['default_nonce']) || ! wp_verify_nonce($_REQUEST['default_nonce'], 'default_nonce')) {
135 135
                 wp_die(esc_html__('The link you clicked to start the batch job has expired. Please go back and refresh the previous page.', 'event_espresso'));
136 136
             }
137 137
             switch ($this->batch_request_type()) {
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
         $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
154 154
         wp_enqueue_script(
155 155
             'batch_runner_init',
156
-            BATCH_URL . 'assets/batch_runner_init.js',
156
+            BATCH_URL.'assets/batch_runner_init.js',
157 157
             array('batch_runner'),
158 158
             EVENT_ESPRESSO_VERSION,
159 159
             true
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
         $job_response = $this->_enqueue_batch_job_scripts_and_styles_and_start_job();
178 178
         wp_enqueue_script(
179 179
             'batch_file_runner_init',
180
-            BATCH_URL . 'assets/batch_file_runner_init.js',
180
+            BATCH_URL.'assets/batch_file_runner_init.js',
181 181
             array('batch_runner'),
182 182
             EVENT_ESPRESSO_VERSION,
183 183
             true
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
                     wp_strip_all_tags(
192 192
                         __('File Generation complete. Downloading, and %1$sredirecting%2$s...', 'event_espresso')
193 193
                     ),
194
-                    '<a href="' . $_REQUEST['return_url'] . '">',
194
+                    '<a href="'.$_REQUEST['return_url'].'">',
195 195
                     '</a>'
196 196
                 ),
197 197
                 'return_url'               => $_REQUEST['return_url'],
@@ -209,26 +209,26 @@  discard block
 block discarded – undo
209 209
     protected function _enqueue_batch_job_scripts_and_styles_and_start_job()
210 210
     {
211 211
         // just copy the bits of EE admin's eei18n that we need in the JS
212
-        EE_Registry::$i18n_js_strings['batchJobError'] =  esc_html__(
212
+        EE_Registry::$i18n_js_strings['batchJobError'] = esc_html__(
213 213
             'An error occurred and the job has been stopped. Please refresh the page to try again.',
214 214
             'event_espresso'
215 215
         );
216 216
         wp_register_script(
217 217
             'progress_bar',
218
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.js',
218
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/progress_bar.js',
219 219
             array('jquery'),
220 220
             EVENT_ESPRESSO_VERSION,
221 221
             true
222 222
         );
223 223
         wp_enqueue_style(
224 224
             'progress_bar',
225
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/progress_bar.css',
225
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/progress_bar.css',
226 226
             array(),
227 227
             EVENT_ESPRESSO_VERSION
228 228
         );
229 229
         wp_enqueue_script(
230 230
             'batch_runner',
231
-            EE_PLUGIN_DIR_URL . 'core/libraries/batch/Assets/batch_runner.js',
231
+            EE_PLUGIN_DIR_URL.'core/libraries/batch/Assets/batch_runner.js',
232 232
             array('progress_bar', CoreAssetManager::JS_HANDLE_CORE),
233 233
             EVENT_ESPRESSO_VERSION,
234 234
             true
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
     public function override_template($template)
256 256
     {
257 257
         if (isset($_REQUEST['espresso_batch']) && isset($_REQUEST['batch'])) {
258
-            return EE_MODULES . 'batch/templates/batch_frontend_wrapper.template.html';
258
+            return EE_MODULES.'batch/templates/batch_frontend_wrapper.template.html';
259 259
         }
260 260
         return $template;
261 261
     }
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
     public function show_admin_page()
283 283
     {
284 284
         echo EEH_Template::locate_template(
285
-            EE_MODULES . 'batch/templates/batch_wrapper.template.html',
285
+            EE_MODULES.'batch/templates/batch_wrapper.template.html',
286 286
             array('batch_request_type' => $this->batch_request_type())
287 287
         );
288 288
     }
Please login to merge, or discard this patch.
core/db_models/helpers/EE_Table_Base.php 2 patches
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -7,151 +7,151 @@
 block discarded – undo
7 7
 abstract class EE_Table_Base
8 8
 {
9 9
 
10
-    /**
11
-     * This holds the table_name without the table prefix.
12
-     *
13
-     * @var string
14
-     */
15
-    public $_table_name;
16
-
17
-
18
-    /**
19
-     * This holds what is used as the alias for the table in queries.
20
-     *
21
-     * @var string
22
-     */
23
-    public $_table_alias;
24
-
25
-
26
-    /**
27
-     * Table's private key column
28
-     *
29
-     * @var string
30
-     */
31
-    protected $_pk_column;
32
-
33
-
34
-    /**
35
-     * Whether this table is a global table (in multisite) or specific to site.
36
-     *
37
-     * @var bool
38
-     */
39
-    protected $_global;
40
-
41
-
42
-    /**
43
-     * @param string  $table_name with or without wpdb prefix
44
-     * @param string  $pk_column
45
-     * @param boolean $global     whether the table is "global" as in there is only 1 table on an entire multisite
46
-     *                            install, or whether each site on a multisite install has a copy of this table
47
-     * @global wpdb   $wpdb
48
-     */
49
-    public function __construct($table_name, $pk_column, $global = false)
50
-    {
51
-        $this->_global = $global;
52
-        $prefix        = $this->get_table_prefix();
53
-        // if they added the prefix, let's remove it because we delay adding the prefix until right when its needed.
54
-        if (strpos($table_name, $prefix) === 0) {
55
-            $table_name = substr_replace($table_name, '', 0, strlen($prefix));
56
-        }
57
-        $this->_table_name = $table_name;
58
-        $this->_pk_column  = $pk_column;
59
-    }
60
-
61
-
62
-    /**
63
-     * This returns the table prefix for the current model state.
64
-     *
65
-     * @return string
66
-     * @global wpdb $wpdb
67
-     */
68
-    public function get_table_prefix()
69
-    {
70
-        global $wpdb;
71
-        if ($this->_global) {
72
-            return $wpdb->base_prefix;
73
-        }
74
-        return $wpdb->get_blog_prefix(EEM_Base::get_model_query_blog_id());
75
-    }
76
-
77
-
78
-    /**
79
-     * Used to set the table_alias property
80
-     *
81
-     * @param string $table_alias
82
-     */
83
-    public function _construct_finalize_with_alias($table_alias)
84
-    {
85
-        $this->_table_alias = $table_alias;
86
-    }
87
-
88
-
89
-    /**
90
-     * Returns the fully qualified table name for the database (includes the table prefix current for the blog).
91
-     *
92
-     * @return string
93
-     */
94
-    public function get_table_name()
95
-    {
96
-        return $this->get_table_prefix() . $this->_table_name;
97
-    }
98
-
99
-
100
-    /**
101
-     * Provides what is currently set as the alias for the table to be used in queries.
102
-     *
103
-     * @return string
104
-     * @throws EE_Error
105
-     */
106
-    public function get_table_alias()
107
-    {
108
-        if (! $this->_table_alias) {
109
-            throw new EE_Error("You must call _construct_finalize_with_alias before using the EE_Table_Base. Did you forget to call parent::__construct at the end of your EEMerimental_Base child's __construct?");
110
-        }
111
-        return $this->_table_alias;
112
-    }
113
-
114
-
115
-    /**
116
-     * @return string name of column of PK
117
-     */
118
-    public function get_pk_column()
119
-    {
120
-        return $this->_pk_column;
121
-    }
122
-
123
-
124
-    /**
125
-     * returns a string with the table alias, a period, and the private key's column.
126
-     *
127
-     * @return string
128
-     */
129
-    public function get_fully_qualified_pk_column()
130
-    {
131
-        return $this->get_table_alias() . "." . $this->get_pk_column();
132
-    }
133
-
134
-
135
-    /**
136
-     * returns the special sql for a inner select with a limit.
137
-     *
138
-     * @return string    SQL select
139
-     */
140
-    public function get_select_join_limit($limit)
141
-    {
142
-        $limit = is_array($limit) ? 'LIMIT ' . implode(',', array_map('intval', $limit)) : 'LIMIT ' . (int) $limit;
143
-        return SP . '(SELECT * FROM ' . $this->_table_name . SP . $limit . ') AS ' . $this->_table_alias;
144
-    }
145
-
146
-
147
-    /**
148
-     * Returns whether or not htis is a global table (ie, on multisite there's
149
-     * only one of these tables, on the main blog)
150
-     *
151
-     * @return boolean
152
-     */
153
-    public function is_global()
154
-    {
155
-        return $this->_global;
156
-    }
10
+	/**
11
+	 * This holds the table_name without the table prefix.
12
+	 *
13
+	 * @var string
14
+	 */
15
+	public $_table_name;
16
+
17
+
18
+	/**
19
+	 * This holds what is used as the alias for the table in queries.
20
+	 *
21
+	 * @var string
22
+	 */
23
+	public $_table_alias;
24
+
25
+
26
+	/**
27
+	 * Table's private key column
28
+	 *
29
+	 * @var string
30
+	 */
31
+	protected $_pk_column;
32
+
33
+
34
+	/**
35
+	 * Whether this table is a global table (in multisite) or specific to site.
36
+	 *
37
+	 * @var bool
38
+	 */
39
+	protected $_global;
40
+
41
+
42
+	/**
43
+	 * @param string  $table_name with or without wpdb prefix
44
+	 * @param string  $pk_column
45
+	 * @param boolean $global     whether the table is "global" as in there is only 1 table on an entire multisite
46
+	 *                            install, or whether each site on a multisite install has a copy of this table
47
+	 * @global wpdb   $wpdb
48
+	 */
49
+	public function __construct($table_name, $pk_column, $global = false)
50
+	{
51
+		$this->_global = $global;
52
+		$prefix        = $this->get_table_prefix();
53
+		// if they added the prefix, let's remove it because we delay adding the prefix until right when its needed.
54
+		if (strpos($table_name, $prefix) === 0) {
55
+			$table_name = substr_replace($table_name, '', 0, strlen($prefix));
56
+		}
57
+		$this->_table_name = $table_name;
58
+		$this->_pk_column  = $pk_column;
59
+	}
60
+
61
+
62
+	/**
63
+	 * This returns the table prefix for the current model state.
64
+	 *
65
+	 * @return string
66
+	 * @global wpdb $wpdb
67
+	 */
68
+	public function get_table_prefix()
69
+	{
70
+		global $wpdb;
71
+		if ($this->_global) {
72
+			return $wpdb->base_prefix;
73
+		}
74
+		return $wpdb->get_blog_prefix(EEM_Base::get_model_query_blog_id());
75
+	}
76
+
77
+
78
+	/**
79
+	 * Used to set the table_alias property
80
+	 *
81
+	 * @param string $table_alias
82
+	 */
83
+	public function _construct_finalize_with_alias($table_alias)
84
+	{
85
+		$this->_table_alias = $table_alias;
86
+	}
87
+
88
+
89
+	/**
90
+	 * Returns the fully qualified table name for the database (includes the table prefix current for the blog).
91
+	 *
92
+	 * @return string
93
+	 */
94
+	public function get_table_name()
95
+	{
96
+		return $this->get_table_prefix() . $this->_table_name;
97
+	}
98
+
99
+
100
+	/**
101
+	 * Provides what is currently set as the alias for the table to be used in queries.
102
+	 *
103
+	 * @return string
104
+	 * @throws EE_Error
105
+	 */
106
+	public function get_table_alias()
107
+	{
108
+		if (! $this->_table_alias) {
109
+			throw new EE_Error("You must call _construct_finalize_with_alias before using the EE_Table_Base. Did you forget to call parent::__construct at the end of your EEMerimental_Base child's __construct?");
110
+		}
111
+		return $this->_table_alias;
112
+	}
113
+
114
+
115
+	/**
116
+	 * @return string name of column of PK
117
+	 */
118
+	public function get_pk_column()
119
+	{
120
+		return $this->_pk_column;
121
+	}
122
+
123
+
124
+	/**
125
+	 * returns a string with the table alias, a period, and the private key's column.
126
+	 *
127
+	 * @return string
128
+	 */
129
+	public function get_fully_qualified_pk_column()
130
+	{
131
+		return $this->get_table_alias() . "." . $this->get_pk_column();
132
+	}
133
+
134
+
135
+	/**
136
+	 * returns the special sql for a inner select with a limit.
137
+	 *
138
+	 * @return string    SQL select
139
+	 */
140
+	public function get_select_join_limit($limit)
141
+	{
142
+		$limit = is_array($limit) ? 'LIMIT ' . implode(',', array_map('intval', $limit)) : 'LIMIT ' . (int) $limit;
143
+		return SP . '(SELECT * FROM ' . $this->_table_name . SP . $limit . ') AS ' . $this->_table_alias;
144
+	}
145
+
146
+
147
+	/**
148
+	 * Returns whether or not htis is a global table (ie, on multisite there's
149
+	 * only one of these tables, on the main blog)
150
+	 *
151
+	 * @return boolean
152
+	 */
153
+	public function is_global()
154
+	{
155
+		return $this->_global;
156
+	}
157 157
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
      */
94 94
     public function get_table_name()
95 95
     {
96
-        return $this->get_table_prefix() . $this->_table_name;
96
+        return $this->get_table_prefix().$this->_table_name;
97 97
     }
98 98
 
99 99
 
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
      */
106 106
     public function get_table_alias()
107 107
     {
108
-        if (! $this->_table_alias) {
108
+        if ( ! $this->_table_alias) {
109 109
             throw new EE_Error("You must call _construct_finalize_with_alias before using the EE_Table_Base. Did you forget to call parent::__construct at the end of your EEMerimental_Base child's __construct?");
110 110
         }
111 111
         return $this->_table_alias;
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
      */
129 129
     public function get_fully_qualified_pk_column()
130 130
     {
131
-        return $this->get_table_alias() . "." . $this->get_pk_column();
131
+        return $this->get_table_alias().".".$this->get_pk_column();
132 132
     }
133 133
 
134 134
 
@@ -139,8 +139,8 @@  discard block
 block discarded – undo
139 139
      */
140 140
     public function get_select_join_limit($limit)
141 141
     {
142
-        $limit = is_array($limit) ? 'LIMIT ' . implode(',', array_map('intval', $limit)) : 'LIMIT ' . (int) $limit;
143
-        return SP . '(SELECT * FROM ' . $this->_table_name . SP . $limit . ') AS ' . $this->_table_alias;
142
+        $limit = is_array($limit) ? 'LIMIT '.implode(',', array_map('intval', $limit)) : 'LIMIT '.(int) $limit;
143
+        return SP.'(SELECT * FROM '.$this->_table_name.SP.$limit.') AS '.$this->_table_alias;
144 144
     }
145 145
 
146 146
 
Please login to merge, or discard this patch.
admin_pages/messages/Messages_Admin_Page.core.php 1 patch
Indentation   +4541 added lines, -4541 removed lines patch added patch discarded remove patch
@@ -19,2642 +19,2642 @@  discard block
 block discarded – undo
19 19
 class Messages_Admin_Page extends EE_Admin_Page
20 20
 {
21 21
 
22
-    /**
23
-     * @type EE_Message_Resource_Manager $_message_resource_manager
24
-     */
25
-    protected $_message_resource_manager;
26
-
27
-    /**
28
-     * @type string $_active_message_type_name
29
-     */
30
-    protected $_active_message_type_name = '';
31
-
32
-    /**
33
-     * @type EE_messenger $_active_messenger
34
-     */
35
-    protected $_active_messenger;
36
-    protected $_activate_state;
37
-    protected $_activate_meta_box_type;
38
-    protected $_current_message_meta_box;
39
-    protected $_current_message_meta_box_object;
40
-    protected $_context_switcher;
41
-    protected $_shortcodes = array();
42
-    protected $_active_messengers = array();
43
-    protected $_active_message_types = array();
44
-
45
-    /**
46
-     * @var EE_Message_Template_Group $_message_template_group
47
-     */
48
-    protected $_message_template_group;
49
-    protected $_m_mt_settings = array();
50
-
51
-
52
-    /**
53
-     * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
-     * IF there is no group then it gets automatically set to the Default template pack.
55
-     *
56
-     * @since 4.5.0
57
-     *
58
-     * @var EE_Messages_Template_Pack
59
-     */
60
-    protected $_template_pack;
61
-
62
-
63
-    /**
64
-     * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
-     * group is.  If there is no group then it automatically gets set to default.
66
-     *
67
-     * @since 4.5.0
68
-     *
69
-     * @var string
70
-     */
71
-    protected $_variation;
72
-
73
-
74
-    /**
75
-     * @param bool $routing
76
-     * @throws EE_Error
77
-     */
78
-    public function __construct($routing = true)
79
-    {
80
-        // make sure messages autoloader is running
81
-        EED_Messages::set_autoloaders();
82
-        parent::__construct($routing);
83
-    }
84
-
85
-
86
-    protected function _init_page_props()
87
-    {
88
-        $this->page_slug = EE_MSG_PG_SLUG;
89
-        $this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
-        $this->_admin_base_url = EE_MSG_ADMIN_URL;
91
-        $this->_admin_base_path = EE_MSG_ADMIN;
92
-
93
-        $this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
-            : array();
95
-
96
-        $this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
-        $this->_load_message_resource_manager();
98
-    }
99
-
100
-
101
-    /**
102
-     * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
-     *
104
-     * @throws EE_Error
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     * @throws InvalidArgumentException
108
-     * @throws ReflectionException
109
-     */
110
-    protected function _load_message_resource_manager()
111
-    {
112
-        $this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated 4.9.9.rc.014
118
-     * @return array
119
-     * @throws EE_Error
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidDataTypeException
122
-     * @throws InvalidInterfaceException
123
-     */
124
-    public function get_messengers_for_list_table()
125
-    {
126
-        EE_Error::doing_it_wrong(
127
-            __METHOD__,
128
-            sprintf(
129
-                esc_html__(
130
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
-                    'event_espresso'
132
-                ),
133
-                'Messages_Admin_Page::get_messengers_select_input()'
134
-            ),
135
-            '4.9.9.rc.014'
136
-        );
137
-
138
-        $m_values = array();
139
-        $active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
-        // setup messengers for selects
141
-        $i = 1;
142
-        foreach ($active_messengers as $active_messenger) {
143
-            if ($active_messenger instanceof EE_Message) {
144
-                $m_values[ $i ]['id'] = $active_messenger->messenger();
145
-                $m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
-                $i++;
147
-            }
148
-        }
149
-
150
-        return $m_values;
151
-    }
152
-
153
-
154
-    /**
155
-     * @deprecated 4.9.9.rc.014
156
-     * @return array
157
-     * @throws EE_Error
158
-     * @throws InvalidArgumentException
159
-     * @throws InvalidDataTypeException
160
-     * @throws InvalidInterfaceException
161
-     */
162
-    public function get_message_types_for_list_table()
163
-    {
164
-        EE_Error::doing_it_wrong(
165
-            __METHOD__,
166
-            sprintf(
167
-                esc_html__(
168
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
-                    'event_espresso'
170
-                ),
171
-                'Messages_Admin_Page::get_message_types_select_input()'
172
-            ),
173
-            '4.9.9.rc.014'
174
-        );
175
-
176
-        $mt_values = array();
177
-        $active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
-        $i = 1;
179
-        foreach ($active_messages as $active_message) {
180
-            if ($active_message instanceof EE_Message) {
181
-                $mt_values[ $i ]['id'] = $active_message->message_type();
182
-                $mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
-                $i++;
184
-            }
185
-        }
186
-
187
-        return $mt_values;
188
-    }
189
-
190
-
191
-    /**
192
-     * @deprecated 4.9.9.rc.014
193
-     * @return array
194
-     * @throws EE_Error
195
-     * @throws InvalidArgumentException
196
-     * @throws InvalidDataTypeException
197
-     * @throws InvalidInterfaceException
198
-     */
199
-    public function get_contexts_for_message_types_for_list_table()
200
-    {
201
-        EE_Error::doing_it_wrong(
202
-            __METHOD__,
203
-            sprintf(
204
-                esc_html__(
205
-                    'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
-                    'event_espresso'
207
-                ),
208
-                'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
-            ),
210
-            '4.9.9.rc.014'
211
-        );
212
-
213
-        $contexts = array();
214
-        $active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
-        foreach ($active_message_contexts as $active_message) {
216
-            if ($active_message instanceof EE_Message) {
217
-                $message_type = $active_message->message_type_object();
218
-                if ($message_type instanceof EE_message_type) {
219
-                    $message_type_contexts = $message_type->get_contexts();
220
-                    foreach ($message_type_contexts as $context => $context_details) {
221
-                        $contexts[ $context ] = $context_details['label'];
222
-                    }
223
-                }
224
-            }
225
-        }
226
-
227
-        return $contexts;
228
-    }
229
-
230
-
231
-    /**
232
-     * Generate select input with provided messenger options array.
233
-     *
234
-     * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
-     *                                 labels.
236
-     * @return string
237
-     * @throws EE_Error
238
-     */
239
-    public function get_messengers_select_input($messenger_options)
240
-    {
241
-        // if empty or just one value then just return an empty string
242
-        if (empty($messenger_options)
243
-            || ! is_array($messenger_options)
244
-            || count($messenger_options) === 1
245
-        ) {
246
-            return '';
247
-        }
248
-        // merge in default
249
-        $messenger_options = array_merge(
250
-            array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
-            $messenger_options
252
-        );
253
-        $input = new EE_Select_Input(
254
-            $messenger_options,
255
-            array(
256
-                'html_name'  => 'ee_messenger_filter_by',
257
-                'html_id'    => 'ee_messenger_filter_by',
258
-                'html_class' => 'wide',
259
-                'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
-                    ? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
-                    : 'none_selected',
262
-            )
263
-        );
264
-
265
-        return $input->get_html_for_input();
266
-    }
267
-
268
-
269
-    /**
270
-     * Generate select input with provided message type options array.
271
-     *
272
-     * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
-     *                                    message type labels
274
-     * @return string
275
-     * @throws EE_Error
276
-     */
277
-    public function get_message_types_select_input($message_type_options)
278
-    {
279
-        // if empty or count of options is 1 then just return an empty string
280
-        if (empty($message_type_options)
281
-            || ! is_array($message_type_options)
282
-            || count($message_type_options) === 1
283
-        ) {
284
-            return '';
285
-        }
286
-        // merge in default
287
-        $message_type_options = array_merge(
288
-            array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
-            $message_type_options
290
-        );
291
-        $input = new EE_Select_Input(
292
-            $message_type_options,
293
-            array(
294
-                'html_name'  => 'ee_message_type_filter_by',
295
-                'html_id'    => 'ee_message_type_filter_by',
296
-                'html_class' => 'wide',
297
-                'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
-                    ? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
-                    : 'none_selected',
300
-            )
301
-        );
302
-
303
-        return $input->get_html_for_input();
304
-    }
305
-
306
-
307
-    /**
308
-     * Generate select input with provide message type contexts array.
309
-     *
310
-     * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
-     *                               context label.
312
-     * @return string
313
-     * @throws EE_Error
314
-     */
315
-    public function get_contexts_for_message_types_select_input($context_options)
316
-    {
317
-        // if empty or count of options is one then just return empty string
318
-        if (empty($context_options)
319
-            || ! is_array($context_options)
320
-            || count($context_options) === 1
321
-        ) {
322
-            return '';
323
-        }
324
-        // merge in default
325
-        $context_options = array_merge(
326
-            array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
-            $context_options
328
-        );
329
-        $input = new EE_Select_Input(
330
-            $context_options,
331
-            array(
332
-                'html_name'  => 'ee_context_filter_by',
333
-                'html_id'    => 'ee_context_filter_by',
334
-                'html_class' => 'wide',
335
-                'default'    => isset($this->_req_data['ee_context_filter_by'])
336
-                    ? sanitize_title($this->_req_data['ee_context_filter_by'])
337
-                    : 'none_selected',
338
-            )
339
-        );
340
-
341
-        return $input->get_html_for_input();
342
-    }
343
-
344
-
345
-    protected function _ajax_hooks()
346
-    {
347
-        add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
-        add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
-        add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
-        add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
-        add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
-        add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
-    }
354
-
355
-
356
-    protected function _define_page_props()
357
-    {
358
-        $this->_admin_page_title = $this->page_label;
359
-        $this->_labels = array(
360
-            'buttons'    => array(
361
-                'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
-                'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
-                'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
-            ),
365
-            'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     *        an array for storing key => value pairs of request actions and their corresponding methods
372
-     *
373
-     * @access protected
374
-     * @return void
375
-     */
376
-    protected function _set_page_routes()
377
-    {
378
-        $grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
-            ? $this->_req_data['GRP_ID']
380
-            : 0;
381
-        $grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
-            ? $this->_req_data['id']
383
-            : $grp_id;
384
-        $msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
-            ? $this->_req_data['MSG_ID']
386
-            : 0;
387
-
388
-        $this->_page_routes = array(
389
-            'default'                          => array(
390
-                'func'       => '_message_queue_list_table',
391
-                'capability' => 'ee_read_global_messages',
392
-            ),
393
-            'global_mtps'                      => array(
394
-                'func'       => '_ee_default_messages_overview_list_table',
395
-                'capability' => 'ee_read_global_messages',
396
-            ),
397
-            'custom_mtps'                      => array(
398
-                'func'       => '_custom_mtps_preview',
399
-                'capability' => 'ee_read_messages',
400
-            ),
401
-            'add_new_message_template'         => array(
402
-                'func'       => '_add_message_template',
403
-                'capability' => 'ee_edit_messages',
404
-                'noheader'   => true,
405
-            ),
406
-            'edit_message_template'            => array(
407
-                'func'       => '_edit_message_template',
408
-                'capability' => 'ee_edit_message',
409
-                'obj_id'     => $grp_id,
410
-            ),
411
-            'preview_message'                  => array(
412
-                'func'               => '_preview_message',
413
-                'capability'         => 'ee_read_message',
414
-                'obj_id'             => $grp_id,
415
-                'noheader'           => true,
416
-                'headers_sent_route' => 'display_preview_message',
417
-            ),
418
-            'display_preview_message'          => array(
419
-                'func'       => '_display_preview_message',
420
-                'capability' => 'ee_read_message',
421
-                'obj_id'     => $grp_id,
422
-            ),
423
-            'insert_message_template'          => array(
424
-                'func'       => '_insert_or_update_message_template',
425
-                'capability' => 'ee_edit_messages',
426
-                'args'       => array('new_template' => true),
427
-                'noheader'   => true,
428
-            ),
429
-            'update_message_template'          => array(
430
-                'func'       => '_insert_or_update_message_template',
431
-                'capability' => 'ee_edit_message',
432
-                'obj_id'     => $grp_id,
433
-                'args'       => array('new_template' => false),
434
-                'noheader'   => true,
435
-            ),
436
-            'trash_message_template'           => array(
437
-                'func'       => '_trash_or_restore_message_template',
438
-                'capability' => 'ee_delete_message',
439
-                'obj_id'     => $grp_id,
440
-                'args'       => array('trash' => true, 'all' => true),
441
-                'noheader'   => true,
442
-            ),
443
-            'trash_message_template_context'   => array(
444
-                'func'       => '_trash_or_restore_message_template',
445
-                'capability' => 'ee_delete_message',
446
-                'obj_id'     => $grp_id,
447
-                'args'       => array('trash' => true),
448
-                'noheader'   => true,
449
-            ),
450
-            'restore_message_template'         => array(
451
-                'func'       => '_trash_or_restore_message_template',
452
-                'capability' => 'ee_delete_message',
453
-                'obj_id'     => $grp_id,
454
-                'args'       => array('trash' => false, 'all' => true),
455
-                'noheader'   => true,
456
-            ),
457
-            'restore_message_template_context' => array(
458
-                'func'       => '_trash_or_restore_message_template',
459
-                'capability' => 'ee_delete_message',
460
-                'obj_id'     => $grp_id,
461
-                'args'       => array('trash' => false),
462
-                'noheader'   => true,
463
-            ),
464
-            'delete_message_template'          => array(
465
-                'func'       => '_delete_message_template',
466
-                'capability' => 'ee_delete_message',
467
-                'obj_id'     => $grp_id,
468
-                'noheader'   => true,
469
-            ),
470
-            'reset_to_default'                 => array(
471
-                'func'       => '_reset_to_default_template',
472
-                'capability' => 'ee_edit_message',
473
-                'obj_id'     => $grp_id,
474
-                'noheader'   => true,
475
-            ),
476
-            'settings'                         => array(
477
-                'func'       => '_settings',
478
-                'capability' => 'manage_options',
479
-            ),
480
-            'update_global_settings'           => array(
481
-                'func'       => '_update_global_settings',
482
-                'capability' => 'manage_options',
483
-                'noheader'   => true,
484
-            ),
485
-            'generate_now'                     => array(
486
-                'func'       => '_generate_now',
487
-                'capability' => 'ee_send_message',
488
-                'noheader'   => true,
489
-            ),
490
-            'generate_and_send_now'            => array(
491
-                'func'       => '_generate_and_send_now',
492
-                'capability' => 'ee_send_message',
493
-                'noheader'   => true,
494
-            ),
495
-            'queue_for_resending'              => array(
496
-                'func'       => '_queue_for_resending',
497
-                'capability' => 'ee_send_message',
498
-                'noheader'   => true,
499
-            ),
500
-            'send_now'                         => array(
501
-                'func'       => '_send_now',
502
-                'capability' => 'ee_send_message',
503
-                'noheader'   => true,
504
-            ),
505
-            'delete_ee_message'                => array(
506
-                'func'       => '_delete_ee_messages',
507
-                'capability' => 'ee_delete_messages',
508
-                'noheader'   => true,
509
-            ),
510
-            'delete_ee_messages'               => array(
511
-                'func'       => '_delete_ee_messages',
512
-                'capability' => 'ee_delete_messages',
513
-                'noheader'   => true,
514
-                'obj_id'     => $msg_id,
515
-            ),
516
-        );
517
-    }
518
-
519
-
520
-    protected function _set_page_config()
521
-    {
522
-        $this->_page_config = array(
523
-            'default'                  => array(
524
-                'nav'           => array(
525
-                    'label' => esc_html__('Message Activity', 'event_espresso'),
526
-                    'order' => 10,
527
-                ),
528
-                'list_table'    => 'EE_Message_List_Table',
529
-                // 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
-                'require_nonce' => false,
531
-            ),
532
-            'global_mtps'              => array(
533
-                'nav'           => array(
534
-                    'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
-                    'order' => 20,
536
-                ),
537
-                'list_table'    => 'Messages_Template_List_Table',
538
-                'help_tabs'     => array(
539
-                    'messages_overview_help_tab'                                => array(
540
-                        'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
-                        'filename' => 'messages_overview',
542
-                    ),
543
-                    'messages_overview_messages_table_column_headings_help_tab' => array(
544
-                        'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
-                        'filename' => 'messages_overview_table_column_headings',
546
-                    ),
547
-                    'messages_overview_messages_filters_help_tab'               => array(
548
-                        'title'    => esc_html__('Message Filters', 'event_espresso'),
549
-                        'filename' => 'messages_overview_filters',
550
-                    ),
551
-                    'messages_overview_messages_views_help_tab'                 => array(
552
-                        'title'    => esc_html__('Message Views', 'event_espresso'),
553
-                        'filename' => 'messages_overview_views',
554
-                    ),
555
-                    'message_overview_message_types_help_tab'                   => array(
556
-                        'title'    => esc_html__('Message Types', 'event_espresso'),
557
-                        'filename' => 'messages_overview_types',
558
-                    ),
559
-                    'messages_overview_messengers_help_tab'                     => array(
560
-                        'title'    => esc_html__('Messengers', 'event_espresso'),
561
-                        'filename' => 'messages_overview_messengers',
562
-                    ),
563
-                ),
564
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
565
-                // 'help_tour'     => array('Messages_Overview_Help_Tour'),
566
-                'require_nonce' => false,
567
-            ),
568
-            'custom_mtps'              => array(
569
-                'nav'           => array(
570
-                    'label' => esc_html__('Custom Message Templates', 'event_espresso'),
571
-                    'order' => 30,
572
-                ),
573
-                'help_tabs'     => array(),
574
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
575
-                // 'help_tour'     => array(),
576
-                'require_nonce' => false,
577
-            ),
578
-            'add_new_message_template' => array(
579
-                'nav'           => array(
580
-                    'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
581
-                    'order'      => 5,
582
-                    'persistent' => false,
583
-                ),
584
-                'require_nonce' => false,
585
-            ),
586
-            'edit_message_template'    => array(
587
-                'labels'        => array(
588
-                    'buttons'    => array(
589
-                        'reset' => esc_html__('Reset Templates', 'event_espresso'),
590
-                    ),
591
-                    'publishbox' => esc_html__('Update Actions', 'event_espresso'),
592
-                ),
593
-                'nav'           => array(
594
-                    'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
595
-                    'order'      => 5,
596
-                    'persistent' => false,
597
-                    'url'        => '',
598
-                ),
599
-                'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
600
-                'has_metaboxes' => true,
601
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
602
-                // 'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
603
-                'help_tabs'     => array(
604
-                    'edit_message_template'            => array(
605
-                        'title'    => esc_html__('Message Template Editor', 'event_espresso'),
606
-                        'callback' => 'edit_message_template_help_tab',
607
-                    ),
608
-                    'message_templates_help_tab'       => array(
609
-                        'title'    => esc_html__('Message Templates', 'event_espresso'),
610
-                        'filename' => 'messages_templates',
611
-                    ),
612
-                    'message_template_shortcodes'      => array(
613
-                        'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
614
-                        'callback' => 'message_template_shortcodes_help_tab',
615
-                    ),
616
-                    'message_preview_help_tab'         => array(
617
-                        'title'    => esc_html__('Message Preview', 'event_espresso'),
618
-                        'filename' => 'messages_preview',
619
-                    ),
620
-                    'messages_overview_other_help_tab' => array(
621
-                        'title'    => esc_html__('Messages Other', 'event_espresso'),
622
-                        'filename' => 'messages_overview_other',
623
-                    ),
624
-                ),
625
-                'require_nonce' => false,
626
-            ),
627
-            'display_preview_message'  => array(
628
-                'nav'           => array(
629
-                    'label'      => esc_html__('Message Preview', 'event_espresso'),
630
-                    'order'      => 5,
631
-                    'url'        => '',
632
-                    'persistent' => false,
633
-                ),
634
-                'help_tabs'     => array(
635
-                    'preview_message' => array(
636
-                        'title'    => esc_html__('About Previews', 'event_espresso'),
637
-                        'callback' => 'preview_message_help_tab',
638
-                    ),
639
-                ),
640
-                'require_nonce' => false,
641
-            ),
642
-            'settings'                 => array(
643
-                'nav'           => array(
644
-                    'label' => esc_html__('Settings', 'event_espresso'),
645
-                    'order' => 40,
646
-                ),
647
-                'metaboxes'     => array('_messages_settings_metaboxes'),
648
-                'help_tabs'     => array(
649
-                    'messages_settings_help_tab'               => array(
650
-                        'title'    => esc_html__('Messages Settings', 'event_espresso'),
651
-                        'filename' => 'messages_settings',
652
-                    ),
653
-                    'messages_settings_message_types_help_tab' => array(
654
-                        'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
655
-                        'filename' => 'messages_settings_message_types',
656
-                    ),
657
-                    'messages_settings_messengers_help_tab'    => array(
658
-                        'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
659
-                        'filename' => 'messages_settings_messengers',
660
-                    ),
661
-                ),
662
-                // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
663
-                // 'help_tour'     => array('Messages_Settings_Help_Tour'),
664
-                'require_nonce' => false,
665
-            ),
666
-        );
667
-    }
668
-
669
-
670
-    protected function _add_screen_options()
671
-    {
672
-        // todo
673
-    }
674
-
675
-
676
-    protected function _add_screen_options_global_mtps()
677
-    {
678
-        /**
679
-         * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
680
-         * uses the $_admin_page_title property and we want different outputs in the different spots.
681
-         */
682
-        $page_title = $this->_admin_page_title;
683
-        $this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
684
-        $this->_per_page_screen_option();
685
-        $this->_admin_page_title = $page_title;
686
-    }
687
-
688
-
689
-    protected function _add_screen_options_default()
690
-    {
691
-        $this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
692
-        $this->_per_page_screen_option();
693
-    }
694
-
695
-
696
-    // none of the below group are currently used for Messages
697
-    protected function _add_feature_pointers()
698
-    {
699
-    }
700
-
701
-    public function admin_init()
702
-    {
703
-    }
704
-
705
-    public function admin_notices()
706
-    {
707
-    }
708
-
709
-    public function admin_footer_scripts()
710
-    {
711
-    }
712
-
713
-
714
-    public function messages_help_tab()
715
-    {
716
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
717
-    }
718
-
719
-
720
-    public function messengers_help_tab()
721
-    {
722
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
723
-    }
724
-
725
-
726
-    public function message_types_help_tab()
727
-    {
728
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
729
-    }
730
-
731
-
732
-    public function messages_overview_help_tab()
733
-    {
734
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
735
-    }
736
-
737
-
738
-    public function message_templates_help_tab()
739
-    {
740
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
741
-    }
742
-
743
-
744
-    public function edit_message_template_help_tab()
745
-    {
746
-        $args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
747
-                        . esc_attr__('Editor Title', 'event_espresso')
748
-                        . '" />';
749
-        $args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
750
-                        . esc_attr__('Context Switcher and Preview', 'event_espresso')
751
-                        . '" />';
752
-        $args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
753
-                        . esc_attr__('Message Template Form Fields', 'event_espresso')
754
-                        . '" />';
755
-        $args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
756
-                        . esc_attr__('Shortcodes Metabox', 'event_espresso')
757
-                        . '" />';
758
-        $args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
759
-                        . esc_attr__('Publish Metabox', 'event_espresso')
760
-                        . '" />';
761
-        EEH_Template::display_template(
762
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
763
-            $args
764
-        );
765
-    }
766
-
767
-
768
-    public function message_template_shortcodes_help_tab()
769
-    {
770
-        $this->_set_shortcodes();
771
-        $args['shortcodes'] = $this->_shortcodes;
772
-        EEH_Template::display_template(
773
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
774
-            $args
775
-        );
776
-    }
777
-
778
-
779
-    public function preview_message_help_tab()
780
-    {
781
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
782
-    }
783
-
784
-
785
-    public function settings_help_tab()
786
-    {
787
-        $args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
788
-                        . '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
789
-        $args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
790
-                        . '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
791
-        $args['img3'] = '<div class="switch">'
792
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
793
-                        . ' type="checkbox" checked="checked">'
794
-                        . '<label for="ee-on-off-toggle-on"></label>'
795
-                        . '</div>';
796
-        $args['img4'] = '<div class="switch">'
797
-                        . '<input class="ee-on-off-toggle ee-toggle-round-flat"'
798
-                        . ' type="checkbox">'
799
-                        . '<label for="ee-on-off-toggle-on"></label>'
800
-                        . '</div>';
801
-        EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
802
-    }
803
-
804
-
805
-    public function load_scripts_styles()
806
-    {
807
-        wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
808
-        wp_enqueue_style('espresso_ee_msg');
809
-
810
-        wp_register_script(
811
-            'ee-messages-settings',
812
-            EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
813
-            array('jquery-ui-droppable', 'ee-serialize-full-array'),
814
-            EVENT_ESPRESSO_VERSION,
815
-            true
816
-        );
817
-        wp_register_script(
818
-            'ee-msg-list-table-js',
819
-            EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
820
-            array('ee-dialog'),
821
-            EVENT_ESPRESSO_VERSION
822
-        );
823
-    }
824
-
825
-
826
-    public function load_scripts_styles_default()
827
-    {
828
-        wp_enqueue_script('ee-msg-list-table-js');
829
-    }
830
-
831
-
832
-    public function wp_editor_css($mce_css)
833
-    {
834
-        // if we're on the edit_message_template route
835
-        if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
836
-            $message_type_name = $this->_active_message_type_name;
837
-
838
-            // we're going to REPLACE the existing mce css
839
-            // we need to get the css file location from the active messenger
840
-            $mce_css = $this->_active_messenger->get_variation(
841
-                $this->_template_pack,
842
-                $message_type_name,
843
-                true,
844
-                'wpeditor',
845
-                $this->_variation
846
-            );
847
-        }
848
-
849
-        return $mce_css;
850
-    }
851
-
852
-
853
-    public function load_scripts_styles_edit_message_template()
854
-    {
855
-
856
-        $this->_set_shortcodes();
857
-
858
-        EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
859
-            esc_html__(
860
-                'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
861
-                'event_espresso'
862
-            ),
863
-            $this->_message_template_group->messenger_obj()->label['singular'],
864
-            $this->_message_template_group->message_type_obj()->label['singular']
865
-        );
866
-        EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
867
-            'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
868
-            'event_espresso'
869
-        );
870
-        EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
871
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
872
-            'event_espresso'
873
-        );
874
-
875
-        wp_register_script(
876
-            'ee_msgs_edit_js',
877
-            EE_MSG_ASSETS_URL . 'ee_message_editor.js',
878
-            array('jquery'),
879
-            EVENT_ESPRESSO_VERSION
880
-        );
881
-
882
-        wp_enqueue_script('ee_admin_js');
883
-        wp_enqueue_script('ee_msgs_edit_js');
884
-
885
-        // add in special css for tiny_mce
886
-        add_filter('mce_css', array($this, 'wp_editor_css'));
887
-    }
888
-
889
-
890
-    public function load_scripts_styles_display_preview_message()
891
-    {
892
-
893
-        $this->_set_message_template_group();
894
-
895
-        if (isset($this->_req_data['messenger'])) {
896
-            $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
897
-                $this->_req_data['messenger']
898
-            );
899
-        }
900
-
901
-        $message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
902
-
903
-
904
-        wp_enqueue_style(
905
-            'espresso_preview_css',
906
-            $this->_active_messenger->get_variation(
907
-                $this->_template_pack,
908
-                $message_type_name,
909
-                true,
910
-                'preview',
911
-                $this->_variation
912
-            )
913
-        );
914
-    }
915
-
916
-
917
-    public function load_scripts_styles_settings()
918
-    {
919
-        wp_register_style(
920
-            'ee-message-settings',
921
-            EE_MSG_ASSETS_URL . 'ee_message_settings.css',
922
-            array(),
923
-            EVENT_ESPRESSO_VERSION
924
-        );
925
-        wp_enqueue_style('ee-text-links');
926
-        wp_enqueue_style('ee-message-settings');
927
-        wp_enqueue_script('ee-messages-settings');
928
-    }
929
-
930
-
931
-    /**
932
-     * set views array for List Table
933
-     */
934
-    public function _set_list_table_views_global_mtps()
935
-    {
936
-        $this->_views = array(
937
-            'in_use' => array(
938
-                'slug'  => 'in_use',
939
-                'label' => esc_html__('In Use', 'event_espresso'),
940
-                'count' => 0,
941
-            ),
942
-        );
943
-    }
944
-
945
-
946
-    /**
947
-     * Set views array for the Custom Template List Table
948
-     */
949
-    public function _set_list_table_views_custom_mtps()
950
-    {
951
-        $this->_set_list_table_views_global_mtps();
952
-        $this->_views['in_use']['bulk_action'] = array(
953
-            'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
954
-        );
955
-    }
956
-
957
-
958
-    /**
959
-     * set views array for message queue list table
960
-     *
961
-     * @throws InvalidDataTypeException
962
-     * @throws InvalidInterfaceException
963
-     * @throws InvalidArgumentException
964
-     * @throws EE_Error
965
-     * @throws ReflectionException
966
-     */
967
-    public function _set_list_table_views_default()
968
-    {
969
-        EE_Registry::instance()->load_helper('Template');
970
-
971
-        $common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
972
-            'ee_send_message',
973
-            'message_list_table_bulk_actions'
974
-        )
975
-            ? array(
976
-                'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
977
-                'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
978
-                'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
979
-                'send_now'              => esc_html__('Send Now', 'event_espresso'),
980
-            )
981
-            : array();
982
-
983
-        $delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
984
-            'ee_delete_messages',
985
-            'message_list_table_bulk_actions'
986
-        )
987
-            ? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
988
-            : array();
989
-
990
-
991
-        $this->_views = array(
992
-            'all' => array(
993
-                'slug'        => 'all',
994
-                'label'       => esc_html__('All', 'event_espresso'),
995
-                'count'       => 0,
996
-                'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
997
-            ),
998
-        );
999
-
1000
-
1001
-        foreach (EEM_Message::instance()->all_statuses() as $status) {
1002
-            if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1003
-                continue;
1004
-            }
1005
-            $status_bulk_actions = $common_bulk_actions;
1006
-            // unset bulk actions not applying to status
1007
-            if (! empty($status_bulk_actions)) {
1008
-                switch ($status) {
1009
-                    case EEM_Message::status_idle:
1010
-                    case EEM_Message::status_resend:
1011
-                        $status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1012
-                        break;
1013
-
1014
-                    case EEM_Message::status_failed:
1015
-                    case EEM_Message::status_debug_only:
1016
-                    case EEM_Message::status_messenger_executing:
1017
-                        $status_bulk_actions = array();
1018
-                        break;
1019
-
1020
-                    case EEM_Message::status_incomplete:
1021
-                        unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1022
-                        break;
1023
-
1024
-                    case EEM_Message::status_retry:
1025
-                    case EEM_Message::status_sent:
1026
-                        unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1027
-                        break;
1028
-                }
1029
-            }
1030
-
1031
-            // skip adding messenger executing status to views because it will be included with the Failed view.
1032
-            if ($status === EEM_Message::status_messenger_executing) {
1033
-                continue;
1034
-            }
1035
-
1036
-            $this->_views[ strtolower($status) ] = array(
1037
-                'slug'        => strtolower($status),
1038
-                'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1039
-                'count'       => 0,
1040
-                'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1041
-            );
1042
-        }
1043
-    }
1044
-
1045
-
1046
-    protected function _ee_default_messages_overview_list_table()
1047
-    {
1048
-        $this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1049
-        $this->display_admin_list_table_page_with_no_sidebar();
1050
-    }
1051
-
1052
-
1053
-    protected function _message_queue_list_table()
1054
-    {
1055
-        $this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1056
-        $this->_template_args['per_column'] = 6;
1057
-        $this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1058
-        $this->_template_args['before_list_table'] = '<h3>'
1059
-                                                     . EEM_Message::instance()->get_pretty_label_for_results()
1060
-                                                     . '</h3>';
1061
-        $this->display_admin_list_table_page_with_no_sidebar();
1062
-    }
1063
-
1064
-
1065
-    protected function _message_legend_items()
1066
-    {
1067
-
1068
-        $action_css_classes = EEH_MSG_Template::get_message_action_icons();
1069
-        $action_items = array();
1070
-
1071
-        foreach ($action_css_classes as $action_item => $action_details) {
1072
-            if ($action_item === 'see_notifications_for') {
1073
-                continue;
1074
-            }
1075
-            $action_items[ $action_item ] = array(
1076
-                'class' => $action_details['css_class'],
1077
-                'desc'  => $action_details['label'],
1078
-            );
1079
-        }
1080
-
1081
-        /** @type array $status_items status legend setup */
1082
-        $status_items = array(
1083
-            'sent_status'                => array(
1084
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1085
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1086
-            ),
1087
-            'idle_status'                => array(
1088
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1089
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1090
-            ),
1091
-            'failed_status'              => array(
1092
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1093
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1094
-            ),
1095
-            'messenger_executing_status' => array(
1096
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1097
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1098
-            ),
1099
-            'resend_status'              => array(
1100
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1101
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1102
-            ),
1103
-            'incomplete_status'          => array(
1104
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1105
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1106
-            ),
1107
-            'retry_status'               => array(
1108
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1109
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1110
-            ),
1111
-        );
1112
-        if (EEM_Message::debug()) {
1113
-            $status_items['debug_only_status'] = array(
1114
-                'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1115
-                'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1116
-            );
1117
-        }
1118
-
1119
-        return array_merge($action_items, $status_items);
1120
-    }
1121
-
1122
-
1123
-    protected function _custom_mtps_preview()
1124
-    {
1125
-        $this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1126
-        $this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1127
-                                               . ' alt="' . esc_attr__(
1128
-                                                   'Preview Custom Message Templates screenshot',
1129
-                                                   'event_espresso'
1130
-                                               ) . '" />';
1131
-        $this->_template_args['preview_text'] = '<strong>'
1132
-                                                . esc_html__(
1133
-                                                    'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1134
-                                                    'event_espresso'
1135
-                                                )
1136
-                                                . '</strong>';
1137
-
1138
-        $this->display_admin_caf_preview_page('custom_message_types', false);
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * get_message_templates
1144
-     * This gets all the message templates for listing on the overview list.
1145
-     *
1146
-     * @access public
1147
-     * @param int    $perpage the amount of templates groups to show per page
1148
-     * @param string $type    the current _view we're getting templates for
1149
-     * @param bool   $count   return count?
1150
-     * @param bool   $all     disregard any paging info (get all data);
1151
-     * @param bool   $global  whether to return just global (true) or custom templates (false)
1152
-     * @return array
1153
-     * @throws EE_Error
1154
-     * @throws InvalidArgumentException
1155
-     * @throws InvalidDataTypeException
1156
-     * @throws InvalidInterfaceException
1157
-     */
1158
-    public function get_message_templates(
1159
-        $perpage = 10,
1160
-        $type = 'in_use',
1161
-        $count = false,
1162
-        $all = false,
1163
-        $global = true
1164
-    ) {
1165
-
1166
-        $MTP = EEM_Message_Template_Group::instance();
1167
-
1168
-        $this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1169
-        $orderby = $this->_req_data['orderby'];
1170
-
1171
-        $order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1172
-            ? $this->_req_data['order']
1173
-            : 'ASC';
1174
-
1175
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1176
-            ? $this->_req_data['paged']
1177
-            : 1;
1178
-        $per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1179
-            ? $this->_req_data['perpage']
1180
-            : $perpage;
1181
-
1182
-        $offset = ($current_page - 1) * $per_page;
1183
-        $limit = $all ? null : array($offset, $per_page);
1184
-
1185
-
1186
-        // options will match what is in the _views array property
1187
-        switch ($type) {
1188
-            case 'in_use':
1189
-                $templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1190
-                break;
1191
-            default:
1192
-                $templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1193
-        }
1194
-
1195
-        return $templates;
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * filters etc might need a list of installed message_types
1201
-     *
1202
-     * @return array an array of message type objects
1203
-     */
1204
-    public function get_installed_message_types()
1205
-    {
1206
-        $installed_message_types = $this->_message_resource_manager->installed_message_types();
1207
-        $installed = array();
1208
-
1209
-        foreach ($installed_message_types as $message_type) {
1210
-            $installed[ $message_type->name ] = $message_type;
1211
-        }
1212
-
1213
-        return $installed;
1214
-    }
1215
-
1216
-
1217
-    /**
1218
-     * _add_message_template
1219
-     *
1220
-     * This is used when creating a custom template. All Custom Templates start based off another template.
1221
-     *
1222
-     * @param string $message_type
1223
-     * @param string $messenger
1224
-     * @param string $GRP_ID
1225
-     *
1226
-     * @throws EE_error
1227
-     */
1228
-    protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1229
-    {
1230
-        // set values override any request data
1231
-        $message_type = ! empty($message_type) ? $message_type : '';
1232
-        $message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1233
-            ? $this->_req_data['message_type']
1234
-            : $message_type;
1235
-
1236
-        $messenger = ! empty($messenger) ? $messenger : '';
1237
-        $messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1238
-            ? $this->_req_data['messenger']
1239
-            : $messenger;
1240
-
1241
-        $GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1242
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1243
-
1244
-        // we need messenger and message type.  They should be coming from the event editor. If not here then return error
1245
-        if (empty($message_type) || empty($messenger)) {
1246
-            throw new EE_Error(
1247
-                esc_html__(
1248
-                    'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1249
-                    'event_espresso'
1250
-                )
1251
-            );
1252
-        }
1253
-
1254
-        // we need the GRP_ID for the template being used as the base for the new template
1255
-        if (empty($GRP_ID)) {
1256
-            throw new EE_Error(
1257
-                esc_html__(
1258
-                    'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1259
-                    'event_espresso'
1260
-                )
1261
-            );
1262
-        }
1263
-
1264
-        // let's just make sure the template gets generated!
1265
-
1266
-        // we need to reassign some variables for what the insert is expecting
1267
-        $this->_req_data['MTP_messenger'] = $messenger;
1268
-        $this->_req_data['MTP_message_type'] = $message_type;
1269
-        $this->_req_data['GRP_ID'] = $GRP_ID;
1270
-        $this->_insert_or_update_message_template(true);
1271
-    }
1272
-
1273
-
1274
-    /**
1275
-     * public wrapper for the _add_message_template method
1276
-     *
1277
-     * @param string $message_type     message type slug
1278
-     * @param string $messenger        messenger slug
1279
-     * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1280
-     *                                 off of.
1281
-     * @throws EE_error
1282
-     */
1283
-    public function add_message_template($message_type, $messenger, $GRP_ID)
1284
-    {
1285
-        $this->_add_message_template($message_type, $messenger, $GRP_ID);
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * _edit_message_template
1291
-     *
1292
-     * @access protected
1293
-     * @return void
1294
-     * @throws InvalidIdentifierException
1295
-     * @throws DomainException
1296
-     * @throws EE_Error
1297
-     * @throws InvalidArgumentException
1298
-     * @throws ReflectionException
1299
-     * @throws InvalidDataTypeException
1300
-     * @throws InvalidInterfaceException
1301
-     */
1302
-    protected function _edit_message_template()
1303
-    {
1304
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1305
-        $template_fields = '';
1306
-        $sidebar_fields = '';
1307
-        // we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1308
-        // valid html in the templates.
1309
-        add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1310
-
1311
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1312
-            ? absint($this->_req_data['id'])
1313
-            : false;
1314
-
1315
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1316
-        ? absint($this->_req_data['evt_id'])
1317
-        : false;
1318
-
1319
-        $this->_set_shortcodes(); // this also sets the _message_template property.
1320
-        $message_template_group = $this->_message_template_group;
1321
-        $c_label = $message_template_group->context_label();
1322
-        $c_config = $message_template_group->contexts_config();
1323
-
1324
-        reset($c_config);
1325
-        $context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1326
-            ? strtolower($this->_req_data['context'])
1327
-            : key($c_config);
1328
-
1329
-
1330
-        if (empty($GRP_ID)) {
1331
-            $action = 'insert_message_template';
1332
-            $edit_message_template_form_url = add_query_arg(
1333
-                array('action' => $action, 'noheader' => true),
1334
-                EE_MSG_ADMIN_URL
1335
-            );
1336
-        } else {
1337
-            $action = 'update_message_template';
1338
-            $edit_message_template_form_url = add_query_arg(
1339
-                array('action' => $action, 'noheader' => true),
1340
-                EE_MSG_ADMIN_URL
1341
-            );
1342
-        }
1343
-
1344
-        // set active messenger for this view
1345
-        $this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1346
-            $message_template_group->messenger()
1347
-        );
1348
-        $this->_active_message_type_name = $message_template_group->message_type();
1349
-
1350
-
1351
-        // Do we have any validation errors?
1352
-        $validators = $this->_get_transient();
1353
-        $v_fields = ! empty($validators) ? array_keys($validators) : array();
1354
-
1355
-
1356
-        // we need to assemble the title from Various details
1357
-        $context_label = sprintf(
1358
-            esc_html__('(%s %s)', 'event_espresso'),
1359
-            $c_config[ $context ]['label'],
1360
-            ucwords($c_label['label'])
1361
-        );
1362
-
1363
-        $title = sprintf(
1364
-            esc_html__(' %s %s Template %s', 'event_espresso'),
1365
-            ucwords($message_template_group->messenger_obj()->label['singular']),
1366
-            ucwords($message_template_group->message_type_obj()->label['singular']),
1367
-            $context_label
1368
-        );
1369
-
1370
-        $this->_template_args['GRP_ID'] = $GRP_ID;
1371
-        $this->_template_args['message_template'] = $message_template_group;
1372
-        $this->_template_args['is_extra_fields'] = false;
1373
-
1374
-
1375
-        // let's get EEH_MSG_Template so we can get template form fields
1376
-        $template_field_structure = EEH_MSG_Template::get_fields(
1377
-            $message_template_group->messenger(),
1378
-            $message_template_group->message_type()
1379
-        );
1380
-
1381
-        if (! $template_field_structure) {
1382
-            $template_field_structure = false;
1383
-            $template_fields = esc_html__(
1384
-                'There was an error in assembling the fields for this display (you should see an error message)',
1385
-                'event_espresso'
1386
-            );
1387
-        }
1388
-
1389
-
1390
-        $message_templates = $message_template_group->context_templates();
1391
-
1392
-
1393
-        // if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394
-        // will get handled in the "extra" array.
1395
-        if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
-            foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
-                unset($template_field_structure[ $context ][ $reference_field ]);
1398
-            }
1399
-        }
1400
-
1401
-        // let's loop through the template_field_structure and actually assemble the input fields!
1402
-        if (! empty($template_field_structure)) {
1403
-            foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1404
-                // if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405
-                // the extra array and reset them.
1406
-                if ($template_field === 'extra') {
1407
-                    $this->_template_args['is_extra_fields'] = true;
1408
-                    foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
-                        $message_template = $message_templates[ $context ][ $reference_field ];
1410
-                        $content = $message_template instanceof EE_Message_Template
1411
-                            ? $message_template->get('MTP_content')
1412
-                            : '';
1413
-                        foreach ($new_fields_array as $extra_field => $extra_array) {
1414
-                            // let's verify if we need this extra field via the shortcodes parameter.
1415
-                            $continue = false;
1416
-                            if (isset($extra_array['shortcodes_required'])) {
1417
-                                foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
-                                    if (! array_key_exists($shortcode, $this->_shortcodes)) {
1419
-                                        $continue = true;
1420
-                                    }
1421
-                                }
1422
-                                if ($continue) {
1423
-                                    continue;
1424
-                                }
1425
-                            }
1426
-
1427
-                            $field_id = $reference_field
1428
-                                        . '-'
1429
-                                        . $extra_field
1430
-                                        . '-content';
1431
-                            $template_form_fields[ $field_id ] = $extra_array;
1432
-                            $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1433
-                                                                         . $reference_field
1434
-                                                                         . '][content]['
1435
-                                                                         . $extra_field . ']';
1436
-                            $css_class = isset($extra_array['css_class'])
1437
-                                ? $extra_array['css_class']
1438
-                                : '';
1439
-
1440
-                            $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1441
-                                                                              && in_array($extra_field, $v_fields, true)
1442
-                                                                              &&
1443
-                                                                              (
1444
-                                                                                  is_array($validators[ $extra_field ])
1445
-                                                                                  && isset($validators[ $extra_field ]['msg'])
1446
-                                                                              )
1447
-                                ? 'validate-error ' . $css_class
1448
-                                : $css_class;
1449
-
1450
-                            $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1451
-                                                                          && isset($content[ $extra_field ])
1452
-                                ? $content[ $extra_field ]
1453
-                                : '';
1454
-
1455
-                            // do we have a validation error?  if we do then let's use that value instead
1456
-                            $template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1457
-                                ? $validators[ $extra_field ]['value']
1458
-                                : $template_form_fields[ $field_id ]['value'];
1459
-
1460
-
1461
-                            $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1462
-
1463
-                            // shortcode selector
1464
-                            $field_name_to_use = $extra_field === 'main'
1465
-                                ? 'content'
1466
-                                : $extra_field;
1467
-                            $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1468
-                                $field_name_to_use,
1469
-                                $field_id
1470
-                            );
1471
-
1472
-                            if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1473
-                                // we want to decode the entities
1474
-                                $template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1475
-                            }/**/
1476
-                        }
1477
-                        $templatefield_MTP_id = $reference_field . '-MTP_ID';
1478
-                        $templatefield_templatename_id = $reference_field . '-name';
1479
-
1480
-                        $template_form_fields[ $templatefield_MTP_id ] = array(
1481
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1482
-                            'label'      => null,
1483
-                            'input'      => 'hidden',
1484
-                            'type'       => 'int',
1485
-                            'required'   => false,
1486
-                            'validation' => false,
1487
-                            'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1488
-                            'css_class'  => '',
1489
-                            'format'     => '%d',
1490
-                            'db-col'     => 'MTP_ID',
1491
-                        );
1492
-
1493
-                        $template_form_fields[ $templatefield_templatename_id ] = array(
1494
-                            'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1495
-                            'label'      => null,
1496
-                            'input'      => 'hidden',
1497
-                            'type'       => 'string',
1498
-                            'required'   => false,
1499
-                            'validation' => true,
1500
-                            'value'      => $reference_field,
1501
-                            'css_class'  => '',
1502
-                            'format'     => '%s',
1503
-                            'db-col'     => 'MTP_template_field',
1504
-                        );
1505
-                    }
1506
-                    continue; // skip the next stuff, we got the necessary fields here for this dataset.
1507
-                } else {
1508
-                    $field_id = $template_field . '-content';
1509
-                    $template_form_fields[ $field_id ] = $field_setup_array;
1510
-                    $template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1511
-                    $message_template = isset($message_templates[ $context ][ $template_field ])
1512
-                        ? $message_templates[ $context ][ $template_field ]
1513
-                        : null;
1514
-                    $template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1515
-                                                                  && is_array($message_templates[ $context ])
1516
-                                                                  && $message_template instanceof EE_Message_Template
1517
-                        ? $message_template->get('MTP_content')
1518
-                        : '';
1519
-
1520
-                    // do we have a validator error for this field?  if we do then we'll use that value instead
1521
-                    $template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1522
-                        ? $validators[ $template_field ]['value']
1523
-                        : $template_form_fields[ $field_id ]['value'];
1524
-
1525
-
1526
-                    $template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1527
-                    $css_class = isset($field_setup_array['css_class'])
1528
-                        ? $field_setup_array['css_class']
1529
-                        : '';
1530
-                    $template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1531
-                                                                      && in_array($template_field, $v_fields, true)
1532
-                                                                      && isset($validators[ $template_field ]['msg'])
1533
-                        ? 'validate-error ' . $css_class
1534
-                        : $css_class;
1535
-
1536
-                    // shortcode selector
1537
-                    $template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1538
-                        $template_field,
1539
-                        $field_id
1540
-                    );
1541
-                }
1542
-
1543
-                // k took care of content field(s) now let's take care of others.
1544
-
1545
-                $templatefield_MTP_id = $template_field . '-MTP_ID';
1546
-                $templatefield_field_templatename_id = $template_field . '-name';
1547
-
1548
-                // foreach template field there are actually two form fields created
1549
-                $template_form_fields[ $templatefield_MTP_id ] = array(
1550
-                    'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1551
-                    'label'      => null,
1552
-                    'input'      => 'hidden',
1553
-                    'type'       => 'int',
1554
-                    'required'   => false,
1555
-                    'validation' => true,
1556
-                    'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1557
-                    'css_class'  => '',
1558
-                    'format'     => '%d',
1559
-                    'db-col'     => 'MTP_ID',
1560
-                );
1561
-
1562
-                $template_form_fields[ $templatefield_field_templatename_id ] = array(
1563
-                    'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1564
-                    'label'      => null,
1565
-                    'input'      => 'hidden',
1566
-                    'type'       => 'string',
1567
-                    'required'   => false,
1568
-                    'validation' => true,
1569
-                    'value'      => $template_field,
1570
-                    'css_class'  => '',
1571
-                    'format'     => '%s',
1572
-                    'db-col'     => 'MTP_template_field',
1573
-                );
1574
-            }
1575
-
1576
-            // add other fields
1577
-            $template_form_fields['ee-msg-current-context'] = array(
1578
-                'name'       => 'MTP_context',
1579
-                'label'      => null,
1580
-                'input'      => 'hidden',
1581
-                'type'       => 'string',
1582
-                'required'   => false,
1583
-                'validation' => true,
1584
-                'value'      => $context,
1585
-                'css_class'  => '',
1586
-                'format'     => '%s',
1587
-                'db-col'     => 'MTP_context',
1588
-            );
1589
-
1590
-            $template_form_fields['ee-msg-grp-id'] = array(
1591
-                'name'       => 'GRP_ID',
1592
-                'label'      => null,
1593
-                'input'      => 'hidden',
1594
-                'type'       => 'int',
1595
-                'required'   => false,
1596
-                'validation' => true,
1597
-                'value'      => $GRP_ID,
1598
-                'css_class'  => '',
1599
-                'format'     => '%d',
1600
-                'db-col'     => 'GRP_ID',
1601
-            );
1602
-
1603
-            $template_form_fields['ee-msg-messenger'] = array(
1604
-                'name'       => 'MTP_messenger',
1605
-                'label'      => null,
1606
-                'input'      => 'hidden',
1607
-                'type'       => 'string',
1608
-                'required'   => false,
1609
-                'validation' => true,
1610
-                'value'      => $message_template_group->messenger(),
1611
-                'css_class'  => '',
1612
-                'format'     => '%s',
1613
-                'db-col'     => 'MTP_messenger',
1614
-            );
1615
-
1616
-            $template_form_fields['ee-msg-message-type'] = array(
1617
-                'name'       => 'MTP_message_type',
1618
-                'label'      => null,
1619
-                'input'      => 'hidden',
1620
-                'type'       => 'string',
1621
-                'required'   => false,
1622
-                'validation' => true,
1623
-                'value'      => $message_template_group->message_type(),
1624
-                'css_class'  => '',
1625
-                'format'     => '%s',
1626
-                'db-col'     => 'MTP_message_type',
1627
-            );
1628
-
1629
-            $sidebar_form_fields['ee-msg-is-global'] = array(
1630
-                'name'       => 'MTP_is_global',
1631
-                'label'      => esc_html__('Global Template', 'event_espresso'),
1632
-                'input'      => 'hidden',
1633
-                'type'       => 'int',
1634
-                'required'   => false,
1635
-                'validation' => true,
1636
-                'value'      => $message_template_group->get('MTP_is_global'),
1637
-                'css_class'  => '',
1638
-                'format'     => '%d',
1639
-                'db-col'     => 'MTP_is_global',
1640
-            );
1641
-
1642
-            $sidebar_form_fields['ee-msg-is-override'] = array(
1643
-                'name'       => 'MTP_is_override',
1644
-                'label'      => esc_html__('Override all custom', 'event_espresso'),
1645
-                'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1646
-                'type'       => 'int',
1647
-                'required'   => false,
1648
-                'validation' => true,
1649
-                'value'      => $message_template_group->get('MTP_is_override'),
1650
-                'css_class'  => '',
1651
-                'format'     => '%d',
1652
-                'db-col'     => 'MTP_is_override',
1653
-            );
1654
-
1655
-            $sidebar_form_fields['ee-msg-is-active'] = array(
1656
-                'name'       => 'MTP_is_active',
1657
-                'label'      => esc_html__('Active Template', 'event_espresso'),
1658
-                'input'      => 'hidden',
1659
-                'type'       => 'int',
1660
-                'required'   => false,
1661
-                'validation' => true,
1662
-                'value'      => $message_template_group->is_active(),
1663
-                'css_class'  => '',
1664
-                'format'     => '%d',
1665
-                'db-col'     => 'MTP_is_active',
1666
-            );
1667
-
1668
-            $sidebar_form_fields['ee-msg-deleted'] = array(
1669
-                'name'       => 'MTP_deleted',
1670
-                'label'      => null,
1671
-                'input'      => 'hidden',
1672
-                'type'       => 'int',
1673
-                'required'   => false,
1674
-                'validation' => true,
1675
-                'value'      => $message_template_group->get('MTP_deleted'),
1676
-                'css_class'  => '',
1677
-                'format'     => '%d',
1678
-                'db-col'     => 'MTP_deleted',
1679
-            );
1680
-            $sidebar_form_fields['ee-msg-author'] = array(
1681
-                'name'       => 'MTP_user_id',
1682
-                'label'      => esc_html__('Author', 'event_espresso'),
1683
-                'input'      => 'hidden',
1684
-                'type'       => 'int',
1685
-                'required'   => false,
1686
-                'validation' => false,
1687
-                'value'      => $message_template_group->user(),
1688
-                'format'     => '%d',
1689
-                'db-col'     => 'MTP_user_id',
1690
-            );
1691
-
1692
-            $sidebar_form_fields['ee-msg-route'] = array(
1693
-                'name'  => 'action',
1694
-                'input' => 'hidden',
1695
-                'type'  => 'string',
1696
-                'value' => $action,
1697
-            );
1698
-
1699
-            $sidebar_form_fields['ee-msg-id'] = array(
1700
-                'name'  => 'id',
1701
-                'input' => 'hidden',
1702
-                'type'  => 'int',
1703
-                'value' => $GRP_ID,
1704
-            );
1705
-            $sidebar_form_fields['ee-msg-evt-nonce'] = array(
1706
-                'name'  => $action . '_nonce',
1707
-                'input' => 'hidden',
1708
-                'type'  => 'string',
1709
-                'value' => wp_create_nonce($action . '_nonce'),
1710
-            );
1711
-
1712
-            if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1713
-                $sidebar_form_fields['ee-msg-template-switch'] = array(
1714
-                    'name'  => 'template_switch',
1715
-                    'input' => 'hidden',
1716
-                    'type'  => 'int',
1717
-                    'value' => 1,
1718
-                );
1719
-            }
1720
-
1721
-
1722
-            $template_fields = $this->_generate_admin_form_fields($template_form_fields);
1723
-            $sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1724
-        } //end if ( !empty($template_field_structure) )
1725
-
1726
-        // set extra content for publish box
1727
-        $this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1728
-        $this->_set_publish_post_box_vars(
1729
-            'id',
1730
-            $GRP_ID,
1731
-            false,
1732
-            add_query_arg(
1733
-                array('action' => 'global_mtps'),
1734
-                $this->_admin_base_url
1735
-            )
1736
-        );
1737
-
1738
-        // add preview button
1739
-        $preview_url = parent::add_query_args_and_nonce(
1740
-            array(
1741
-                'message_type' => $message_template_group->message_type(),
1742
-                'messenger'    => $message_template_group->messenger(),
1743
-                'context'      => $context,
1744
-                'GRP_ID'       => $GRP_ID,
1745
-                'evt_id'       => $EVT_ID,
1746
-                'action'       => 'preview_message',
1747
-            ),
1748
-            $this->_admin_base_url
1749
-        );
1750
-        $preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1751
-                          . esc_html__('Preview', 'event_espresso')
1752
-                          . '</a>';
1753
-
1754
-
1755
-        // setup context switcher
1756
-        $context_switcher_args = array(
1757
-            'page'    => 'espresso_messages',
1758
-            'action'  => 'edit_message_template',
1759
-            'id'      => $GRP_ID,
1760
-            'evt_id'  => $EVT_ID,
1761
-            'context' => $context,
1762
-            'extra'   => $preview_button,
1763
-        );
1764
-        $this->_set_context_switcher($message_template_group, $context_switcher_args);
1765
-
1766
-
1767
-        // main box
1768
-        $this->_template_args['template_fields'] = $template_fields;
1769
-        $this->_template_args['sidebar_box_id'] = 'details';
1770
-        $this->_template_args['action'] = $action;
1771
-        $this->_template_args['context'] = $context;
1772
-        $this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1773
-        $this->_template_args['learn_more_about_message_templates_link'] =
1774
-            $this->_learn_more_about_message_templates_link();
1775
-
1776
-
1777
-        $this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1778
-        $this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1779
-            $message_template_group,
1780
-            $context,
1781
-            $context_label
1782
-        );
1783
-        $this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1784
-        $this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1785
-
1786
-        $this->_template_path = $this->_template_args['GRP_ID']
1787
-            ? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1788
-            : EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1789
-
1790
-        // send along EE_Message_Template_Group object for further template use.
1791
-        $this->_template_args['MTP'] = $message_template_group;
1792
-
1793
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1794
-            $this->_template_path,
1795
-            $this->_template_args,
1796
-            true
1797
-        );
1798
-
1799
-
1800
-        // finally, let's set the admin_page title
1801
-        $this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1802
-
1803
-
1804
-        // we need to take care of setting the shortcodes property for use elsewhere.
1805
-        $this->_set_shortcodes();
1806
-
1807
-
1808
-        // final template wrapper
1809
-        $this->display_admin_page_with_sidebar();
1810
-    }
1811
-
1812
-
1813
-    public function filter_tinymce_init($mceInit, $editor_id)
1814
-    {
1815
-        return $mceInit;
1816
-    }
1817
-
1818
-
1819
-    public function add_context_switcher()
1820
-    {
1821
-        return $this->_context_switcher;
1822
-    }
1823
-
1824
-
1825
-    /**
1826
-     * Adds the activation/deactivation toggle for the message template context.
1827
-     *
1828
-     * @param EE_Message_Template_Group $message_template_group
1829
-     * @param string                    $context
1830
-     * @param string                    $context_label
1831
-     * @return string
1832
-     * @throws DomainException
1833
-     * @throws EE_Error
1834
-     * @throws InvalidIdentifierException
1835
-     */
1836
-    protected function add_active_context_element(
1837
-        EE_Message_Template_Group $message_template_group,
1838
-        $context,
1839
-        $context_label
1840
-    ) {
1841
-        $template_args = array(
1842
-            'context'                   => $context,
1843
-            'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1844
-            'is_active'                 => $message_template_group->is_context_active($context),
1845
-            'on_off_action'             => $message_template_group->is_context_active($context)
1846
-                ? 'context-off'
1847
-                : 'context-on',
1848
-            'context_label'             => str_replace(array('(', ')'), '', $context_label),
1849
-            'message_template_group_id' => $message_template_group->ID(),
1850
-        );
1851
-        return EEH_Template::display_template(
1852
-            EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1853
-            $template_args,
1854
-            true
1855
-        );
1856
-    }
1857
-
1858
-
1859
-    /**
1860
-     * Ajax callback for `toggle_context_template` ajax action.
1861
-     * Handles toggling the message context on or off.
1862
-     *
1863
-     * @throws EE_Error
1864
-     * @throws InvalidArgumentException
1865
-     * @throws InvalidDataTypeException
1866
-     * @throws InvalidIdentifierException
1867
-     * @throws InvalidInterfaceException
1868
-     */
1869
-    public function toggle_context_template()
1870
-    {
1871
-        $success = true;
1872
-        // check for required data
1873
-        if (! isset(
1874
-            $this->_req_data['message_template_group_id'],
1875
-            $this->_req_data['context'],
1876
-            $this->_req_data['status']
1877
-        )) {
1878
-            EE_Error::add_error(
1879
-                esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1880
-                __FILE__,
1881
-                __FUNCTION__,
1882
-                __LINE__
1883
-            );
1884
-            $success = false;
1885
-        }
1886
-
1887
-        $nonce = isset($this->_req_data['toggle_context_nonce'])
1888
-            ? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1889
-            : '';
1890
-        $nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1891
-        $this->_verify_nonce($nonce, $nonce_ref);
1892
-        $status = $this->_req_data['status'];
1893
-        if ($status !== 'off' && $status !== 'on') {
1894
-            EE_Error::add_error(
1895
-                sprintf(
1896
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1897
-                    $this->_req_data['status']
1898
-                ),
1899
-                __FILE__,
1900
-                __FUNCTION__,
1901
-                __LINE__
1902
-            );
1903
-            $success = false;
1904
-        }
1905
-        $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1906
-            $this->_req_data['message_template_group_id']
1907
-        );
1908
-        if (! $message_template_group instanceof EE_Message_Template_Group) {
1909
-            EE_Error::add_error(
1910
-                sprintf(
1911
-                    esc_html__(
1912
-                        'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1913
-                        'event_espresso'
1914
-                    ),
1915
-                    $this->_req_data['message_template_group_id'],
1916
-                    'EE_Message_Template_Group'
1917
-                ),
1918
-                __FILE__,
1919
-                __FUNCTION__,
1920
-                __LINE__
1921
-            );
1922
-            $success = false;
1923
-        }
1924
-        if ($success) {
1925
-            $success = $status === 'off'
1926
-                ? $message_template_group->deactivate_context($this->_req_data['context'])
1927
-                : $message_template_group->activate_context($this->_req_data['context']);
1928
-        }
1929
-        $this->_template_args['success'] = $success;
1930
-        $this->_return_json();
1931
-    }
1932
-
1933
-
1934
-    public function _add_form_element_before()
1935
-    {
1936
-        return '<form method="post" action="'
1937
-               . $this->_template_args["edit_message_template_form_url"]
1938
-               . '" id="ee-msg-edit-frm">';
1939
-    }
1940
-
1941
-    public function _add_form_element_after()
1942
-    {
1943
-        return '</form>';
1944
-    }
1945
-
1946
-
1947
-    /**
1948
-     * This executes switching the template pack for a message template.
1949
-     *
1950
-     * @since 4.5.0
1951
-     * @throws EE_Error
1952
-     * @throws InvalidDataTypeException
1953
-     * @throws InvalidInterfaceException
1954
-     * @throws InvalidArgumentException
1955
-     * @throws ReflectionException
1956
-     */
1957
-    public function switch_template_pack()
1958
-    {
1959
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1960
-        $template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1961
-
1962
-        // verify we have needed values.
1963
-        if (empty($GRP_ID) || empty($template_pack)) {
1964
-            $this->_template_args['error'] = true;
1965
-            EE_Error::add_error(
1966
-                esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1967
-                __FILE__,
1968
-                __FUNCTION__,
1969
-                __LINE__
1970
-            );
1971
-        } else {
1972
-            // get template, set the new template_pack and then reset to default
1973
-            /** @type EE_Message_Template_Group $message_template_group */
1974
-            $message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1975
-
1976
-            $message_template_group->set_template_pack_name($template_pack);
1977
-            $this->_req_data['msgr'] = $message_template_group->messenger();
1978
-            $this->_req_data['mt'] = $message_template_group->message_type();
1979
-
1980
-            $query_args = $this->_reset_to_default_template();
1981
-
1982
-            if (empty($query_args['id'])) {
1983
-                EE_Error::add_error(
1984
-                    esc_html__(
1985
-                        'Something went wrong with switching the template pack. Please try again or contact EE support',
1986
-                        'event_espresso'
1987
-                    ),
1988
-                    __FILE__,
1989
-                    __FUNCTION__,
1990
-                    __LINE__
1991
-                );
1992
-                $this->_template_args['error'] = true;
1993
-            } else {
1994
-                $template_label = $message_template_group->get_template_pack()->label;
1995
-                $template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1996
-                EE_Error::add_success(
1997
-                    sprintf(
1998
-                        esc_html__(
1999
-                            'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2000
-                            'event_espresso'
2001
-                        ),
2002
-                        $template_label,
2003
-                        $template_pack_labels->template_pack
2004
-                    )
2005
-                );
2006
-                // generate the redirect url for js.
2007
-                $url = self::add_query_args_and_nonce(
2008
-                    $query_args,
2009
-                    $this->_admin_base_url
2010
-                );
2011
-                $this->_template_args['data']['redirect_url'] = $url;
2012
-                $this->_template_args['success'] = true;
2013
-            }
2014
-
2015
-            $this->_return_json();
2016
-        }
2017
-    }
2018
-
2019
-
2020
-    /**
2021
-     * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2022
-     * they want.
2023
-     *
2024
-     * @access protected
2025
-     * @return array|null
2026
-     * @throws EE_Error
2027
-     * @throws InvalidArgumentException
2028
-     * @throws InvalidDataTypeException
2029
-     * @throws InvalidInterfaceException
2030
-     */
2031
-    protected function _reset_to_default_template()
2032
-    {
2033
-
2034
-        $templates = array();
2035
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2036
-        // we need to make sure we've got the info we need.
2037
-        if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2038
-            EE_Error::add_error(
2039
-                esc_html__(
2040
-                    'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2041
-                    'event_espresso'
2042
-                ),
2043
-                __FILE__,
2044
-                __FUNCTION__,
2045
-                __LINE__
2046
-            );
2047
-        }
2048
-
2049
-        // all templates will be reset to whatever the defaults are
2050
-        // for the global template matching the messenger and message type.
2051
-        $success = ! empty($GRP_ID) ? true : false;
2052
-
2053
-        if ($success) {
2054
-            // let's first determine if the incoming template is a global template,
2055
-            // if it isn't then we need to get the global template matching messenger and message type.
2056
-            // $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2057
-
2058
-
2059
-            // note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2060
-            $success = $this->_delete_mtp_permanently($GRP_ID, false);
2061
-
2062
-            if ($success) {
2063
-                // if successfully deleted, lets generate the new ones.
2064
-                // Note. We set GLOBAL to true, because resets on ANY template
2065
-                // will use the related global template defaults for regeneration.
2066
-                // This means that if a custom template is reset it resets to whatever the related global template is.
2067
-                // HOWEVER, we DO keep the template pack and template variation set
2068
-                // for the current custom template when resetting.
2069
-                $templates = $this->_generate_new_templates(
2070
-                    $this->_req_data['msgr'],
2071
-                    $this->_req_data['mt'],
2072
-                    $GRP_ID,
2073
-                    true
2074
-                );
2075
-            }
2076
-        }
2077
-
2078
-        // any error messages?
2079
-        if (! $success) {
2080
-            EE_Error::add_error(
2081
-                esc_html__(
2082
-                    'Something went wrong with deleting existing templates. Unable to reset to default',
2083
-                    'event_espresso'
2084
-                ),
2085
-                __FILE__,
2086
-                __FUNCTION__,
2087
-                __LINE__
2088
-            );
2089
-        }
2090
-
2091
-        // all good, let's add a success message!
2092
-        if ($success && ! empty($templates)) {
2093
-            // the info for the template we generated is the first element in the returned array
2094
-            // $templates = $templates[0];
2095
-            EE_Error::overwrite_success();
2096
-            EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2097
-        }
2098
-
2099
-
2100
-        $query_args = array(
2101
-            'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2102
-            'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2103
-            'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2104
-        );
2105
-
2106
-        // if called via ajax then we return query args otherwise redirect
2107
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2108
-            return $query_args;
2109
-        } else {
2110
-            $this->_redirect_after_action(false, '', '', $query_args, true);
2111
-
2112
-            return null;
2113
-        }
2114
-    }
2115
-
2116
-
2117
-    /**
2118
-     * Retrieve and set the message preview for display.
2119
-     *
2120
-     * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2121
-     * @return string
2122
-     * @throws ReflectionException
2123
-     * @throws EE_Error
2124
-     * @throws InvalidArgumentException
2125
-     * @throws InvalidDataTypeException
2126
-     * @throws InvalidInterfaceException
2127
-     */
2128
-    public function _preview_message($send = false)
2129
-    {
2130
-        // first make sure we've got the necessary parameters
2131
-        if (! isset(
2132
-            $this->_req_data['message_type'],
2133
-            $this->_req_data['messenger'],
2134
-            $this->_req_data['messenger'],
2135
-            $this->_req_data['GRP_ID']
2136
-        )) {
2137
-            EE_Error::add_error(
2138
-                esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2139
-                __FILE__,
2140
-                __FUNCTION__,
2141
-                __LINE__
2142
-            );
2143
-        }
2144
-
2145
-        EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
22
+	/**
23
+	 * @type EE_Message_Resource_Manager $_message_resource_manager
24
+	 */
25
+	protected $_message_resource_manager;
26
+
27
+	/**
28
+	 * @type string $_active_message_type_name
29
+	 */
30
+	protected $_active_message_type_name = '';
31
+
32
+	/**
33
+	 * @type EE_messenger $_active_messenger
34
+	 */
35
+	protected $_active_messenger;
36
+	protected $_activate_state;
37
+	protected $_activate_meta_box_type;
38
+	protected $_current_message_meta_box;
39
+	protected $_current_message_meta_box_object;
40
+	protected $_context_switcher;
41
+	protected $_shortcodes = array();
42
+	protected $_active_messengers = array();
43
+	protected $_active_message_types = array();
44
+
45
+	/**
46
+	 * @var EE_Message_Template_Group $_message_template_group
47
+	 */
48
+	protected $_message_template_group;
49
+	protected $_m_mt_settings = array();
50
+
51
+
52
+	/**
53
+	 * This is set via the _set_message_template_group method and holds whatever the template pack for the group is.
54
+	 * IF there is no group then it gets automatically set to the Default template pack.
55
+	 *
56
+	 * @since 4.5.0
57
+	 *
58
+	 * @var EE_Messages_Template_Pack
59
+	 */
60
+	protected $_template_pack;
61
+
62
+
63
+	/**
64
+	 * This is set via the _set_message_template_group method and holds whatever the template pack variation for the
65
+	 * group is.  If there is no group then it automatically gets set to default.
66
+	 *
67
+	 * @since 4.5.0
68
+	 *
69
+	 * @var string
70
+	 */
71
+	protected $_variation;
72
+
73
+
74
+	/**
75
+	 * @param bool $routing
76
+	 * @throws EE_Error
77
+	 */
78
+	public function __construct($routing = true)
79
+	{
80
+		// make sure messages autoloader is running
81
+		EED_Messages::set_autoloaders();
82
+		parent::__construct($routing);
83
+	}
84
+
85
+
86
+	protected function _init_page_props()
87
+	{
88
+		$this->page_slug = EE_MSG_PG_SLUG;
89
+		$this->page_label = esc_html__('Messages Settings', 'event_espresso');
90
+		$this->_admin_base_url = EE_MSG_ADMIN_URL;
91
+		$this->_admin_base_path = EE_MSG_ADMIN;
92
+
93
+		$this->_activate_state = isset($this->_req_data['activate_state']) ? (array) $this->_req_data['activate_state']
94
+			: array();
95
+
96
+		$this->_active_messenger = isset($this->_req_data['messenger']) ? $this->_req_data['messenger'] : null;
97
+		$this->_load_message_resource_manager();
98
+	}
99
+
100
+
101
+	/**
102
+	 * loads messenger objects into the $_active_messengers property (so we can access the needed methods)
103
+	 *
104
+	 * @throws EE_Error
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 * @throws InvalidArgumentException
108
+	 * @throws ReflectionException
109
+	 */
110
+	protected function _load_message_resource_manager()
111
+	{
112
+		$this->_message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated 4.9.9.rc.014
118
+	 * @return array
119
+	 * @throws EE_Error
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws InvalidInterfaceException
123
+	 */
124
+	public function get_messengers_for_list_table()
125
+	{
126
+		EE_Error::doing_it_wrong(
127
+			__METHOD__,
128
+			sprintf(
129
+				esc_html__(
130
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a messenger filter dropdown which is now generated differently via %s',
131
+					'event_espresso'
132
+				),
133
+				'Messages_Admin_Page::get_messengers_select_input()'
134
+			),
135
+			'4.9.9.rc.014'
136
+		);
137
+
138
+		$m_values = array();
139
+		$active_messengers = EEM_Message::instance()->get_all(array('group_by' => 'MSG_messenger'));
140
+		// setup messengers for selects
141
+		$i = 1;
142
+		foreach ($active_messengers as $active_messenger) {
143
+			if ($active_messenger instanceof EE_Message) {
144
+				$m_values[ $i ]['id'] = $active_messenger->messenger();
145
+				$m_values[ $i ]['text'] = ucwords($active_messenger->messenger_label());
146
+				$i++;
147
+			}
148
+		}
149
+
150
+		return $m_values;
151
+	}
152
+
153
+
154
+	/**
155
+	 * @deprecated 4.9.9.rc.014
156
+	 * @return array
157
+	 * @throws EE_Error
158
+	 * @throws InvalidArgumentException
159
+	 * @throws InvalidDataTypeException
160
+	 * @throws InvalidInterfaceException
161
+	 */
162
+	public function get_message_types_for_list_table()
163
+	{
164
+		EE_Error::doing_it_wrong(
165
+			__METHOD__,
166
+			sprintf(
167
+				esc_html__(
168
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type filter dropdown which is now generated differently via %s',
169
+					'event_espresso'
170
+				),
171
+				'Messages_Admin_Page::get_message_types_select_input()'
172
+			),
173
+			'4.9.9.rc.014'
174
+		);
175
+
176
+		$mt_values = array();
177
+		$active_messages = EEM_Message::instance()->get_all(array('group_by' => 'MSG_message_type'));
178
+		$i = 1;
179
+		foreach ($active_messages as $active_message) {
180
+			if ($active_message instanceof EE_Message) {
181
+				$mt_values[ $i ]['id'] = $active_message->message_type();
182
+				$mt_values[ $i ]['text'] = ucwords($active_message->message_type_label());
183
+				$i++;
184
+			}
185
+		}
186
+
187
+		return $mt_values;
188
+	}
189
+
190
+
191
+	/**
192
+	 * @deprecated 4.9.9.rc.014
193
+	 * @return array
194
+	 * @throws EE_Error
195
+	 * @throws InvalidArgumentException
196
+	 * @throws InvalidDataTypeException
197
+	 * @throws InvalidInterfaceException
198
+	 */
199
+	public function get_contexts_for_message_types_for_list_table()
200
+	{
201
+		EE_Error::doing_it_wrong(
202
+			__METHOD__,
203
+			sprintf(
204
+				esc_html__(
205
+					'This method is no longer in use.  There is no replacement for it. The method was used to generate a set of values for use in creating a message type context filter dropdown which is now generated differently via %s',
206
+					'event_espresso'
207
+				),
208
+				'Messages_Admin_Page::get_contexts_for_message_types_select_input()'
209
+			),
210
+			'4.9.9.rc.014'
211
+		);
212
+
213
+		$contexts = array();
214
+		$active_message_contexts = EEM_Message::instance()->get_all(array('group_by' => 'MSG_context'));
215
+		foreach ($active_message_contexts as $active_message) {
216
+			if ($active_message instanceof EE_Message) {
217
+				$message_type = $active_message->message_type_object();
218
+				if ($message_type instanceof EE_message_type) {
219
+					$message_type_contexts = $message_type->get_contexts();
220
+					foreach ($message_type_contexts as $context => $context_details) {
221
+						$contexts[ $context ] = $context_details['label'];
222
+					}
223
+				}
224
+			}
225
+		}
226
+
227
+		return $contexts;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Generate select input with provided messenger options array.
233
+	 *
234
+	 * @param array $messenger_options Array of messengers indexed by messenger slug and values are the messenger
235
+	 *                                 labels.
236
+	 * @return string
237
+	 * @throws EE_Error
238
+	 */
239
+	public function get_messengers_select_input($messenger_options)
240
+	{
241
+		// if empty or just one value then just return an empty string
242
+		if (empty($messenger_options)
243
+			|| ! is_array($messenger_options)
244
+			|| count($messenger_options) === 1
245
+		) {
246
+			return '';
247
+		}
248
+		// merge in default
249
+		$messenger_options = array_merge(
250
+			array('none_selected' => esc_html__('Show All Messengers', 'event_espresso')),
251
+			$messenger_options
252
+		);
253
+		$input = new EE_Select_Input(
254
+			$messenger_options,
255
+			array(
256
+				'html_name'  => 'ee_messenger_filter_by',
257
+				'html_id'    => 'ee_messenger_filter_by',
258
+				'html_class' => 'wide',
259
+				'default'    => isset($this->_req_data['ee_messenger_filter_by'])
260
+					? sanitize_title($this->_req_data['ee_messenger_filter_by'])
261
+					: 'none_selected',
262
+			)
263
+		);
264
+
265
+		return $input->get_html_for_input();
266
+	}
267
+
268
+
269
+	/**
270
+	 * Generate select input with provided message type options array.
271
+	 *
272
+	 * @param array $message_type_options Array of message types indexed by message type slug, and values are the
273
+	 *                                    message type labels
274
+	 * @return string
275
+	 * @throws EE_Error
276
+	 */
277
+	public function get_message_types_select_input($message_type_options)
278
+	{
279
+		// if empty or count of options is 1 then just return an empty string
280
+		if (empty($message_type_options)
281
+			|| ! is_array($message_type_options)
282
+			|| count($message_type_options) === 1
283
+		) {
284
+			return '';
285
+		}
286
+		// merge in default
287
+		$message_type_options = array_merge(
288
+			array('none_selected' => esc_html__('Show All Message Types', 'event_espresso')),
289
+			$message_type_options
290
+		);
291
+		$input = new EE_Select_Input(
292
+			$message_type_options,
293
+			array(
294
+				'html_name'  => 'ee_message_type_filter_by',
295
+				'html_id'    => 'ee_message_type_filter_by',
296
+				'html_class' => 'wide',
297
+				'default'    => isset($this->_req_data['ee_message_type_filter_by'])
298
+					? sanitize_title($this->_req_data['ee_message_type_filter_by'])
299
+					: 'none_selected',
300
+			)
301
+		);
302
+
303
+		return $input->get_html_for_input();
304
+	}
305
+
306
+
307
+	/**
308
+	 * Generate select input with provide message type contexts array.
309
+	 *
310
+	 * @param array $context_options Array of message type contexts indexed by context slug, and values are the
311
+	 *                               context label.
312
+	 * @return string
313
+	 * @throws EE_Error
314
+	 */
315
+	public function get_contexts_for_message_types_select_input($context_options)
316
+	{
317
+		// if empty or count of options is one then just return empty string
318
+		if (empty($context_options)
319
+			|| ! is_array($context_options)
320
+			|| count($context_options) === 1
321
+		) {
322
+			return '';
323
+		}
324
+		// merge in default
325
+		$context_options = array_merge(
326
+			array('none_selected' => esc_html__('Show all Contexts', 'event_espresso')),
327
+			$context_options
328
+		);
329
+		$input = new EE_Select_Input(
330
+			$context_options,
331
+			array(
332
+				'html_name'  => 'ee_context_filter_by',
333
+				'html_id'    => 'ee_context_filter_by',
334
+				'html_class' => 'wide',
335
+				'default'    => isset($this->_req_data['ee_context_filter_by'])
336
+					? sanitize_title($this->_req_data['ee_context_filter_by'])
337
+					: 'none_selected',
338
+			)
339
+		);
340
+
341
+		return $input->get_html_for_input();
342
+	}
343
+
344
+
345
+	protected function _ajax_hooks()
346
+	{
347
+		add_action('wp_ajax_activate_messenger', array($this, 'activate_messenger_toggle'));
348
+		add_action('wp_ajax_activate_mt', array($this, 'activate_mt_toggle'));
349
+		add_action('wp_ajax_ee_msgs_save_settings', array($this, 'save_settings'));
350
+		add_action('wp_ajax_ee_msgs_update_mt_form', array($this, 'update_mt_form'));
351
+		add_action('wp_ajax_switch_template_pack', array($this, 'switch_template_pack'));
352
+		add_action('wp_ajax_toggle_context_template', array($this, 'toggle_context_template'));
353
+	}
354
+
355
+
356
+	protected function _define_page_props()
357
+	{
358
+		$this->_admin_page_title = $this->page_label;
359
+		$this->_labels = array(
360
+			'buttons'    => array(
361
+				'add'    => esc_html__('Add New Message Template', 'event_espresso'),
362
+				'edit'   => esc_html__('Edit Message Template', 'event_espresso'),
363
+				'delete' => esc_html__('Delete Message Template', 'event_espresso'),
364
+			),
365
+			'publishbox' => esc_html__('Update Actions', 'event_espresso'),
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 *        an array for storing key => value pairs of request actions and their corresponding methods
372
+	 *
373
+	 * @access protected
374
+	 * @return void
375
+	 */
376
+	protected function _set_page_routes()
377
+	{
378
+		$grp_id = ! empty($this->_req_data['GRP_ID']) && ! is_array($this->_req_data['GRP_ID'])
379
+			? $this->_req_data['GRP_ID']
380
+			: 0;
381
+		$grp_id = empty($grp_id) && ! empty($this->_req_data['id'])
382
+			? $this->_req_data['id']
383
+			: $grp_id;
384
+		$msg_id = ! empty($this->_req_data['MSG_ID']) && ! is_array($this->_req_data['MSG_ID'])
385
+			? $this->_req_data['MSG_ID']
386
+			: 0;
387
+
388
+		$this->_page_routes = array(
389
+			'default'                          => array(
390
+				'func'       => '_message_queue_list_table',
391
+				'capability' => 'ee_read_global_messages',
392
+			),
393
+			'global_mtps'                      => array(
394
+				'func'       => '_ee_default_messages_overview_list_table',
395
+				'capability' => 'ee_read_global_messages',
396
+			),
397
+			'custom_mtps'                      => array(
398
+				'func'       => '_custom_mtps_preview',
399
+				'capability' => 'ee_read_messages',
400
+			),
401
+			'add_new_message_template'         => array(
402
+				'func'       => '_add_message_template',
403
+				'capability' => 'ee_edit_messages',
404
+				'noheader'   => true,
405
+			),
406
+			'edit_message_template'            => array(
407
+				'func'       => '_edit_message_template',
408
+				'capability' => 'ee_edit_message',
409
+				'obj_id'     => $grp_id,
410
+			),
411
+			'preview_message'                  => array(
412
+				'func'               => '_preview_message',
413
+				'capability'         => 'ee_read_message',
414
+				'obj_id'             => $grp_id,
415
+				'noheader'           => true,
416
+				'headers_sent_route' => 'display_preview_message',
417
+			),
418
+			'display_preview_message'          => array(
419
+				'func'       => '_display_preview_message',
420
+				'capability' => 'ee_read_message',
421
+				'obj_id'     => $grp_id,
422
+			),
423
+			'insert_message_template'          => array(
424
+				'func'       => '_insert_or_update_message_template',
425
+				'capability' => 'ee_edit_messages',
426
+				'args'       => array('new_template' => true),
427
+				'noheader'   => true,
428
+			),
429
+			'update_message_template'          => array(
430
+				'func'       => '_insert_or_update_message_template',
431
+				'capability' => 'ee_edit_message',
432
+				'obj_id'     => $grp_id,
433
+				'args'       => array('new_template' => false),
434
+				'noheader'   => true,
435
+			),
436
+			'trash_message_template'           => array(
437
+				'func'       => '_trash_or_restore_message_template',
438
+				'capability' => 'ee_delete_message',
439
+				'obj_id'     => $grp_id,
440
+				'args'       => array('trash' => true, 'all' => true),
441
+				'noheader'   => true,
442
+			),
443
+			'trash_message_template_context'   => array(
444
+				'func'       => '_trash_or_restore_message_template',
445
+				'capability' => 'ee_delete_message',
446
+				'obj_id'     => $grp_id,
447
+				'args'       => array('trash' => true),
448
+				'noheader'   => true,
449
+			),
450
+			'restore_message_template'         => array(
451
+				'func'       => '_trash_or_restore_message_template',
452
+				'capability' => 'ee_delete_message',
453
+				'obj_id'     => $grp_id,
454
+				'args'       => array('trash' => false, 'all' => true),
455
+				'noheader'   => true,
456
+			),
457
+			'restore_message_template_context' => array(
458
+				'func'       => '_trash_or_restore_message_template',
459
+				'capability' => 'ee_delete_message',
460
+				'obj_id'     => $grp_id,
461
+				'args'       => array('trash' => false),
462
+				'noheader'   => true,
463
+			),
464
+			'delete_message_template'          => array(
465
+				'func'       => '_delete_message_template',
466
+				'capability' => 'ee_delete_message',
467
+				'obj_id'     => $grp_id,
468
+				'noheader'   => true,
469
+			),
470
+			'reset_to_default'                 => array(
471
+				'func'       => '_reset_to_default_template',
472
+				'capability' => 'ee_edit_message',
473
+				'obj_id'     => $grp_id,
474
+				'noheader'   => true,
475
+			),
476
+			'settings'                         => array(
477
+				'func'       => '_settings',
478
+				'capability' => 'manage_options',
479
+			),
480
+			'update_global_settings'           => array(
481
+				'func'       => '_update_global_settings',
482
+				'capability' => 'manage_options',
483
+				'noheader'   => true,
484
+			),
485
+			'generate_now'                     => array(
486
+				'func'       => '_generate_now',
487
+				'capability' => 'ee_send_message',
488
+				'noheader'   => true,
489
+			),
490
+			'generate_and_send_now'            => array(
491
+				'func'       => '_generate_and_send_now',
492
+				'capability' => 'ee_send_message',
493
+				'noheader'   => true,
494
+			),
495
+			'queue_for_resending'              => array(
496
+				'func'       => '_queue_for_resending',
497
+				'capability' => 'ee_send_message',
498
+				'noheader'   => true,
499
+			),
500
+			'send_now'                         => array(
501
+				'func'       => '_send_now',
502
+				'capability' => 'ee_send_message',
503
+				'noheader'   => true,
504
+			),
505
+			'delete_ee_message'                => array(
506
+				'func'       => '_delete_ee_messages',
507
+				'capability' => 'ee_delete_messages',
508
+				'noheader'   => true,
509
+			),
510
+			'delete_ee_messages'               => array(
511
+				'func'       => '_delete_ee_messages',
512
+				'capability' => 'ee_delete_messages',
513
+				'noheader'   => true,
514
+				'obj_id'     => $msg_id,
515
+			),
516
+		);
517
+	}
518
+
519
+
520
+	protected function _set_page_config()
521
+	{
522
+		$this->_page_config = array(
523
+			'default'                  => array(
524
+				'nav'           => array(
525
+					'label' => esc_html__('Message Activity', 'event_espresso'),
526
+					'order' => 10,
527
+				),
528
+				'list_table'    => 'EE_Message_List_Table',
529
+				// 'qtips' => array( 'EE_Message_List_Table_Tips' ),
530
+				'require_nonce' => false,
531
+			),
532
+			'global_mtps'              => array(
533
+				'nav'           => array(
534
+					'label' => esc_html__('Default Message Templates', 'event_espresso'),
535
+					'order' => 20,
536
+				),
537
+				'list_table'    => 'Messages_Template_List_Table',
538
+				'help_tabs'     => array(
539
+					'messages_overview_help_tab'                                => array(
540
+						'title'    => esc_html__('Messages Overview', 'event_espresso'),
541
+						'filename' => 'messages_overview',
542
+					),
543
+					'messages_overview_messages_table_column_headings_help_tab' => array(
544
+						'title'    => esc_html__('Messages Table Column Headings', 'event_espresso'),
545
+						'filename' => 'messages_overview_table_column_headings',
546
+					),
547
+					'messages_overview_messages_filters_help_tab'               => array(
548
+						'title'    => esc_html__('Message Filters', 'event_espresso'),
549
+						'filename' => 'messages_overview_filters',
550
+					),
551
+					'messages_overview_messages_views_help_tab'                 => array(
552
+						'title'    => esc_html__('Message Views', 'event_espresso'),
553
+						'filename' => 'messages_overview_views',
554
+					),
555
+					'message_overview_message_types_help_tab'                   => array(
556
+						'title'    => esc_html__('Message Types', 'event_espresso'),
557
+						'filename' => 'messages_overview_types',
558
+					),
559
+					'messages_overview_messengers_help_tab'                     => array(
560
+						'title'    => esc_html__('Messengers', 'event_espresso'),
561
+						'filename' => 'messages_overview_messengers',
562
+					),
563
+				),
564
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
565
+				// 'help_tour'     => array('Messages_Overview_Help_Tour'),
566
+				'require_nonce' => false,
567
+			),
568
+			'custom_mtps'              => array(
569
+				'nav'           => array(
570
+					'label' => esc_html__('Custom Message Templates', 'event_espresso'),
571
+					'order' => 30,
572
+				),
573
+				'help_tabs'     => array(),
574
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
575
+				// 'help_tour'     => array(),
576
+				'require_nonce' => false,
577
+			),
578
+			'add_new_message_template' => array(
579
+				'nav'           => array(
580
+					'label'      => esc_html__('Add New Message Templates', 'event_espresso'),
581
+					'order'      => 5,
582
+					'persistent' => false,
583
+				),
584
+				'require_nonce' => false,
585
+			),
586
+			'edit_message_template'    => array(
587
+				'labels'        => array(
588
+					'buttons'    => array(
589
+						'reset' => esc_html__('Reset Templates', 'event_espresso'),
590
+					),
591
+					'publishbox' => esc_html__('Update Actions', 'event_espresso'),
592
+				),
593
+				'nav'           => array(
594
+					'label'      => esc_html__('Edit Message Templates', 'event_espresso'),
595
+					'order'      => 5,
596
+					'persistent' => false,
597
+					'url'        => '',
598
+				),
599
+				'metaboxes'     => array('_publish_post_box', '_register_edit_meta_boxes'),
600
+				'has_metaboxes' => true,
601
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
602
+				// 'help_tour'     => array('Message_Templates_Edit_Help_Tour'),
603
+				'help_tabs'     => array(
604
+					'edit_message_template'            => array(
605
+						'title'    => esc_html__('Message Template Editor', 'event_espresso'),
606
+						'callback' => 'edit_message_template_help_tab',
607
+					),
608
+					'message_templates_help_tab'       => array(
609
+						'title'    => esc_html__('Message Templates', 'event_espresso'),
610
+						'filename' => 'messages_templates',
611
+					),
612
+					'message_template_shortcodes'      => array(
613
+						'title'    => esc_html__('Message Shortcodes', 'event_espresso'),
614
+						'callback' => 'message_template_shortcodes_help_tab',
615
+					),
616
+					'message_preview_help_tab'         => array(
617
+						'title'    => esc_html__('Message Preview', 'event_espresso'),
618
+						'filename' => 'messages_preview',
619
+					),
620
+					'messages_overview_other_help_tab' => array(
621
+						'title'    => esc_html__('Messages Other', 'event_espresso'),
622
+						'filename' => 'messages_overview_other',
623
+					),
624
+				),
625
+				'require_nonce' => false,
626
+			),
627
+			'display_preview_message'  => array(
628
+				'nav'           => array(
629
+					'label'      => esc_html__('Message Preview', 'event_espresso'),
630
+					'order'      => 5,
631
+					'url'        => '',
632
+					'persistent' => false,
633
+				),
634
+				'help_tabs'     => array(
635
+					'preview_message' => array(
636
+						'title'    => esc_html__('About Previews', 'event_espresso'),
637
+						'callback' => 'preview_message_help_tab',
638
+					),
639
+				),
640
+				'require_nonce' => false,
641
+			),
642
+			'settings'                 => array(
643
+				'nav'           => array(
644
+					'label' => esc_html__('Settings', 'event_espresso'),
645
+					'order' => 40,
646
+				),
647
+				'metaboxes'     => array('_messages_settings_metaboxes'),
648
+				'help_tabs'     => array(
649
+					'messages_settings_help_tab'               => array(
650
+						'title'    => esc_html__('Messages Settings', 'event_espresso'),
651
+						'filename' => 'messages_settings',
652
+					),
653
+					'messages_settings_message_types_help_tab' => array(
654
+						'title'    => esc_html__('Activating / Deactivating Message Types', 'event_espresso'),
655
+						'filename' => 'messages_settings_message_types',
656
+					),
657
+					'messages_settings_messengers_help_tab'    => array(
658
+						'title'    => esc_html__('Activating / Deactivating Messengers', 'event_espresso'),
659
+						'filename' => 'messages_settings_messengers',
660
+					),
661
+				),
662
+				// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
663
+				// 'help_tour'     => array('Messages_Settings_Help_Tour'),
664
+				'require_nonce' => false,
665
+			),
666
+		);
667
+	}
668
+
669
+
670
+	protected function _add_screen_options()
671
+	{
672
+		// todo
673
+	}
674
+
675
+
676
+	protected function _add_screen_options_global_mtps()
677
+	{
678
+		/**
679
+		 * Note: the reason for the value swap here on $this->_admin_page_title is because $this->_per_page_screen_options
680
+		 * uses the $_admin_page_title property and we want different outputs in the different spots.
681
+		 */
682
+		$page_title = $this->_admin_page_title;
683
+		$this->_admin_page_title = esc_html__('Global Message Templates', 'event_espresso');
684
+		$this->_per_page_screen_option();
685
+		$this->_admin_page_title = $page_title;
686
+	}
687
+
688
+
689
+	protected function _add_screen_options_default()
690
+	{
691
+		$this->_admin_page_title = esc_html__('Message Activity', 'event_espresso');
692
+		$this->_per_page_screen_option();
693
+	}
694
+
695
+
696
+	// none of the below group are currently used for Messages
697
+	protected function _add_feature_pointers()
698
+	{
699
+	}
700
+
701
+	public function admin_init()
702
+	{
703
+	}
704
+
705
+	public function admin_notices()
706
+	{
707
+	}
708
+
709
+	public function admin_footer_scripts()
710
+	{
711
+	}
712
+
713
+
714
+	public function messages_help_tab()
715
+	{
716
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_help_tab.template.php');
717
+	}
718
+
719
+
720
+	public function messengers_help_tab()
721
+	{
722
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messenger_help_tab.template.php');
723
+	}
724
+
725
+
726
+	public function message_types_help_tab()
727
+	{
728
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_type_help_tab.template.php');
729
+	}
730
+
731
+
732
+	public function messages_overview_help_tab()
733
+	{
734
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_overview_help_tab.template.php');
735
+	}
736
+
737
+
738
+	public function message_templates_help_tab()
739
+	{
740
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_message_templates_help_tab.template.php');
741
+	}
742
+
743
+
744
+	public function edit_message_template_help_tab()
745
+	{
746
+		$args['img1'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/editor.png' . '" alt="'
747
+						. esc_attr__('Editor Title', 'event_espresso')
748
+						. '" />';
749
+		$args['img2'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/switch-context.png' . '" alt="'
750
+						. esc_attr__('Context Switcher and Preview', 'event_espresso')
751
+						. '" />';
752
+		$args['img3'] = '<img class="left" src="' . EE_MSG_ASSETS_URL . 'images/form-fields.png' . '" alt="'
753
+						. esc_attr__('Message Template Form Fields', 'event_espresso')
754
+						. '" />';
755
+		$args['img4'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/shortcodes-metabox.png' . '" alt="'
756
+						. esc_attr__('Shortcodes Metabox', 'event_espresso')
757
+						. '" />';
758
+		$args['img5'] = '<img class="right" src="' . EE_MSG_ASSETS_URL . 'images/publish-meta-box.png' . '" alt="'
759
+						. esc_attr__('Publish Metabox', 'event_espresso')
760
+						. '" />';
761
+		EEH_Template::display_template(
762
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_templates_editor_help_tab.template.php',
763
+			$args
764
+		);
765
+	}
766
+
767
+
768
+	public function message_template_shortcodes_help_tab()
769
+	{
770
+		$this->_set_shortcodes();
771
+		$args['shortcodes'] = $this->_shortcodes;
772
+		EEH_Template::display_template(
773
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_shortcodes_help_tab.template.php',
774
+			$args
775
+		);
776
+	}
777
+
778
+
779
+	public function preview_message_help_tab()
780
+	{
781
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_preview_help_tab.template.php');
782
+	}
783
+
784
+
785
+	public function settings_help_tab()
786
+	{
787
+		$args['img1'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-active.png'
788
+						. '" alt="' . esc_attr__('Active Email Tab', 'event_espresso') . '" />';
789
+		$args['img2'] = '<img class="inline-text" src="' . EE_MSG_ASSETS_URL . 'images/email-tab-inactive.png'
790
+						. '" alt="' . esc_attr__('Inactive Email Tab', 'event_espresso') . '" />';
791
+		$args['img3'] = '<div class="switch">'
792
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
793
+						. ' type="checkbox" checked="checked">'
794
+						. '<label for="ee-on-off-toggle-on"></label>'
795
+						. '</div>';
796
+		$args['img4'] = '<div class="switch">'
797
+						. '<input class="ee-on-off-toggle ee-toggle-round-flat"'
798
+						. ' type="checkbox">'
799
+						. '<label for="ee-on-off-toggle-on"></label>'
800
+						. '</div>';
801
+		EEH_Template::display_template(EE_MSG_TEMPLATE_PATH . 'ee_msg_messages_settings_help_tab.template.php', $args);
802
+	}
803
+
804
+
805
+	public function load_scripts_styles()
806
+	{
807
+		wp_register_style('espresso_ee_msg', EE_MSG_ASSETS_URL . 'ee_message_admin.css', EVENT_ESPRESSO_VERSION);
808
+		wp_enqueue_style('espresso_ee_msg');
809
+
810
+		wp_register_script(
811
+			'ee-messages-settings',
812
+			EE_MSG_ASSETS_URL . 'ee-messages-settings.js',
813
+			array('jquery-ui-droppable', 'ee-serialize-full-array'),
814
+			EVENT_ESPRESSO_VERSION,
815
+			true
816
+		);
817
+		wp_register_script(
818
+			'ee-msg-list-table-js',
819
+			EE_MSG_ASSETS_URL . 'ee_message_admin_list_table.js',
820
+			array('ee-dialog'),
821
+			EVENT_ESPRESSO_VERSION
822
+		);
823
+	}
824
+
825
+
826
+	public function load_scripts_styles_default()
827
+	{
828
+		wp_enqueue_script('ee-msg-list-table-js');
829
+	}
830
+
831
+
832
+	public function wp_editor_css($mce_css)
833
+	{
834
+		// if we're on the edit_message_template route
835
+		if ($this->_req_action === 'edit_message_template' && $this->_active_messenger instanceof EE_messenger) {
836
+			$message_type_name = $this->_active_message_type_name;
837
+
838
+			// we're going to REPLACE the existing mce css
839
+			// we need to get the css file location from the active messenger
840
+			$mce_css = $this->_active_messenger->get_variation(
841
+				$this->_template_pack,
842
+				$message_type_name,
843
+				true,
844
+				'wpeditor',
845
+				$this->_variation
846
+			);
847
+		}
848
+
849
+		return $mce_css;
850
+	}
851
+
852
+
853
+	public function load_scripts_styles_edit_message_template()
854
+	{
855
+
856
+		$this->_set_shortcodes();
857
+
858
+		EE_Registry::$i18n_js_strings['confirm_default_reset'] = sprintf(
859
+			esc_html__(
860
+				'Are you sure you want to reset the %s %s message templates?  Remember continuing will reset the templates for all contexts in this messenger and message type group.',
861
+				'event_espresso'
862
+			),
863
+			$this->_message_template_group->messenger_obj()->label['singular'],
864
+			$this->_message_template_group->message_type_obj()->label['singular']
865
+		);
866
+		EE_Registry::$i18n_js_strings['confirm_switch_template_pack'] = esc_html__(
867
+			'Switching the template pack for a messages template will reset the content for the template so the new layout is loaded.  Any custom content in the existing template will be lost. Are you sure you wish to do this?',
868
+			'event_espresso'
869
+		);
870
+		EE_Registry::$i18n_js_strings['server_error'] = esc_html__(
871
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
872
+			'event_espresso'
873
+		);
874
+
875
+		wp_register_script(
876
+			'ee_msgs_edit_js',
877
+			EE_MSG_ASSETS_URL . 'ee_message_editor.js',
878
+			array('jquery'),
879
+			EVENT_ESPRESSO_VERSION
880
+		);
881
+
882
+		wp_enqueue_script('ee_admin_js');
883
+		wp_enqueue_script('ee_msgs_edit_js');
884
+
885
+		// add in special css for tiny_mce
886
+		add_filter('mce_css', array($this, 'wp_editor_css'));
887
+	}
888
+
889
+
890
+	public function load_scripts_styles_display_preview_message()
891
+	{
892
+
893
+		$this->_set_message_template_group();
894
+
895
+		if (isset($this->_req_data['messenger'])) {
896
+			$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
897
+				$this->_req_data['messenger']
898
+			);
899
+		}
900
+
901
+		$message_type_name = isset($this->_req_data['message_type']) ? $this->_req_data['message_type'] : '';
902
+
903
+
904
+		wp_enqueue_style(
905
+			'espresso_preview_css',
906
+			$this->_active_messenger->get_variation(
907
+				$this->_template_pack,
908
+				$message_type_name,
909
+				true,
910
+				'preview',
911
+				$this->_variation
912
+			)
913
+		);
914
+	}
915
+
916
+
917
+	public function load_scripts_styles_settings()
918
+	{
919
+		wp_register_style(
920
+			'ee-message-settings',
921
+			EE_MSG_ASSETS_URL . 'ee_message_settings.css',
922
+			array(),
923
+			EVENT_ESPRESSO_VERSION
924
+		);
925
+		wp_enqueue_style('ee-text-links');
926
+		wp_enqueue_style('ee-message-settings');
927
+		wp_enqueue_script('ee-messages-settings');
928
+	}
929
+
930
+
931
+	/**
932
+	 * set views array for List Table
933
+	 */
934
+	public function _set_list_table_views_global_mtps()
935
+	{
936
+		$this->_views = array(
937
+			'in_use' => array(
938
+				'slug'  => 'in_use',
939
+				'label' => esc_html__('In Use', 'event_espresso'),
940
+				'count' => 0,
941
+			),
942
+		);
943
+	}
944
+
945
+
946
+	/**
947
+	 * Set views array for the Custom Template List Table
948
+	 */
949
+	public function _set_list_table_views_custom_mtps()
950
+	{
951
+		$this->_set_list_table_views_global_mtps();
952
+		$this->_views['in_use']['bulk_action'] = array(
953
+			'trash_message_template' => esc_html__('Move to Trash', 'event_espresso'),
954
+		);
955
+	}
956
+
957
+
958
+	/**
959
+	 * set views array for message queue list table
960
+	 *
961
+	 * @throws InvalidDataTypeException
962
+	 * @throws InvalidInterfaceException
963
+	 * @throws InvalidArgumentException
964
+	 * @throws EE_Error
965
+	 * @throws ReflectionException
966
+	 */
967
+	public function _set_list_table_views_default()
968
+	{
969
+		EE_Registry::instance()->load_helper('Template');
970
+
971
+		$common_bulk_actions = EE_Registry::instance()->CAP->current_user_can(
972
+			'ee_send_message',
973
+			'message_list_table_bulk_actions'
974
+		)
975
+			? array(
976
+				'generate_now'          => esc_html__('Generate Now', 'event_espresso'),
977
+				'generate_and_send_now' => esc_html__('Generate and Send Now', 'event_espresso'),
978
+				'queue_for_resending'   => esc_html__('Queue for Resending', 'event_espresso'),
979
+				'send_now'              => esc_html__('Send Now', 'event_espresso'),
980
+			)
981
+			: array();
982
+
983
+		$delete_bulk_action = EE_Registry::instance()->CAP->current_user_can(
984
+			'ee_delete_messages',
985
+			'message_list_table_bulk_actions'
986
+		)
987
+			? array('delete_ee_messages' => esc_html__('Delete Messages', 'event_espresso'))
988
+			: array();
989
+
990
+
991
+		$this->_views = array(
992
+			'all' => array(
993
+				'slug'        => 'all',
994
+				'label'       => esc_html__('All', 'event_espresso'),
995
+				'count'       => 0,
996
+				'bulk_action' => array_merge($common_bulk_actions, $delete_bulk_action),
997
+			),
998
+		);
999
+
1000
+
1001
+		foreach (EEM_Message::instance()->all_statuses() as $status) {
1002
+			if ($status === EEM_Message::status_debug_only && ! EEM_Message::debug()) {
1003
+				continue;
1004
+			}
1005
+			$status_bulk_actions = $common_bulk_actions;
1006
+			// unset bulk actions not applying to status
1007
+			if (! empty($status_bulk_actions)) {
1008
+				switch ($status) {
1009
+					case EEM_Message::status_idle:
1010
+					case EEM_Message::status_resend:
1011
+						$status_bulk_actions['send_now'] = $common_bulk_actions['send_now'];
1012
+						break;
1013
+
1014
+					case EEM_Message::status_failed:
1015
+					case EEM_Message::status_debug_only:
1016
+					case EEM_Message::status_messenger_executing:
1017
+						$status_bulk_actions = array();
1018
+						break;
1019
+
1020
+					case EEM_Message::status_incomplete:
1021
+						unset($status_bulk_actions['queue_for_resending'], $status_bulk_actions['send_now']);
1022
+						break;
1023
+
1024
+					case EEM_Message::status_retry:
1025
+					case EEM_Message::status_sent:
1026
+						unset($status_bulk_actions['generate_now'], $status_bulk_actions['generate_and_send_now']);
1027
+						break;
1028
+				}
1029
+			}
1030
+
1031
+			// skip adding messenger executing status to views because it will be included with the Failed view.
1032
+			if ($status === EEM_Message::status_messenger_executing) {
1033
+				continue;
1034
+			}
1035
+
1036
+			$this->_views[ strtolower($status) ] = array(
1037
+				'slug'        => strtolower($status),
1038
+				'label'       => EEH_Template::pretty_status($status, false, 'sentence'),
1039
+				'count'       => 0,
1040
+				'bulk_action' => array_merge($status_bulk_actions, $delete_bulk_action),
1041
+			);
1042
+		}
1043
+	}
1044
+
1045
+
1046
+	protected function _ee_default_messages_overview_list_table()
1047
+	{
1048
+		$this->_admin_page_title = esc_html__('Default Message Templates', 'event_espresso');
1049
+		$this->display_admin_list_table_page_with_no_sidebar();
1050
+	}
1051
+
1052
+
1053
+	protected function _message_queue_list_table()
1054
+	{
1055
+		$this->_search_btn_label = esc_html__('Message Activity', 'event_espresso');
1056
+		$this->_template_args['per_column'] = 6;
1057
+		$this->_template_args['after_list_table'] = $this->_display_legend($this->_message_legend_items());
1058
+		$this->_template_args['before_list_table'] = '<h3>'
1059
+													 . EEM_Message::instance()->get_pretty_label_for_results()
1060
+													 . '</h3>';
1061
+		$this->display_admin_list_table_page_with_no_sidebar();
1062
+	}
1063
+
1064
+
1065
+	protected function _message_legend_items()
1066
+	{
1067
+
1068
+		$action_css_classes = EEH_MSG_Template::get_message_action_icons();
1069
+		$action_items = array();
1070
+
1071
+		foreach ($action_css_classes as $action_item => $action_details) {
1072
+			if ($action_item === 'see_notifications_for') {
1073
+				continue;
1074
+			}
1075
+			$action_items[ $action_item ] = array(
1076
+				'class' => $action_details['css_class'],
1077
+				'desc'  => $action_details['label'],
1078
+			);
1079
+		}
1080
+
1081
+		/** @type array $status_items status legend setup */
1082
+		$status_items = array(
1083
+			'sent_status'                => array(
1084
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_sent,
1085
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_sent, false, 'sentence'),
1086
+			),
1087
+			'idle_status'                => array(
1088
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_idle,
1089
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_idle, false, 'sentence'),
1090
+			),
1091
+			'failed_status'              => array(
1092
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_failed,
1093
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_failed, false, 'sentence'),
1094
+			),
1095
+			'messenger_executing_status' => array(
1096
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_messenger_executing,
1097
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_messenger_executing, false, 'sentence'),
1098
+			),
1099
+			'resend_status'              => array(
1100
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_resend,
1101
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_resend, false, 'sentence'),
1102
+			),
1103
+			'incomplete_status'          => array(
1104
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_incomplete,
1105
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_incomplete, false, 'sentence'),
1106
+			),
1107
+			'retry_status'               => array(
1108
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_retry,
1109
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_retry, false, 'sentence'),
1110
+			),
1111
+		);
1112
+		if (EEM_Message::debug()) {
1113
+			$status_items['debug_only_status'] = array(
1114
+				'class' => 'ee-status-legend ee-status-legend-' . EEM_Message::status_debug_only,
1115
+				'desc'  => EEH_Template::pretty_status(EEM_Message::status_debug_only, false, 'sentence'),
1116
+			);
1117
+		}
1118
+
1119
+		return array_merge($action_items, $status_items);
1120
+	}
1121
+
1122
+
1123
+	protected function _custom_mtps_preview()
1124
+	{
1125
+		$this->_admin_page_title = esc_html__('Custom Message Templates (Preview)', 'event_espresso');
1126
+		$this->_template_args['preview_img'] = '<img src="' . EE_MSG_ASSETS_URL . 'images/custom_mtps_preview.png"'
1127
+											   . ' alt="' . esc_attr__(
1128
+												   'Preview Custom Message Templates screenshot',
1129
+												   'event_espresso'
1130
+											   ) . '" />';
1131
+		$this->_template_args['preview_text'] = '<strong>'
1132
+												. esc_html__(
1133
+													'Custom Message Templates is a feature that is only available in the premium version of Event Espresso 4 which is available with a support license purchase on EventEspresso.com. With the Custom Message Templates feature, you are able to create custom message templates and assign them on a per-event basis.',
1134
+													'event_espresso'
1135
+												)
1136
+												. '</strong>';
1137
+
1138
+		$this->display_admin_caf_preview_page('custom_message_types', false);
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * get_message_templates
1144
+	 * This gets all the message templates for listing on the overview list.
1145
+	 *
1146
+	 * @access public
1147
+	 * @param int    $perpage the amount of templates groups to show per page
1148
+	 * @param string $type    the current _view we're getting templates for
1149
+	 * @param bool   $count   return count?
1150
+	 * @param bool   $all     disregard any paging info (get all data);
1151
+	 * @param bool   $global  whether to return just global (true) or custom templates (false)
1152
+	 * @return array
1153
+	 * @throws EE_Error
1154
+	 * @throws InvalidArgumentException
1155
+	 * @throws InvalidDataTypeException
1156
+	 * @throws InvalidInterfaceException
1157
+	 */
1158
+	public function get_message_templates(
1159
+		$perpage = 10,
1160
+		$type = 'in_use',
1161
+		$count = false,
1162
+		$all = false,
1163
+		$global = true
1164
+	) {
1165
+
1166
+		$MTP = EEM_Message_Template_Group::instance();
1167
+
1168
+		$this->_req_data['orderby'] = empty($this->_req_data['orderby']) ? 'GRP_ID' : $this->_req_data['orderby'];
1169
+		$orderby = $this->_req_data['orderby'];
1170
+
1171
+		$order = (isset($this->_req_data['order']) && ! empty($this->_req_data['order']))
1172
+			? $this->_req_data['order']
1173
+			: 'ASC';
1174
+
1175
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1176
+			? $this->_req_data['paged']
1177
+			: 1;
1178
+		$per_page = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1179
+			? $this->_req_data['perpage']
1180
+			: $perpage;
1181
+
1182
+		$offset = ($current_page - 1) * $per_page;
1183
+		$limit = $all ? null : array($offset, $per_page);
1184
+
1185
+
1186
+		// options will match what is in the _views array property
1187
+		switch ($type) {
1188
+			case 'in_use':
1189
+				$templates = $MTP->get_all_active_message_templates($orderby, $order, $limit, $count, $global, true);
1190
+				break;
1191
+			default:
1192
+				$templates = $MTP->get_all_trashed_grouped_message_templates($orderby, $order, $limit, $count, $global);
1193
+		}
1194
+
1195
+		return $templates;
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * filters etc might need a list of installed message_types
1201
+	 *
1202
+	 * @return array an array of message type objects
1203
+	 */
1204
+	public function get_installed_message_types()
1205
+	{
1206
+		$installed_message_types = $this->_message_resource_manager->installed_message_types();
1207
+		$installed = array();
1208
+
1209
+		foreach ($installed_message_types as $message_type) {
1210
+			$installed[ $message_type->name ] = $message_type;
1211
+		}
1212
+
1213
+		return $installed;
1214
+	}
1215
+
1216
+
1217
+	/**
1218
+	 * _add_message_template
1219
+	 *
1220
+	 * This is used when creating a custom template. All Custom Templates start based off another template.
1221
+	 *
1222
+	 * @param string $message_type
1223
+	 * @param string $messenger
1224
+	 * @param string $GRP_ID
1225
+	 *
1226
+	 * @throws EE_error
1227
+	 */
1228
+	protected function _add_message_template($message_type = '', $messenger = '', $GRP_ID = '')
1229
+	{
1230
+		// set values override any request data
1231
+		$message_type = ! empty($message_type) ? $message_type : '';
1232
+		$message_type = empty($message_type) && ! empty($this->_req_data['message_type'])
1233
+			? $this->_req_data['message_type']
1234
+			: $message_type;
1235
+
1236
+		$messenger = ! empty($messenger) ? $messenger : '';
1237
+		$messenger = empty($messenger) && ! empty($this->_req_data['messenger'])
1238
+			? $this->_req_data['messenger']
1239
+			: $messenger;
1240
+
1241
+		$GRP_ID = ! empty($GRP_ID) ? $GRP_ID : '';
1242
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : $GRP_ID;
1243
+
1244
+		// we need messenger and message type.  They should be coming from the event editor. If not here then return error
1245
+		if (empty($message_type) || empty($messenger)) {
1246
+			throw new EE_Error(
1247
+				esc_html__(
1248
+					'Sorry, but we can\'t create new templates because we\'re missing the messenger or message type',
1249
+					'event_espresso'
1250
+				)
1251
+			);
1252
+		}
1253
+
1254
+		// we need the GRP_ID for the template being used as the base for the new template
1255
+		if (empty($GRP_ID)) {
1256
+			throw new EE_Error(
1257
+				esc_html__(
1258
+					'In order to create a custom message template the GRP_ID of the template being used as a base is needed',
1259
+					'event_espresso'
1260
+				)
1261
+			);
1262
+		}
1263
+
1264
+		// let's just make sure the template gets generated!
1265
+
1266
+		// we need to reassign some variables for what the insert is expecting
1267
+		$this->_req_data['MTP_messenger'] = $messenger;
1268
+		$this->_req_data['MTP_message_type'] = $message_type;
1269
+		$this->_req_data['GRP_ID'] = $GRP_ID;
1270
+		$this->_insert_or_update_message_template(true);
1271
+	}
1272
+
1273
+
1274
+	/**
1275
+	 * public wrapper for the _add_message_template method
1276
+	 *
1277
+	 * @param string $message_type     message type slug
1278
+	 * @param string $messenger        messenger slug
1279
+	 * @param int    $GRP_ID           GRP_ID for the related message template group this new template will be based
1280
+	 *                                 off of.
1281
+	 * @throws EE_error
1282
+	 */
1283
+	public function add_message_template($message_type, $messenger, $GRP_ID)
1284
+	{
1285
+		$this->_add_message_template($message_type, $messenger, $GRP_ID);
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * _edit_message_template
1291
+	 *
1292
+	 * @access protected
1293
+	 * @return void
1294
+	 * @throws InvalidIdentifierException
1295
+	 * @throws DomainException
1296
+	 * @throws EE_Error
1297
+	 * @throws InvalidArgumentException
1298
+	 * @throws ReflectionException
1299
+	 * @throws InvalidDataTypeException
1300
+	 * @throws InvalidInterfaceException
1301
+	 */
1302
+	protected function _edit_message_template()
1303
+	{
1304
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1305
+		$template_fields = '';
1306
+		$sidebar_fields = '';
1307
+		// we filter the tinyMCE settings to remove the validation since message templates by their nature will not have
1308
+		// valid html in the templates.
1309
+		add_filter('tiny_mce_before_init', array($this, 'filter_tinymce_init'), 10, 2);
1310
+
1311
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
1312
+			? absint($this->_req_data['id'])
1313
+			: false;
1314
+
1315
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
1316
+		? absint($this->_req_data['evt_id'])
1317
+		: false;
1318
+
1319
+		$this->_set_shortcodes(); // this also sets the _message_template property.
1320
+		$message_template_group = $this->_message_template_group;
1321
+		$c_label = $message_template_group->context_label();
1322
+		$c_config = $message_template_group->contexts_config();
1323
+
1324
+		reset($c_config);
1325
+		$context = isset($this->_req_data['context']) && ! empty($this->_req_data['context'])
1326
+			? strtolower($this->_req_data['context'])
1327
+			: key($c_config);
1328
+
1329
+
1330
+		if (empty($GRP_ID)) {
1331
+			$action = 'insert_message_template';
1332
+			$edit_message_template_form_url = add_query_arg(
1333
+				array('action' => $action, 'noheader' => true),
1334
+				EE_MSG_ADMIN_URL
1335
+			);
1336
+		} else {
1337
+			$action = 'update_message_template';
1338
+			$edit_message_template_form_url = add_query_arg(
1339
+				array('action' => $action, 'noheader' => true),
1340
+				EE_MSG_ADMIN_URL
1341
+			);
1342
+		}
1343
+
1344
+		// set active messenger for this view
1345
+		$this->_active_messenger = $this->_message_resource_manager->get_active_messenger(
1346
+			$message_template_group->messenger()
1347
+		);
1348
+		$this->_active_message_type_name = $message_template_group->message_type();
1349
+
1350
+
1351
+		// Do we have any validation errors?
1352
+		$validators = $this->_get_transient();
1353
+		$v_fields = ! empty($validators) ? array_keys($validators) : array();
1354
+
1355
+
1356
+		// we need to assemble the title from Various details
1357
+		$context_label = sprintf(
1358
+			esc_html__('(%s %s)', 'event_espresso'),
1359
+			$c_config[ $context ]['label'],
1360
+			ucwords($c_label['label'])
1361
+		);
1362
+
1363
+		$title = sprintf(
1364
+			esc_html__(' %s %s Template %s', 'event_espresso'),
1365
+			ucwords($message_template_group->messenger_obj()->label['singular']),
1366
+			ucwords($message_template_group->message_type_obj()->label['singular']),
1367
+			$context_label
1368
+		);
1369
+
1370
+		$this->_template_args['GRP_ID'] = $GRP_ID;
1371
+		$this->_template_args['message_template'] = $message_template_group;
1372
+		$this->_template_args['is_extra_fields'] = false;
1373
+
1374
+
1375
+		// let's get EEH_MSG_Template so we can get template form fields
1376
+		$template_field_structure = EEH_MSG_Template::get_fields(
1377
+			$message_template_group->messenger(),
1378
+			$message_template_group->message_type()
1379
+		);
1380
+
1381
+		if (! $template_field_structure) {
1382
+			$template_field_structure = false;
1383
+			$template_fields = esc_html__(
1384
+				'There was an error in assembling the fields for this display (you should see an error message)',
1385
+				'event_espresso'
1386
+			);
1387
+		}
1388
+
1389
+
1390
+		$message_templates = $message_template_group->context_templates();
1391
+
1392
+
1393
+		// if we have the extra key.. then we need to remove the content index from the template_field_structure as it
1394
+		// will get handled in the "extra" array.
1395
+		if (is_array($template_field_structure[ $context ]) && isset($template_field_structure[ $context ]['extra'])) {
1396
+			foreach ($template_field_structure[ $context ]['extra'] as $reference_field => $new_fields) {
1397
+				unset($template_field_structure[ $context ][ $reference_field ]);
1398
+			}
1399
+		}
1400
+
1401
+		// let's loop through the template_field_structure and actually assemble the input fields!
1402
+		if (! empty($template_field_structure)) {
1403
+			foreach ($template_field_structure[ $context ] as $template_field => $field_setup_array) {
1404
+				// if this is an 'extra' template field then we need to remove any existing fields that are keyed up in
1405
+				// the extra array and reset them.
1406
+				if ($template_field === 'extra') {
1407
+					$this->_template_args['is_extra_fields'] = true;
1408
+					foreach ($field_setup_array as $reference_field => $new_fields_array) {
1409
+						$message_template = $message_templates[ $context ][ $reference_field ];
1410
+						$content = $message_template instanceof EE_Message_Template
1411
+							? $message_template->get('MTP_content')
1412
+							: '';
1413
+						foreach ($new_fields_array as $extra_field => $extra_array) {
1414
+							// let's verify if we need this extra field via the shortcodes parameter.
1415
+							$continue = false;
1416
+							if (isset($extra_array['shortcodes_required'])) {
1417
+								foreach ((array) $extra_array['shortcodes_required'] as $shortcode) {
1418
+									if (! array_key_exists($shortcode, $this->_shortcodes)) {
1419
+										$continue = true;
1420
+									}
1421
+								}
1422
+								if ($continue) {
1423
+									continue;
1424
+								}
1425
+							}
1426
+
1427
+							$field_id = $reference_field
1428
+										. '-'
1429
+										. $extra_field
1430
+										. '-content';
1431
+							$template_form_fields[ $field_id ] = $extra_array;
1432
+							$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields['
1433
+																		 . $reference_field
1434
+																		 . '][content]['
1435
+																		 . $extra_field . ']';
1436
+							$css_class = isset($extra_array['css_class'])
1437
+								? $extra_array['css_class']
1438
+								: '';
1439
+
1440
+							$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1441
+																			  && in_array($extra_field, $v_fields, true)
1442
+																			  &&
1443
+																			  (
1444
+																				  is_array($validators[ $extra_field ])
1445
+																				  && isset($validators[ $extra_field ]['msg'])
1446
+																			  )
1447
+								? 'validate-error ' . $css_class
1448
+								: $css_class;
1449
+
1450
+							$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1451
+																		  && isset($content[ $extra_field ])
1452
+								? $content[ $extra_field ]
1453
+								: '';
1454
+
1455
+							// do we have a validation error?  if we do then let's use that value instead
1456
+							$template_form_fields[ $field_id ]['value'] = isset($validators[ $extra_field ])
1457
+								? $validators[ $extra_field ]['value']
1458
+								: $template_form_fields[ $field_id ]['value'];
1459
+
1460
+
1461
+							$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1462
+
1463
+							// shortcode selector
1464
+							$field_name_to_use = $extra_field === 'main'
1465
+								? 'content'
1466
+								: $extra_field;
1467
+							$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1468
+								$field_name_to_use,
1469
+								$field_id
1470
+							);
1471
+
1472
+							if (isset($extra_array['input']) && $extra_array['input'] === 'wp_editor') {
1473
+								// we want to decode the entities
1474
+								$template_form_fields[ $field_id ]['value'] = $template_form_fields[ $field_id ]['value'];
1475
+							}/**/
1476
+						}
1477
+						$templatefield_MTP_id = $reference_field . '-MTP_ID';
1478
+						$templatefield_templatename_id = $reference_field . '-name';
1479
+
1480
+						$template_form_fields[ $templatefield_MTP_id ] = array(
1481
+							'name'       => 'MTP_template_fields[' . $reference_field . '][MTP_ID]',
1482
+							'label'      => null,
1483
+							'input'      => 'hidden',
1484
+							'type'       => 'int',
1485
+							'required'   => false,
1486
+							'validation' => false,
1487
+							'value'      => ! empty($message_templates) ? $message_template->ID() : '',
1488
+							'css_class'  => '',
1489
+							'format'     => '%d',
1490
+							'db-col'     => 'MTP_ID',
1491
+						);
1492
+
1493
+						$template_form_fields[ $templatefield_templatename_id ] = array(
1494
+							'name'       => 'MTP_template_fields[' . $reference_field . '][name]',
1495
+							'label'      => null,
1496
+							'input'      => 'hidden',
1497
+							'type'       => 'string',
1498
+							'required'   => false,
1499
+							'validation' => true,
1500
+							'value'      => $reference_field,
1501
+							'css_class'  => '',
1502
+							'format'     => '%s',
1503
+							'db-col'     => 'MTP_template_field',
1504
+						);
1505
+					}
1506
+					continue; // skip the next stuff, we got the necessary fields here for this dataset.
1507
+				} else {
1508
+					$field_id = $template_field . '-content';
1509
+					$template_form_fields[ $field_id ] = $field_setup_array;
1510
+					$template_form_fields[ $field_id ]['name'] = 'MTP_template_fields[' . $template_field . '][content]';
1511
+					$message_template = isset($message_templates[ $context ][ $template_field ])
1512
+						? $message_templates[ $context ][ $template_field ]
1513
+						: null;
1514
+					$template_form_fields[ $field_id ]['value'] = ! empty($message_templates)
1515
+																  && is_array($message_templates[ $context ])
1516
+																  && $message_template instanceof EE_Message_Template
1517
+						? $message_template->get('MTP_content')
1518
+						: '';
1519
+
1520
+					// do we have a validator error for this field?  if we do then we'll use that value instead
1521
+					$template_form_fields[ $field_id ]['value'] = isset($validators[ $template_field ])
1522
+						? $validators[ $template_field ]['value']
1523
+						: $template_form_fields[ $field_id ]['value'];
1524
+
1525
+
1526
+					$template_form_fields[ $field_id ]['db-col'] = 'MTP_content';
1527
+					$css_class = isset($field_setup_array['css_class'])
1528
+						? $field_setup_array['css_class']
1529
+						: '';
1530
+					$template_form_fields[ $field_id ]['css_class'] = ! empty($v_fields)
1531
+																	  && in_array($template_field, $v_fields, true)
1532
+																	  && isset($validators[ $template_field ]['msg'])
1533
+						? 'validate-error ' . $css_class
1534
+						: $css_class;
1535
+
1536
+					// shortcode selector
1537
+					$template_form_fields[ $field_id ]['append_content'] = $this->_get_shortcode_selector(
1538
+						$template_field,
1539
+						$field_id
1540
+					);
1541
+				}
1542
+
1543
+				// k took care of content field(s) now let's take care of others.
1544
+
1545
+				$templatefield_MTP_id = $template_field . '-MTP_ID';
1546
+				$templatefield_field_templatename_id = $template_field . '-name';
1547
+
1548
+				// foreach template field there are actually two form fields created
1549
+				$template_form_fields[ $templatefield_MTP_id ] = array(
1550
+					'name'       => 'MTP_template_fields[' . $template_field . '][MTP_ID]',
1551
+					'label'      => null,
1552
+					'input'      => 'hidden',
1553
+					'type'       => 'int',
1554
+					'required'   => false,
1555
+					'validation' => true,
1556
+					'value'      => $message_template instanceof EE_Message_Template ? $message_template->ID() : '',
1557
+					'css_class'  => '',
1558
+					'format'     => '%d',
1559
+					'db-col'     => 'MTP_ID',
1560
+				);
1561
+
1562
+				$template_form_fields[ $templatefield_field_templatename_id ] = array(
1563
+					'name'       => 'MTP_template_fields[' . $template_field . '][name]',
1564
+					'label'      => null,
1565
+					'input'      => 'hidden',
1566
+					'type'       => 'string',
1567
+					'required'   => false,
1568
+					'validation' => true,
1569
+					'value'      => $template_field,
1570
+					'css_class'  => '',
1571
+					'format'     => '%s',
1572
+					'db-col'     => 'MTP_template_field',
1573
+				);
1574
+			}
1575
+
1576
+			// add other fields
1577
+			$template_form_fields['ee-msg-current-context'] = array(
1578
+				'name'       => 'MTP_context',
1579
+				'label'      => null,
1580
+				'input'      => 'hidden',
1581
+				'type'       => 'string',
1582
+				'required'   => false,
1583
+				'validation' => true,
1584
+				'value'      => $context,
1585
+				'css_class'  => '',
1586
+				'format'     => '%s',
1587
+				'db-col'     => 'MTP_context',
1588
+			);
1589
+
1590
+			$template_form_fields['ee-msg-grp-id'] = array(
1591
+				'name'       => 'GRP_ID',
1592
+				'label'      => null,
1593
+				'input'      => 'hidden',
1594
+				'type'       => 'int',
1595
+				'required'   => false,
1596
+				'validation' => true,
1597
+				'value'      => $GRP_ID,
1598
+				'css_class'  => '',
1599
+				'format'     => '%d',
1600
+				'db-col'     => 'GRP_ID',
1601
+			);
1602
+
1603
+			$template_form_fields['ee-msg-messenger'] = array(
1604
+				'name'       => 'MTP_messenger',
1605
+				'label'      => null,
1606
+				'input'      => 'hidden',
1607
+				'type'       => 'string',
1608
+				'required'   => false,
1609
+				'validation' => true,
1610
+				'value'      => $message_template_group->messenger(),
1611
+				'css_class'  => '',
1612
+				'format'     => '%s',
1613
+				'db-col'     => 'MTP_messenger',
1614
+			);
1615
+
1616
+			$template_form_fields['ee-msg-message-type'] = array(
1617
+				'name'       => 'MTP_message_type',
1618
+				'label'      => null,
1619
+				'input'      => 'hidden',
1620
+				'type'       => 'string',
1621
+				'required'   => false,
1622
+				'validation' => true,
1623
+				'value'      => $message_template_group->message_type(),
1624
+				'css_class'  => '',
1625
+				'format'     => '%s',
1626
+				'db-col'     => 'MTP_message_type',
1627
+			);
1628
+
1629
+			$sidebar_form_fields['ee-msg-is-global'] = array(
1630
+				'name'       => 'MTP_is_global',
1631
+				'label'      => esc_html__('Global Template', 'event_espresso'),
1632
+				'input'      => 'hidden',
1633
+				'type'       => 'int',
1634
+				'required'   => false,
1635
+				'validation' => true,
1636
+				'value'      => $message_template_group->get('MTP_is_global'),
1637
+				'css_class'  => '',
1638
+				'format'     => '%d',
1639
+				'db-col'     => 'MTP_is_global',
1640
+			);
1641
+
1642
+			$sidebar_form_fields['ee-msg-is-override'] = array(
1643
+				'name'       => 'MTP_is_override',
1644
+				'label'      => esc_html__('Override all custom', 'event_espresso'),
1645
+				'input'      => $message_template_group->is_global() ? 'checkbox' : 'hidden',
1646
+				'type'       => 'int',
1647
+				'required'   => false,
1648
+				'validation' => true,
1649
+				'value'      => $message_template_group->get('MTP_is_override'),
1650
+				'css_class'  => '',
1651
+				'format'     => '%d',
1652
+				'db-col'     => 'MTP_is_override',
1653
+			);
1654
+
1655
+			$sidebar_form_fields['ee-msg-is-active'] = array(
1656
+				'name'       => 'MTP_is_active',
1657
+				'label'      => esc_html__('Active Template', 'event_espresso'),
1658
+				'input'      => 'hidden',
1659
+				'type'       => 'int',
1660
+				'required'   => false,
1661
+				'validation' => true,
1662
+				'value'      => $message_template_group->is_active(),
1663
+				'css_class'  => '',
1664
+				'format'     => '%d',
1665
+				'db-col'     => 'MTP_is_active',
1666
+			);
1667
+
1668
+			$sidebar_form_fields['ee-msg-deleted'] = array(
1669
+				'name'       => 'MTP_deleted',
1670
+				'label'      => null,
1671
+				'input'      => 'hidden',
1672
+				'type'       => 'int',
1673
+				'required'   => false,
1674
+				'validation' => true,
1675
+				'value'      => $message_template_group->get('MTP_deleted'),
1676
+				'css_class'  => '',
1677
+				'format'     => '%d',
1678
+				'db-col'     => 'MTP_deleted',
1679
+			);
1680
+			$sidebar_form_fields['ee-msg-author'] = array(
1681
+				'name'       => 'MTP_user_id',
1682
+				'label'      => esc_html__('Author', 'event_espresso'),
1683
+				'input'      => 'hidden',
1684
+				'type'       => 'int',
1685
+				'required'   => false,
1686
+				'validation' => false,
1687
+				'value'      => $message_template_group->user(),
1688
+				'format'     => '%d',
1689
+				'db-col'     => 'MTP_user_id',
1690
+			);
1691
+
1692
+			$sidebar_form_fields['ee-msg-route'] = array(
1693
+				'name'  => 'action',
1694
+				'input' => 'hidden',
1695
+				'type'  => 'string',
1696
+				'value' => $action,
1697
+			);
1698
+
1699
+			$sidebar_form_fields['ee-msg-id'] = array(
1700
+				'name'  => 'id',
1701
+				'input' => 'hidden',
1702
+				'type'  => 'int',
1703
+				'value' => $GRP_ID,
1704
+			);
1705
+			$sidebar_form_fields['ee-msg-evt-nonce'] = array(
1706
+				'name'  => $action . '_nonce',
1707
+				'input' => 'hidden',
1708
+				'type'  => 'string',
1709
+				'value' => wp_create_nonce($action . '_nonce'),
1710
+			);
1711
+
1712
+			if (isset($this->_req_data['template_switch']) && $this->_req_data['template_switch']) {
1713
+				$sidebar_form_fields['ee-msg-template-switch'] = array(
1714
+					'name'  => 'template_switch',
1715
+					'input' => 'hidden',
1716
+					'type'  => 'int',
1717
+					'value' => 1,
1718
+				);
1719
+			}
1720
+
1721
+
1722
+			$template_fields = $this->_generate_admin_form_fields($template_form_fields);
1723
+			$sidebar_fields = $this->_generate_admin_form_fields($sidebar_form_fields);
1724
+		} //end if ( !empty($template_field_structure) )
1725
+
1726
+		// set extra content for publish box
1727
+		$this->_template_args['publish_box_extra_content'] = $sidebar_fields;
1728
+		$this->_set_publish_post_box_vars(
1729
+			'id',
1730
+			$GRP_ID,
1731
+			false,
1732
+			add_query_arg(
1733
+				array('action' => 'global_mtps'),
1734
+				$this->_admin_base_url
1735
+			)
1736
+		);
1737
+
1738
+		// add preview button
1739
+		$preview_url = parent::add_query_args_and_nonce(
1740
+			array(
1741
+				'message_type' => $message_template_group->message_type(),
1742
+				'messenger'    => $message_template_group->messenger(),
1743
+				'context'      => $context,
1744
+				'GRP_ID'       => $GRP_ID,
1745
+				'evt_id'       => $EVT_ID,
1746
+				'action'       => 'preview_message',
1747
+			),
1748
+			$this->_admin_base_url
1749
+		);
1750
+		$preview_button = '<a href="' . $preview_url . '" class="button-secondary messages-preview-button">'
1751
+						  . esc_html__('Preview', 'event_espresso')
1752
+						  . '</a>';
1753
+
1754
+
1755
+		// setup context switcher
1756
+		$context_switcher_args = array(
1757
+			'page'    => 'espresso_messages',
1758
+			'action'  => 'edit_message_template',
1759
+			'id'      => $GRP_ID,
1760
+			'evt_id'  => $EVT_ID,
1761
+			'context' => $context,
1762
+			'extra'   => $preview_button,
1763
+		);
1764
+		$this->_set_context_switcher($message_template_group, $context_switcher_args);
1765
+
1766
+
1767
+		// main box
1768
+		$this->_template_args['template_fields'] = $template_fields;
1769
+		$this->_template_args['sidebar_box_id'] = 'details';
1770
+		$this->_template_args['action'] = $action;
1771
+		$this->_template_args['context'] = $context;
1772
+		$this->_template_args['edit_message_template_form_url'] = $edit_message_template_form_url;
1773
+		$this->_template_args['learn_more_about_message_templates_link'] =
1774
+			$this->_learn_more_about_message_templates_link();
1775
+
1776
+
1777
+		$this->_template_args['before_admin_page_content'] = $this->add_context_switcher();
1778
+		$this->_template_args['before_admin_page_content'] .= $this->add_active_context_element(
1779
+			$message_template_group,
1780
+			$context,
1781
+			$context_label
1782
+		);
1783
+		$this->_template_args['before_admin_page_content'] .= $this->_add_form_element_before();
1784
+		$this->_template_args['after_admin_page_content'] = $this->_add_form_element_after();
1785
+
1786
+		$this->_template_path = $this->_template_args['GRP_ID']
1787
+			? EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_edit_meta_box.template.php'
1788
+			: EE_MSG_TEMPLATE_PATH . 'ee_msg_details_main_add_meta_box.template.php';
1789
+
1790
+		// send along EE_Message_Template_Group object for further template use.
1791
+		$this->_template_args['MTP'] = $message_template_group;
1792
+
1793
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1794
+			$this->_template_path,
1795
+			$this->_template_args,
1796
+			true
1797
+		);
1798
+
1799
+
1800
+		// finally, let's set the admin_page title
1801
+		$this->_admin_page_title = sprintf(__('Editing %s', 'event_espresso'), $title);
1802
+
1803
+
1804
+		// we need to take care of setting the shortcodes property for use elsewhere.
1805
+		$this->_set_shortcodes();
1806
+
1807
+
1808
+		// final template wrapper
1809
+		$this->display_admin_page_with_sidebar();
1810
+	}
1811
+
1812
+
1813
+	public function filter_tinymce_init($mceInit, $editor_id)
1814
+	{
1815
+		return $mceInit;
1816
+	}
1817
+
1818
+
1819
+	public function add_context_switcher()
1820
+	{
1821
+		return $this->_context_switcher;
1822
+	}
1823
+
1824
+
1825
+	/**
1826
+	 * Adds the activation/deactivation toggle for the message template context.
1827
+	 *
1828
+	 * @param EE_Message_Template_Group $message_template_group
1829
+	 * @param string                    $context
1830
+	 * @param string                    $context_label
1831
+	 * @return string
1832
+	 * @throws DomainException
1833
+	 * @throws EE_Error
1834
+	 * @throws InvalidIdentifierException
1835
+	 */
1836
+	protected function add_active_context_element(
1837
+		EE_Message_Template_Group $message_template_group,
1838
+		$context,
1839
+		$context_label
1840
+	) {
1841
+		$template_args = array(
1842
+			'context'                   => $context,
1843
+			'nonce'                     => wp_create_nonce('activate_' . $context . '_toggle_nonce'),
1844
+			'is_active'                 => $message_template_group->is_context_active($context),
1845
+			'on_off_action'             => $message_template_group->is_context_active($context)
1846
+				? 'context-off'
1847
+				: 'context-on',
1848
+			'context_label'             => str_replace(array('(', ')'), '', $context_label),
1849
+			'message_template_group_id' => $message_template_group->ID(),
1850
+		);
1851
+		return EEH_Template::display_template(
1852
+			EE_MSG_TEMPLATE_PATH . 'ee_msg_editor_active_context_element.template.php',
1853
+			$template_args,
1854
+			true
1855
+		);
1856
+	}
1857
+
1858
+
1859
+	/**
1860
+	 * Ajax callback for `toggle_context_template` ajax action.
1861
+	 * Handles toggling the message context on or off.
1862
+	 *
1863
+	 * @throws EE_Error
1864
+	 * @throws InvalidArgumentException
1865
+	 * @throws InvalidDataTypeException
1866
+	 * @throws InvalidIdentifierException
1867
+	 * @throws InvalidInterfaceException
1868
+	 */
1869
+	public function toggle_context_template()
1870
+	{
1871
+		$success = true;
1872
+		// check for required data
1873
+		if (! isset(
1874
+			$this->_req_data['message_template_group_id'],
1875
+			$this->_req_data['context'],
1876
+			$this->_req_data['status']
1877
+		)) {
1878
+			EE_Error::add_error(
1879
+				esc_html__('Required data for doing this action is not available.', 'event_espresso'),
1880
+				__FILE__,
1881
+				__FUNCTION__,
1882
+				__LINE__
1883
+			);
1884
+			$success = false;
1885
+		}
1886
+
1887
+		$nonce = isset($this->_req_data['toggle_context_nonce'])
1888
+			? sanitize_text_field($this->_req_data['toggle_context_nonce'])
1889
+			: '';
1890
+		$nonce_ref = 'activate_' . $this->_req_data['context'] . '_toggle_nonce';
1891
+		$this->_verify_nonce($nonce, $nonce_ref);
1892
+		$status = $this->_req_data['status'];
1893
+		if ($status !== 'off' && $status !== 'on') {
1894
+			EE_Error::add_error(
1895
+				sprintf(
1896
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
1897
+					$this->_req_data['status']
1898
+				),
1899
+				__FILE__,
1900
+				__FUNCTION__,
1901
+				__LINE__
1902
+			);
1903
+			$success = false;
1904
+		}
1905
+		$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID(
1906
+			$this->_req_data['message_template_group_id']
1907
+		);
1908
+		if (! $message_template_group instanceof EE_Message_Template_Group) {
1909
+			EE_Error::add_error(
1910
+				sprintf(
1911
+					esc_html__(
1912
+						'Unable to change the active state because the given id "%1$d" does not match a valid "%2$s"',
1913
+						'event_espresso'
1914
+					),
1915
+					$this->_req_data['message_template_group_id'],
1916
+					'EE_Message_Template_Group'
1917
+				),
1918
+				__FILE__,
1919
+				__FUNCTION__,
1920
+				__LINE__
1921
+			);
1922
+			$success = false;
1923
+		}
1924
+		if ($success) {
1925
+			$success = $status === 'off'
1926
+				? $message_template_group->deactivate_context($this->_req_data['context'])
1927
+				: $message_template_group->activate_context($this->_req_data['context']);
1928
+		}
1929
+		$this->_template_args['success'] = $success;
1930
+		$this->_return_json();
1931
+	}
1932
+
1933
+
1934
+	public function _add_form_element_before()
1935
+	{
1936
+		return '<form method="post" action="'
1937
+			   . $this->_template_args["edit_message_template_form_url"]
1938
+			   . '" id="ee-msg-edit-frm">';
1939
+	}
1940
+
1941
+	public function _add_form_element_after()
1942
+	{
1943
+		return '</form>';
1944
+	}
1945
+
1946
+
1947
+	/**
1948
+	 * This executes switching the template pack for a message template.
1949
+	 *
1950
+	 * @since 4.5.0
1951
+	 * @throws EE_Error
1952
+	 * @throws InvalidDataTypeException
1953
+	 * @throws InvalidInterfaceException
1954
+	 * @throws InvalidArgumentException
1955
+	 * @throws ReflectionException
1956
+	 */
1957
+	public function switch_template_pack()
1958
+	{
1959
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
1960
+		$template_pack = ! empty($this->_req_data['template_pack']) ? $this->_req_data['template_pack'] : '';
1961
+
1962
+		// verify we have needed values.
1963
+		if (empty($GRP_ID) || empty($template_pack)) {
1964
+			$this->_template_args['error'] = true;
1965
+			EE_Error::add_error(
1966
+				esc_html__('The required date for switching templates is not available.', 'event_espresso'),
1967
+				__FILE__,
1968
+				__FUNCTION__,
1969
+				__LINE__
1970
+			);
1971
+		} else {
1972
+			// get template, set the new template_pack and then reset to default
1973
+			/** @type EE_Message_Template_Group $message_template_group */
1974
+			$message_template_group = EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1975
+
1976
+			$message_template_group->set_template_pack_name($template_pack);
1977
+			$this->_req_data['msgr'] = $message_template_group->messenger();
1978
+			$this->_req_data['mt'] = $message_template_group->message_type();
1979
+
1980
+			$query_args = $this->_reset_to_default_template();
1981
+
1982
+			if (empty($query_args['id'])) {
1983
+				EE_Error::add_error(
1984
+					esc_html__(
1985
+						'Something went wrong with switching the template pack. Please try again or contact EE support',
1986
+						'event_espresso'
1987
+					),
1988
+					__FILE__,
1989
+					__FUNCTION__,
1990
+					__LINE__
1991
+				);
1992
+				$this->_template_args['error'] = true;
1993
+			} else {
1994
+				$template_label = $message_template_group->get_template_pack()->label;
1995
+				$template_pack_labels = $message_template_group->messenger_obj()->get_supports_labels();
1996
+				EE_Error::add_success(
1997
+					sprintf(
1998
+						esc_html__(
1999
+							'This message template has been successfully switched to use the %1$s %2$s.  Please wait while the page reloads with your new template.',
2000
+							'event_espresso'
2001
+						),
2002
+						$template_label,
2003
+						$template_pack_labels->template_pack
2004
+					)
2005
+				);
2006
+				// generate the redirect url for js.
2007
+				$url = self::add_query_args_and_nonce(
2008
+					$query_args,
2009
+					$this->_admin_base_url
2010
+				);
2011
+				$this->_template_args['data']['redirect_url'] = $url;
2012
+				$this->_template_args['success'] = true;
2013
+			}
2014
+
2015
+			$this->_return_json();
2016
+		}
2017
+	}
2018
+
2019
+
2020
+	/**
2021
+	 * This handles resetting the template for the given messenger/message_type so that users can start from scratch if
2022
+	 * they want.
2023
+	 *
2024
+	 * @access protected
2025
+	 * @return array|null
2026
+	 * @throws EE_Error
2027
+	 * @throws InvalidArgumentException
2028
+	 * @throws InvalidDataTypeException
2029
+	 * @throws InvalidInterfaceException
2030
+	 */
2031
+	protected function _reset_to_default_template()
2032
+	{
2033
+
2034
+		$templates = array();
2035
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2036
+		// we need to make sure we've got the info we need.
2037
+		if (! isset($this->_req_data['msgr'], $this->_req_data['mt'], $this->_req_data['GRP_ID'])) {
2038
+			EE_Error::add_error(
2039
+				esc_html__(
2040
+					'In order to reset the template to its default we require the messenger, message type, and message template GRP_ID to know what is being reset.  At least one of these is missing.',
2041
+					'event_espresso'
2042
+				),
2043
+				__FILE__,
2044
+				__FUNCTION__,
2045
+				__LINE__
2046
+			);
2047
+		}
2048
+
2049
+		// all templates will be reset to whatever the defaults are
2050
+		// for the global template matching the messenger and message type.
2051
+		$success = ! empty($GRP_ID) ? true : false;
2052
+
2053
+		if ($success) {
2054
+			// let's first determine if the incoming template is a global template,
2055
+			// if it isn't then we need to get the global template matching messenger and message type.
2056
+			// $MTPG = EEM_Message_Template_Group::instance()->get_one_by_ID( $GRP_ID );
2057
+
2058
+
2059
+			// note this is ONLY deleting the template fields (Message Template rows) NOT the message template group.
2060
+			$success = $this->_delete_mtp_permanently($GRP_ID, false);
2061
+
2062
+			if ($success) {
2063
+				// if successfully deleted, lets generate the new ones.
2064
+				// Note. We set GLOBAL to true, because resets on ANY template
2065
+				// will use the related global template defaults for regeneration.
2066
+				// This means that if a custom template is reset it resets to whatever the related global template is.
2067
+				// HOWEVER, we DO keep the template pack and template variation set
2068
+				// for the current custom template when resetting.
2069
+				$templates = $this->_generate_new_templates(
2070
+					$this->_req_data['msgr'],
2071
+					$this->_req_data['mt'],
2072
+					$GRP_ID,
2073
+					true
2074
+				);
2075
+			}
2076
+		}
2077
+
2078
+		// any error messages?
2079
+		if (! $success) {
2080
+			EE_Error::add_error(
2081
+				esc_html__(
2082
+					'Something went wrong with deleting existing templates. Unable to reset to default',
2083
+					'event_espresso'
2084
+				),
2085
+				__FILE__,
2086
+				__FUNCTION__,
2087
+				__LINE__
2088
+			);
2089
+		}
2090
+
2091
+		// all good, let's add a success message!
2092
+		if ($success && ! empty($templates)) {
2093
+			// the info for the template we generated is the first element in the returned array
2094
+			// $templates = $templates[0];
2095
+			EE_Error::overwrite_success();
2096
+			EE_Error::add_success(__('Templates have been reset to defaults.', 'event_espresso'));
2097
+		}
2098
+
2099
+
2100
+		$query_args = array(
2101
+			'id'      => isset($templates[0]['GRP_ID']) ? $templates[0]['GRP_ID'] : null,
2102
+			'context' => isset($templates[0]['MTP_context']) ? $templates[0]['MTP_context'] : null,
2103
+			'action'  => isset($templates[0]['GRP_ID']) ? 'edit_message_template' : 'global_mtps',
2104
+		);
2105
+
2106
+		// if called via ajax then we return query args otherwise redirect
2107
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2108
+			return $query_args;
2109
+		} else {
2110
+			$this->_redirect_after_action(false, '', '', $query_args, true);
2111
+
2112
+			return null;
2113
+		}
2114
+	}
2115
+
2116
+
2117
+	/**
2118
+	 * Retrieve and set the message preview for display.
2119
+	 *
2120
+	 * @param bool $send if TRUE then we are doing an actual TEST send with the results of the preview.
2121
+	 * @return string
2122
+	 * @throws ReflectionException
2123
+	 * @throws EE_Error
2124
+	 * @throws InvalidArgumentException
2125
+	 * @throws InvalidDataTypeException
2126
+	 * @throws InvalidInterfaceException
2127
+	 */
2128
+	public function _preview_message($send = false)
2129
+	{
2130
+		// first make sure we've got the necessary parameters
2131
+		if (! isset(
2132
+			$this->_req_data['message_type'],
2133
+			$this->_req_data['messenger'],
2134
+			$this->_req_data['messenger'],
2135
+			$this->_req_data['GRP_ID']
2136
+		)) {
2137
+			EE_Error::add_error(
2138
+				esc_html__('Missing necessary parameters for displaying preview', 'event_espresso'),
2139
+				__FILE__,
2140
+				__FUNCTION__,
2141
+				__LINE__
2142
+			);
2143
+		}
2144
+
2145
+		EE_Registry::instance()->REQ->set('GRP_ID', $this->_req_data['GRP_ID']);
2146 2146
         
2147
-        // if we have an evt_id set on the request, use it.
2148
-        $EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
2149
-        ? absint($this->_req_data['evt_id'])
2150
-        : false;
2151
-
2152
-
2153
-        // get the preview!
2154
-        $preview = EED_Messages::preview_message(
2155
-            $this->_req_data['message_type'],
2156
-            $this->_req_data['context'],
2157
-            $this->_req_data['messenger'],
2158
-            $send
2159
-        );
2160
-
2161
-        if ($send) {
2162
-            return $preview;
2163
-        }
2164
-
2165
-        // let's add a button to go back to the edit view
2166
-        $query_args = array(
2167
-            'id'      => $this->_req_data['GRP_ID'],
2168
-            'evt_id'  => $EVT_ID,
2169
-            'context' => $this->_req_data['context'],
2170
-            'action'  => 'edit_message_template',
2171
-        );
2172
-        $go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2173
-        $preview_button = '<a href="'
2174
-                          . $go_back_url
2175
-                          . '" class="button-secondary messages-preview-go-back-button">'
2176
-                          . esc_html__('Go Back to Edit', 'event_espresso')
2177
-                          . '</a>';
2178
-        $message_types = $this->get_installed_message_types();
2179
-        $active_messenger = $this->_message_resource_manager->get_active_messenger(
2180
-            $this->_req_data['messenger']
2181
-        );
2182
-        $active_messenger_label = $active_messenger instanceof EE_messenger
2183
-            ? ucwords($active_messenger->label['singular'])
2184
-            : esc_html__('Unknown Messenger', 'event_espresso');
2185
-        // let's provide a helpful title for context
2186
-        $preview_title = sprintf(
2187
-            esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2188
-            $active_messenger_label,
2189
-            ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2190
-        );
2191
-        if (empty($preview)) {
2192
-            $this->noEventsErrorMessage();
2193
-        }
2194
-        // setup display of preview.
2195
-        $this->_admin_page_title = $preview_title;
2196
-        $this->_template_args['admin_page_title'] = $preview_title;
2197
-        $this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2198
-        $this->_template_args['data']['force_json'] = true;
2199
-
2200
-        return '';
2201
-    }
2202
-
2203
-
2204
-    /**
2205
-     * Used to set an error if there are no events available for generating a preview/test send.
2206
-     *
2207
-     * @param bool $test_send  Whether the error should be generated for the context of a test send.
2208
-     */
2209
-    protected function noEventsErrorMessage($test_send = false)
2210
-    {
2211
-        $events_url = parent::add_query_args_and_nonce(
2212
-            array(
2213
-                'action' => 'default',
2214
-                'page'   => 'espresso_events',
2215
-            ),
2216
-            admin_url('admin.php')
2217
-        );
2218
-        $message = $test_send
2219
-            ? __(
2220
-                'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2221
-                'event_espresso'
2222
-            )
2223
-            : __(
2224
-                'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2225
-                'event_espresso'
2226
-            );
2227
-
2228
-        EE_Error::add_attention(
2229
-            sprintf(
2230
-                $message,
2231
-                "<a href='{$events_url}'>",
2232
-                '</a>'
2233
-            )
2234
-        );
2235
-    }
2236
-
2237
-
2238
-    /**
2239
-     * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2240
-     * gets called automatically.
2241
-     *
2242
-     * @since 4.5.0
2243
-     *
2244
-     * @return string
2245
-     */
2246
-    protected function _display_preview_message()
2247
-    {
2248
-        $this->display_admin_page_with_no_sidebar();
2249
-    }
2250
-
2251
-
2252
-    /**
2253
-     * registers metaboxes that should show up on the "edit_message_template" page
2254
-     *
2255
-     * @access protected
2256
-     * @return void
2257
-     */
2258
-    protected function _register_edit_meta_boxes()
2259
-    {
2260
-        add_meta_box(
2261
-            'mtp_valid_shortcodes',
2262
-            esc_html__('Valid Shortcodes', 'event_espresso'),
2263
-            array($this, 'shortcode_meta_box'),
2264
-            $this->_current_screen->id,
2265
-            'side',
2266
-            'default'
2267
-        );
2268
-        add_meta_box(
2269
-            'mtp_extra_actions',
2270
-            esc_html__('Extra Actions', 'event_espresso'),
2271
-            array($this, 'extra_actions_meta_box'),
2272
-            $this->_current_screen->id,
2273
-            'side',
2274
-            'high'
2275
-        );
2276
-        add_meta_box(
2277
-            'mtp_templates',
2278
-            esc_html__('Template Styles', 'event_espresso'),
2279
-            array($this, 'template_pack_meta_box'),
2280
-            $this->_current_screen->id,
2281
-            'side',
2282
-            'high'
2283
-        );
2284
-    }
2285
-
2286
-
2287
-    /**
2288
-     * metabox content for all template pack and variation selection.
2289
-     *
2290
-     * @since 4.5.0
2291
-     * @return string
2292
-     * @throws DomainException
2293
-     * @throws EE_Error
2294
-     * @throws InvalidArgumentException
2295
-     * @throws ReflectionException
2296
-     * @throws InvalidDataTypeException
2297
-     * @throws InvalidInterfaceException
2298
-     */
2299
-    public function template_pack_meta_box()
2300
-    {
2301
-        $this->_set_message_template_group();
2302
-
2303
-        $tp_collection = EEH_MSG_Template::get_template_pack_collection();
2304
-
2305
-        $tp_select_values = array();
2306
-
2307
-        foreach ($tp_collection as $tp) {
2308
-            // only include template packs that support this messenger and message type!
2309
-            $supports = $tp->get_supports();
2310
-            if (! isset($supports[ $this->_message_template_group->messenger() ])
2311
-                || ! in_array(
2312
-                    $this->_message_template_group->message_type(),
2313
-                    $supports[ $this->_message_template_group->messenger() ],
2314
-                    true
2315
-                )
2316
-            ) {
2317
-                // not supported
2318
-                continue;
2319
-            }
2320
-
2321
-            $tp_select_values[] = array(
2322
-                'text' => $tp->label,
2323
-                'id'   => $tp->dbref,
2324
-            );
2325
-        }
2326
-
2327
-        // if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2328
-        // the default template pack.  This still allows for the odd template pack to override.
2329
-        if (empty($tp_select_values)) {
2330
-            $tp_select_values[] = array(
2331
-                'text' => esc_html__('Default', 'event_espresso'),
2332
-                'id'   => 'default',
2333
-            );
2334
-        }
2335
-
2336
-        // setup variation select values for the currently selected template.
2337
-        $variations = $this->_message_template_group->get_template_pack()->get_variations(
2338
-            $this->_message_template_group->messenger(),
2339
-            $this->_message_template_group->message_type()
2340
-        );
2341
-        $variations_select_values = array();
2342
-        foreach ($variations as $variation => $label) {
2343
-            $variations_select_values[] = array(
2344
-                'text' => $label,
2345
-                'id'   => $variation,
2346
-            );
2347
-        }
2348
-
2349
-        $template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2350
-
2351
-        $template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2352
-            'MTP_template_pack',
2353
-            $tp_select_values,
2354
-            $this->_message_template_group->get_template_pack_name()
2355
-        );
2356
-        $template_args['variations_selector'] = EEH_Form_Fields::select_input(
2357
-            'MTP_template_variation',
2358
-            $variations_select_values,
2359
-            $this->_message_template_group->get_template_pack_variation()
2360
-        );
2361
-        $template_args['template_pack_label'] = $template_pack_labels->template_pack;
2362
-        $template_args['template_variation_label'] = $template_pack_labels->template_variation;
2363
-        $template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2364
-        $template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2365
-
2366
-        $template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2367
-
2368
-        EEH_Template::display_template($template, $template_args);
2369
-    }
2370
-
2371
-
2372
-    /**
2373
-     * This meta box holds any extra actions related to Message Templates
2374
-     * For now, this includes Resetting templates to defaults and sending a test email.
2375
-     *
2376
-     * @access  public
2377
-     * @return void
2378
-     * @throws EE_Error
2379
-     */
2380
-    public function extra_actions_meta_box()
2381
-    {
2382
-        $template_form_fields = array();
2383
-
2384
-        $extra_args = array(
2385
-            'msgr'   => $this->_message_template_group->messenger(),
2386
-            'mt'     => $this->_message_template_group->message_type(),
2387
-            'GRP_ID' => $this->_message_template_group->GRP_ID(),
2388
-        );
2389
-        // first we need to see if there are any fields
2390
-        $fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2391
-
2392
-        if (! empty($fields)) {
2393
-            // yup there be fields
2394
-            foreach ($fields as $field => $config) {
2395
-                $field_id = $this->_message_template_group->messenger() . '_' . $field;
2396
-                $existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2397
-                $default = isset($config['default']) ? $config['default'] : '';
2398
-                $default = isset($config['value']) ? $config['value'] : $default;
2399
-
2400
-                // if type is hidden and the value is empty
2401
-                // something may have gone wrong so let's correct with the defaults
2402
-                $fix = $config['input'] === 'hidden'
2403
-                       && isset($existing[ $field ])
2404
-                       && empty($existing[ $field ])
2405
-                    ? $default
2406
-                    : '';
2407
-                $existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2408
-                    ? $existing[ $field ]
2409
-                    : $fix;
2410
-
2411
-                $template_form_fields[ $field_id ] = array(
2412
-                    'name'       => 'test_settings_fld[' . $field . ']',
2413
-                    'label'      => $config['label'],
2414
-                    'input'      => $config['input'],
2415
-                    'type'       => $config['type'],
2416
-                    'required'   => $config['required'],
2417
-                    'validation' => $config['validation'],
2418
-                    'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2419
-                    'css_class'  => $config['css_class'],
2420
-                    'options'    => isset($config['options']) ? $config['options'] : array(),
2421
-                    'default'    => $default,
2422
-                    'format'     => $config['format'],
2423
-                );
2424
-            }
2425
-        }
2426
-
2427
-        $test_settings_fields = ! empty($template_form_fields)
2428
-            ? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2429
-            : '';
2430
-
2431
-        $test_settings_html = '';
2432
-        // print out $test_settings_fields
2433
-        if (! empty($test_settings_fields)) {
2434
-            echo $test_settings_fields;
2435
-            $test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2436
-            $test_settings_html .= 'name="test_button" value="';
2437
-            $test_settings_html .= esc_html__('Test Send', 'event_espresso');
2438
-            $test_settings_html .= '" /><div style="clear:both"></div>';
2439
-        }
2440
-
2441
-        // and button
2442
-        $test_settings_html .= '<p>'
2443
-                               . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2444
-                               . '</p>';
2445
-        $test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2446
-        $test_settings_html .= $this->get_action_link_or_button(
2447
-            'reset_to_default',
2448
-            'reset',
2449
-            $extra_args,
2450
-            'button-primary reset-default-button'
2451
-        );
2452
-        $test_settings_html .= '</div><div style="clear:both"></div>';
2453
-        echo $test_settings_html;
2454
-    }
2455
-
2456
-
2457
-    /**
2458
-     * This returns the shortcode selector skeleton for a given context and field.
2459
-     *
2460
-     * @since 4.9.rc.000
2461
-     * @param string $field           The name of the field retrieving shortcodes for.
2462
-     * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2463
-     * @return string
2464
-     * @throws DomainException
2465
-     * @throws EE_Error
2466
-     * @throws InvalidArgumentException
2467
-     * @throws ReflectionException
2468
-     * @throws InvalidDataTypeException
2469
-     * @throws InvalidInterfaceException
2470
-     */
2471
-    protected function _get_shortcode_selector($field, $linked_input_id)
2472
-    {
2473
-        $template_args = array(
2474
-            'shortcodes'      => $this->_get_shortcodes(array($field), true),
2475
-            'fieldname'       => $field,
2476
-            'linked_input_id' => $linked_input_id,
2477
-        );
2478
-
2479
-        return EEH_Template::display_template(
2480
-            EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2481
-            $template_args,
2482
-            true
2483
-        );
2484
-    }
2485
-
2486
-
2487
-    /**
2488
-     * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2489
-     * page)
2490
-     *
2491
-     * @access public
2492
-     * @return void
2493
-     * @throws EE_Error
2494
-     * @throws InvalidArgumentException
2495
-     * @throws ReflectionException
2496
-     * @throws InvalidDataTypeException
2497
-     * @throws InvalidInterfaceException
2498
-     */
2499
-    public function shortcode_meta_box()
2500
-    {
2501
-        $shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2502
-        // $messenger = $this->_message_template_group->messenger_obj();
2503
-        // now let's set the content depending on the status of the shortcodes array
2504
-        if (empty($shortcodes)) {
2505
-            $content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2506
-            echo $content;
2507
-        } else {
2508
-            // $alt = 0;
2509
-            ?>
2147
+		// if we have an evt_id set on the request, use it.
2148
+		$EVT_ID = isset($this->_req_data['evt_id']) && ! empty($this->_req_data['evt_id'])
2149
+		? absint($this->_req_data['evt_id'])
2150
+		: false;
2151
+
2152
+
2153
+		// get the preview!
2154
+		$preview = EED_Messages::preview_message(
2155
+			$this->_req_data['message_type'],
2156
+			$this->_req_data['context'],
2157
+			$this->_req_data['messenger'],
2158
+			$send
2159
+		);
2160
+
2161
+		if ($send) {
2162
+			return $preview;
2163
+		}
2164
+
2165
+		// let's add a button to go back to the edit view
2166
+		$query_args = array(
2167
+			'id'      => $this->_req_data['GRP_ID'],
2168
+			'evt_id'  => $EVT_ID,
2169
+			'context' => $this->_req_data['context'],
2170
+			'action'  => 'edit_message_template',
2171
+		);
2172
+		$go_back_url = parent::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2173
+		$preview_button = '<a href="'
2174
+						  . $go_back_url
2175
+						  . '" class="button-secondary messages-preview-go-back-button">'
2176
+						  . esc_html__('Go Back to Edit', 'event_espresso')
2177
+						  . '</a>';
2178
+		$message_types = $this->get_installed_message_types();
2179
+		$active_messenger = $this->_message_resource_manager->get_active_messenger(
2180
+			$this->_req_data['messenger']
2181
+		);
2182
+		$active_messenger_label = $active_messenger instanceof EE_messenger
2183
+			? ucwords($active_messenger->label['singular'])
2184
+			: esc_html__('Unknown Messenger', 'event_espresso');
2185
+		// let's provide a helpful title for context
2186
+		$preview_title = sprintf(
2187
+			esc_html__('Viewing Preview for %s %s Message Template', 'event_espresso'),
2188
+			$active_messenger_label,
2189
+			ucwords($message_types[ $this->_req_data['message_type'] ]->label['singular'])
2190
+		);
2191
+		if (empty($preview)) {
2192
+			$this->noEventsErrorMessage();
2193
+		}
2194
+		// setup display of preview.
2195
+		$this->_admin_page_title = $preview_title;
2196
+		$this->_template_args['admin_page_title'] = $preview_title;
2197
+		$this->_template_args['admin_page_content'] = $preview_button . '<br />' . $preview;
2198
+		$this->_template_args['data']['force_json'] = true;
2199
+
2200
+		return '';
2201
+	}
2202
+
2203
+
2204
+	/**
2205
+	 * Used to set an error if there are no events available for generating a preview/test send.
2206
+	 *
2207
+	 * @param bool $test_send  Whether the error should be generated for the context of a test send.
2208
+	 */
2209
+	protected function noEventsErrorMessage($test_send = false)
2210
+	{
2211
+		$events_url = parent::add_query_args_and_nonce(
2212
+			array(
2213
+				'action' => 'default',
2214
+				'page'   => 'espresso_events',
2215
+			),
2216
+			admin_url('admin.php')
2217
+		);
2218
+		$message = $test_send
2219
+			? __(
2220
+				'A test message could not be sent for this message template because there are no events created yet. The preview system uses actual events for generating the test message. %1$sGo see your events%2$s!',
2221
+				'event_espresso'
2222
+			)
2223
+			: __(
2224
+				'There is no preview for this message template available because there are no events created yet. The preview system uses actual events for generating the preview. %1$sGo see your events%2$s!',
2225
+				'event_espresso'
2226
+			);
2227
+
2228
+		EE_Error::add_attention(
2229
+			sprintf(
2230
+				$message,
2231
+				"<a href='{$events_url}'>",
2232
+				'</a>'
2233
+			)
2234
+		);
2235
+	}
2236
+
2237
+
2238
+	/**
2239
+	 * The initial _preview_message is on a no headers route.  It will optionally call this if necessary otherwise it
2240
+	 * gets called automatically.
2241
+	 *
2242
+	 * @since 4.5.0
2243
+	 *
2244
+	 * @return string
2245
+	 */
2246
+	protected function _display_preview_message()
2247
+	{
2248
+		$this->display_admin_page_with_no_sidebar();
2249
+	}
2250
+
2251
+
2252
+	/**
2253
+	 * registers metaboxes that should show up on the "edit_message_template" page
2254
+	 *
2255
+	 * @access protected
2256
+	 * @return void
2257
+	 */
2258
+	protected function _register_edit_meta_boxes()
2259
+	{
2260
+		add_meta_box(
2261
+			'mtp_valid_shortcodes',
2262
+			esc_html__('Valid Shortcodes', 'event_espresso'),
2263
+			array($this, 'shortcode_meta_box'),
2264
+			$this->_current_screen->id,
2265
+			'side',
2266
+			'default'
2267
+		);
2268
+		add_meta_box(
2269
+			'mtp_extra_actions',
2270
+			esc_html__('Extra Actions', 'event_espresso'),
2271
+			array($this, 'extra_actions_meta_box'),
2272
+			$this->_current_screen->id,
2273
+			'side',
2274
+			'high'
2275
+		);
2276
+		add_meta_box(
2277
+			'mtp_templates',
2278
+			esc_html__('Template Styles', 'event_espresso'),
2279
+			array($this, 'template_pack_meta_box'),
2280
+			$this->_current_screen->id,
2281
+			'side',
2282
+			'high'
2283
+		);
2284
+	}
2285
+
2286
+
2287
+	/**
2288
+	 * metabox content for all template pack and variation selection.
2289
+	 *
2290
+	 * @since 4.5.0
2291
+	 * @return string
2292
+	 * @throws DomainException
2293
+	 * @throws EE_Error
2294
+	 * @throws InvalidArgumentException
2295
+	 * @throws ReflectionException
2296
+	 * @throws InvalidDataTypeException
2297
+	 * @throws InvalidInterfaceException
2298
+	 */
2299
+	public function template_pack_meta_box()
2300
+	{
2301
+		$this->_set_message_template_group();
2302
+
2303
+		$tp_collection = EEH_MSG_Template::get_template_pack_collection();
2304
+
2305
+		$tp_select_values = array();
2306
+
2307
+		foreach ($tp_collection as $tp) {
2308
+			// only include template packs that support this messenger and message type!
2309
+			$supports = $tp->get_supports();
2310
+			if (! isset($supports[ $this->_message_template_group->messenger() ])
2311
+				|| ! in_array(
2312
+					$this->_message_template_group->message_type(),
2313
+					$supports[ $this->_message_template_group->messenger() ],
2314
+					true
2315
+				)
2316
+			) {
2317
+				// not supported
2318
+				continue;
2319
+			}
2320
+
2321
+			$tp_select_values[] = array(
2322
+				'text' => $tp->label,
2323
+				'id'   => $tp->dbref,
2324
+			);
2325
+		}
2326
+
2327
+		// if empty $tp_select_values then we make sure default is set because EVERY message type should be supported by
2328
+		// the default template pack.  This still allows for the odd template pack to override.
2329
+		if (empty($tp_select_values)) {
2330
+			$tp_select_values[] = array(
2331
+				'text' => esc_html__('Default', 'event_espresso'),
2332
+				'id'   => 'default',
2333
+			);
2334
+		}
2335
+
2336
+		// setup variation select values for the currently selected template.
2337
+		$variations = $this->_message_template_group->get_template_pack()->get_variations(
2338
+			$this->_message_template_group->messenger(),
2339
+			$this->_message_template_group->message_type()
2340
+		);
2341
+		$variations_select_values = array();
2342
+		foreach ($variations as $variation => $label) {
2343
+			$variations_select_values[] = array(
2344
+				'text' => $label,
2345
+				'id'   => $variation,
2346
+			);
2347
+		}
2348
+
2349
+		$template_pack_labels = $this->_message_template_group->messenger_obj()->get_supports_labels();
2350
+
2351
+		$template_args['template_packs_selector'] = EEH_Form_Fields::select_input(
2352
+			'MTP_template_pack',
2353
+			$tp_select_values,
2354
+			$this->_message_template_group->get_template_pack_name()
2355
+		);
2356
+		$template_args['variations_selector'] = EEH_Form_Fields::select_input(
2357
+			'MTP_template_variation',
2358
+			$variations_select_values,
2359
+			$this->_message_template_group->get_template_pack_variation()
2360
+		);
2361
+		$template_args['template_pack_label'] = $template_pack_labels->template_pack;
2362
+		$template_args['template_variation_label'] = $template_pack_labels->template_variation;
2363
+		$template_args['template_pack_description'] = $template_pack_labels->template_pack_description;
2364
+		$template_args['template_variation_description'] = $template_pack_labels->template_variation_description;
2365
+
2366
+		$template = EE_MSG_TEMPLATE_PATH . 'template_pack_and_variations_metabox.template.php';
2367
+
2368
+		EEH_Template::display_template($template, $template_args);
2369
+	}
2370
+
2371
+
2372
+	/**
2373
+	 * This meta box holds any extra actions related to Message Templates
2374
+	 * For now, this includes Resetting templates to defaults and sending a test email.
2375
+	 *
2376
+	 * @access  public
2377
+	 * @return void
2378
+	 * @throws EE_Error
2379
+	 */
2380
+	public function extra_actions_meta_box()
2381
+	{
2382
+		$template_form_fields = array();
2383
+
2384
+		$extra_args = array(
2385
+			'msgr'   => $this->_message_template_group->messenger(),
2386
+			'mt'     => $this->_message_template_group->message_type(),
2387
+			'GRP_ID' => $this->_message_template_group->GRP_ID(),
2388
+		);
2389
+		// first we need to see if there are any fields
2390
+		$fields = $this->_message_template_group->messenger_obj()->get_test_settings_fields();
2391
+
2392
+		if (! empty($fields)) {
2393
+			// yup there be fields
2394
+			foreach ($fields as $field => $config) {
2395
+				$field_id = $this->_message_template_group->messenger() . '_' . $field;
2396
+				$existing = $this->_message_template_group->messenger_obj()->get_existing_test_settings();
2397
+				$default = isset($config['default']) ? $config['default'] : '';
2398
+				$default = isset($config['value']) ? $config['value'] : $default;
2399
+
2400
+				// if type is hidden and the value is empty
2401
+				// something may have gone wrong so let's correct with the defaults
2402
+				$fix = $config['input'] === 'hidden'
2403
+					   && isset($existing[ $field ])
2404
+					   && empty($existing[ $field ])
2405
+					? $default
2406
+					: '';
2407
+				$existing[ $field ] = isset($existing[ $field ]) && empty($fix)
2408
+					? $existing[ $field ]
2409
+					: $fix;
2410
+
2411
+				$template_form_fields[ $field_id ] = array(
2412
+					'name'       => 'test_settings_fld[' . $field . ']',
2413
+					'label'      => $config['label'],
2414
+					'input'      => $config['input'],
2415
+					'type'       => $config['type'],
2416
+					'required'   => $config['required'],
2417
+					'validation' => $config['validation'],
2418
+					'value'      => isset($existing[ $field ]) ? $existing[ $field ] : $default,
2419
+					'css_class'  => $config['css_class'],
2420
+					'options'    => isset($config['options']) ? $config['options'] : array(),
2421
+					'default'    => $default,
2422
+					'format'     => $config['format'],
2423
+				);
2424
+			}
2425
+		}
2426
+
2427
+		$test_settings_fields = ! empty($template_form_fields)
2428
+			? $this->_generate_admin_form_fields($template_form_fields, 'string', 'ee_tst_settings_flds')
2429
+			: '';
2430
+
2431
+		$test_settings_html = '';
2432
+		// print out $test_settings_fields
2433
+		if (! empty($test_settings_fields)) {
2434
+			echo $test_settings_fields;
2435
+			$test_settings_html = '<input type="submit" class="button-primary mtp-test-button alignright" ';
2436
+			$test_settings_html .= 'name="test_button" value="';
2437
+			$test_settings_html .= esc_html__('Test Send', 'event_espresso');
2438
+			$test_settings_html .= '" /><div style="clear:both"></div>';
2439
+		}
2440
+
2441
+		// and button
2442
+		$test_settings_html .= '<p>'
2443
+							   . esc_html__('Need to reset this message type and start over?', 'event_espresso')
2444
+							   . '</p>';
2445
+		$test_settings_html .= '<div class="publishing-action alignright resetbutton">';
2446
+		$test_settings_html .= $this->get_action_link_or_button(
2447
+			'reset_to_default',
2448
+			'reset',
2449
+			$extra_args,
2450
+			'button-primary reset-default-button'
2451
+		);
2452
+		$test_settings_html .= '</div><div style="clear:both"></div>';
2453
+		echo $test_settings_html;
2454
+	}
2455
+
2456
+
2457
+	/**
2458
+	 * This returns the shortcode selector skeleton for a given context and field.
2459
+	 *
2460
+	 * @since 4.9.rc.000
2461
+	 * @param string $field           The name of the field retrieving shortcodes for.
2462
+	 * @param string $linked_input_id The css id of the input that the shortcodes get added to.
2463
+	 * @return string
2464
+	 * @throws DomainException
2465
+	 * @throws EE_Error
2466
+	 * @throws InvalidArgumentException
2467
+	 * @throws ReflectionException
2468
+	 * @throws InvalidDataTypeException
2469
+	 * @throws InvalidInterfaceException
2470
+	 */
2471
+	protected function _get_shortcode_selector($field, $linked_input_id)
2472
+	{
2473
+		$template_args = array(
2474
+			'shortcodes'      => $this->_get_shortcodes(array($field), true),
2475
+			'fieldname'       => $field,
2476
+			'linked_input_id' => $linked_input_id,
2477
+		);
2478
+
2479
+		return EEH_Template::display_template(
2480
+			EE_MSG_TEMPLATE_PATH . 'shortcode_selector_skeleton.template.php',
2481
+			$template_args,
2482
+			true
2483
+		);
2484
+	}
2485
+
2486
+
2487
+	/**
2488
+	 * This just takes care of returning the meta box content for shortcodes (only used on the edit message template
2489
+	 * page)
2490
+	 *
2491
+	 * @access public
2492
+	 * @return void
2493
+	 * @throws EE_Error
2494
+	 * @throws InvalidArgumentException
2495
+	 * @throws ReflectionException
2496
+	 * @throws InvalidDataTypeException
2497
+	 * @throws InvalidInterfaceException
2498
+	 */
2499
+	public function shortcode_meta_box()
2500
+	{
2501
+		$shortcodes = $this->_get_shortcodes(array(), false); // just make sure shortcodes property is set
2502
+		// $messenger = $this->_message_template_group->messenger_obj();
2503
+		// now let's set the content depending on the status of the shortcodes array
2504
+		if (empty($shortcodes)) {
2505
+			$content = '<p>' . esc_html__('There are no valid shortcodes available', 'event_espresso') . '</p>';
2506
+			echo $content;
2507
+		} else {
2508
+			// $alt = 0;
2509
+			?>
2510 2510
             <div style="float:right; margin-top:10px"><?php
2511
-                            echo $this->_get_help_tab_link('message_template_shortcodes');
2512
-                            ?></div>
2511
+							echo $this->_get_help_tab_link('message_template_shortcodes');
2512
+							?></div>
2513 2513
             <p class="small-text"><?php
2514
-                                  printf(
2515
-                                      esc_html__(
2516
-                                          'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2517
-                                          'event_espresso'
2518
-                                      ),
2519
-                                      '<span class="dashicons dashicons-menu"></span>'
2520
-                                  );
2521
-                                ?>
2514
+								  printf(
2515
+									  esc_html__(
2516
+										  'You can view the shortcodes usable in your template by clicking the %s icon next to each field.',
2517
+										  'event_espresso'
2518
+									  ),
2519
+									  '<span class="dashicons dashicons-menu"></span>'
2520
+								  );
2521
+								?>
2522 2522
             </p>
2523 2523
             <?php
2524
-        }
2525
-    }
2526
-
2527
-
2528
-    /**
2529
-     * used to set the $_shortcodes property for when its needed elsewhere.
2530
-     *
2531
-     * @access protected
2532
-     * @return void
2533
-     * @throws EE_Error
2534
-     * @throws InvalidArgumentException
2535
-     * @throws ReflectionException
2536
-     * @throws InvalidDataTypeException
2537
-     * @throws InvalidInterfaceException
2538
-     */
2539
-    protected function _set_shortcodes()
2540
-    {
2541
-
2542
-        // no need to run this if the property is already set
2543
-        if (! empty($this->_shortcodes)) {
2544
-            return;
2545
-        }
2546
-
2547
-        $this->_shortcodes = $this->_get_shortcodes();
2548
-    }
2549
-
2550
-
2551
-    /**
2552
-     * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2553
-     * property)
2554
-     *
2555
-     * @access  protected
2556
-     * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2557
-     *                         for. Defaults to all (for the given context)
2558
-     * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2559
-     * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2560
-     *                         true just an array of shortcode/label pairs.
2561
-     * @throws EE_Error
2562
-     * @throws InvalidArgumentException
2563
-     * @throws ReflectionException
2564
-     * @throws InvalidDataTypeException
2565
-     * @throws InvalidInterfaceException
2566
-     */
2567
-    protected function _get_shortcodes($fields = array(), $merged = true)
2568
-    {
2569
-        $this->_set_message_template_group();
2570
-
2571
-        // we need the messenger and message template to retrieve the valid shortcodes array.
2572
-        $GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2573
-            ? absint($this->_req_data['id'])
2574
-            : false;
2575
-        $context = isset($this->_req_data['context'])
2576
-            ? $this->_req_data['context']
2577
-            : key($this->_message_template_group->contexts_config());
2578
-
2579
-        return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2580
-    }
2581
-
2582
-
2583
-    /**
2584
-     * This sets the _message_template property (containing the called message_template object)
2585
-     *
2586
-     * @access protected
2587
-     * @return void
2588
-     * @throws EE_Error
2589
-     * @throws InvalidArgumentException
2590
-     * @throws ReflectionException
2591
-     * @throws InvalidDataTypeException
2592
-     * @throws InvalidInterfaceException
2593
-     */
2594
-    protected function _set_message_template_group()
2595
-    {
2596
-
2597
-        if (! empty($this->_message_template_group)) {
2598
-            return;
2599
-        } //get out if this is already set.
2600
-
2601
-        $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2602
-        $GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2603
-
2604
-        // let's get the message templates
2605
-        $MTP = EEM_Message_Template_Group::instance();
2606
-
2607
-        if (empty($GRP_ID)) {
2608
-            $this->_message_template_group = $MTP->create_default_object();
2609
-        } else {
2610
-            $this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2611
-        }
2612
-
2613
-        $this->_template_pack = $this->_message_template_group->get_template_pack();
2614
-        $this->_variation = $this->_message_template_group->get_template_pack_variation();
2615
-    }
2616
-
2617
-
2618
-    /**
2619
-     * sets up a context switcher for edit forms
2620
-     *
2621
-     * @access  protected
2622
-     * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2623
-     * @param array                      $args                  various things the context switcher needs.
2624
-     * @throws EE_Error
2625
-     */
2626
-    protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2627
-    {
2628
-        $context_details = $template_group_object->contexts_config();
2629
-        $context_label = $template_group_object->context_label();
2630
-        ob_start();
2631
-        ?>
2524
+		}
2525
+	}
2526
+
2527
+
2528
+	/**
2529
+	 * used to set the $_shortcodes property for when its needed elsewhere.
2530
+	 *
2531
+	 * @access protected
2532
+	 * @return void
2533
+	 * @throws EE_Error
2534
+	 * @throws InvalidArgumentException
2535
+	 * @throws ReflectionException
2536
+	 * @throws InvalidDataTypeException
2537
+	 * @throws InvalidInterfaceException
2538
+	 */
2539
+	protected function _set_shortcodes()
2540
+	{
2541
+
2542
+		// no need to run this if the property is already set
2543
+		if (! empty($this->_shortcodes)) {
2544
+			return;
2545
+		}
2546
+
2547
+		$this->_shortcodes = $this->_get_shortcodes();
2548
+	}
2549
+
2550
+
2551
+	/**
2552
+	 * get's all shortcodes for a given template group. (typically used by _set_shortcodes to set the $_shortcodes
2553
+	 * property)
2554
+	 *
2555
+	 * @access  protected
2556
+	 * @param  array   $fields include an array of specific field names that you want to be used to get the shortcodes
2557
+	 *                         for. Defaults to all (for the given context)
2558
+	 * @param  boolean $merged Whether to merge all the shortcodes into one list of unique shortcodes
2559
+	 * @return array Shortcodes indexed by fieldname and the an array of shortcode/label pairs OR if merged is
2560
+	 *                         true just an array of shortcode/label pairs.
2561
+	 * @throws EE_Error
2562
+	 * @throws InvalidArgumentException
2563
+	 * @throws ReflectionException
2564
+	 * @throws InvalidDataTypeException
2565
+	 * @throws InvalidInterfaceException
2566
+	 */
2567
+	protected function _get_shortcodes($fields = array(), $merged = true)
2568
+	{
2569
+		$this->_set_message_template_group();
2570
+
2571
+		// we need the messenger and message template to retrieve the valid shortcodes array.
2572
+		$GRP_ID = isset($this->_req_data['id']) && ! empty($this->_req_data['id'])
2573
+			? absint($this->_req_data['id'])
2574
+			: false;
2575
+		$context = isset($this->_req_data['context'])
2576
+			? $this->_req_data['context']
2577
+			: key($this->_message_template_group->contexts_config());
2578
+
2579
+		return ! empty($GRP_ID) ? $this->_message_template_group->get_shortcodes($context, $fields, $merged) : array();
2580
+	}
2581
+
2582
+
2583
+	/**
2584
+	 * This sets the _message_template property (containing the called message_template object)
2585
+	 *
2586
+	 * @access protected
2587
+	 * @return void
2588
+	 * @throws EE_Error
2589
+	 * @throws InvalidArgumentException
2590
+	 * @throws ReflectionException
2591
+	 * @throws InvalidDataTypeException
2592
+	 * @throws InvalidInterfaceException
2593
+	 */
2594
+	protected function _set_message_template_group()
2595
+	{
2596
+
2597
+		if (! empty($this->_message_template_group)) {
2598
+			return;
2599
+		} //get out if this is already set.
2600
+
2601
+		$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? absint($this->_req_data['GRP_ID']) : false;
2602
+		$GRP_ID = empty($GRP_ID) && ! empty($this->_req_data['id']) ? $this->_req_data['id'] : $GRP_ID;
2603
+
2604
+		// let's get the message templates
2605
+		$MTP = EEM_Message_Template_Group::instance();
2606
+
2607
+		if (empty($GRP_ID)) {
2608
+			$this->_message_template_group = $MTP->create_default_object();
2609
+		} else {
2610
+			$this->_message_template_group = $MTP->get_one_by_ID($GRP_ID);
2611
+		}
2612
+
2613
+		$this->_template_pack = $this->_message_template_group->get_template_pack();
2614
+		$this->_variation = $this->_message_template_group->get_template_pack_variation();
2615
+	}
2616
+
2617
+
2618
+	/**
2619
+	 * sets up a context switcher for edit forms
2620
+	 *
2621
+	 * @access  protected
2622
+	 * @param  EE_Message_Template_Group $template_group_object the template group object being displayed on the form
2623
+	 * @param array                      $args                  various things the context switcher needs.
2624
+	 * @throws EE_Error
2625
+	 */
2626
+	protected function _set_context_switcher(EE_Message_Template_Group $template_group_object, $args)
2627
+	{
2628
+		$context_details = $template_group_object->contexts_config();
2629
+		$context_label = $template_group_object->context_label();
2630
+		ob_start();
2631
+		?>
2632 2632
         <div class="ee-msg-switcher-container">
2633 2633
             <form method="get" action="<?php echo EE_MSG_ADMIN_URL; ?>" id="ee-msg-context-switcher-frm">
2634 2634
                 <?php
2635
-                foreach ($args as $name => $value) {
2636
-                    if ($name === 'context' || empty($value) || $name === 'extra') {
2637
-                        continue;
2638
-                    }
2639
-                    ?>
2635
+				foreach ($args as $name => $value) {
2636
+					if ($name === 'context' || empty($value) || $name === 'extra') {
2637
+						continue;
2638
+					}
2639
+					?>
2640 2640
                     <input type="hidden" name="<?php echo $name; ?>" value="<?php echo $value; ?>"/>
2641 2641
                     <?php
2642
-                }
2643
-                // setup nonce_url
2644
-                wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2645
-                ?>
2642
+				}
2643
+				// setup nonce_url
2644
+				wp_nonce_field($args['action'] . '_nonce', $args['action'] . '_nonce', false);
2645
+				?>
2646 2646
                 <select name="context">
2647 2647
                     <?php
2648
-                    $context_templates = $template_group_object->context_templates();
2649
-                    if (is_array($context_templates)) :
2650
-                        foreach ($context_templates as $context => $template_fields) :
2651
-                            $checked = ($context === $args['context']) ? 'selected="selected"' : '';
2652
-                            ?>
2648
+					$context_templates = $template_group_object->context_templates();
2649
+					if (is_array($context_templates)) :
2650
+						foreach ($context_templates as $context => $template_fields) :
2651
+							$checked = ($context === $args['context']) ? 'selected="selected"' : '';
2652
+							?>
2653 2653
                             <option value="<?php echo $context; ?>" <?php echo $checked; ?>>
2654 2654
                                 <?php echo $context_details[ $context ]['label']; ?>
2655 2655
                             </option>
2656 2656
                         <?php endforeach;
2657
-                    endif; ?>
2657
+					endif; ?>
2658 2658
                 </select>
2659 2659
                 <?php $button_text = sprintf(__('Switch %s', 'event_espresso'), ucwords($context_label['label'])); ?>
2660 2660
                 <input id="submit-msg-context-switcher-sbmt" class="button-secondary" type="submit"
@@ -2663,1925 +2663,1925 @@  discard block
 block discarded – undo
2663 2663
             <?php echo $args['extra']; ?>
2664 2664
         </div> <!-- end .ee-msg-switcher-container -->
2665 2665
         <?php
2666
-        $output = ob_get_contents();
2667
-        ob_clean();
2668
-        $this->_context_switcher = $output;
2669
-    }
2670
-
2671
-
2672
-    /**
2673
-     * utility for sanitizing new values coming in.
2674
-     * Note: this is only used when updating a context.
2675
-     *
2676
-     * @access protected
2677
-     *
2678
-     * @param int $index This helps us know which template field to select from the request array.
2679
-     *
2680
-     * @return array
2681
-     */
2682
-    protected function _set_message_template_column_values($index)
2683
-    {
2684
-        if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2685
-            foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2686
-                $this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2687
-            }
2688
-        }
2689
-
2690
-
2691
-        $set_column_values = array(
2692
-            'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2693
-            'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2694
-            'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2695
-            'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2696
-            'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2697
-            'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2698
-            'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2699
-            'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2700
-            'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2701
-                ? absint($this->_req_data['MTP_is_global'])
2702
-                : 0,
2703
-            'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2704
-                ? absint($this->_req_data['MTP_is_override'])
2705
-                : 0,
2706
-            'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2707
-            'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2708
-        );
2709
-
2710
-
2711
-        return $set_column_values;
2712
-    }
2713
-
2714
-
2715
-    protected function _insert_or_update_message_template($new = false)
2716
-    {
2717
-
2718
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2719
-        $success = 0;
2720
-        $override = false;
2721
-
2722
-        // setup notices description
2723
-        $messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2724
-
2725
-        // need the message type and messenger objects to be able to use the labels for the notices
2726
-        $messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2727
-        $messenger_label = $messenger_object instanceof EE_messenger
2728
-            ? ucwords($messenger_object->label['singular'])
2729
-            : '';
2730
-
2731
-        $message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2732
-            ? $this->_req_data['MTP_message_type']
2733
-            : '';
2734
-        $message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2735
-
2736
-        $message_type_label = $message_type_object instanceof EE_message_type
2737
-            ? ucwords($message_type_object->label['singular'])
2738
-            : '';
2739
-
2740
-        $context_slug = ! empty($this->_req_data['MTP_context'])
2741
-            ? $this->_req_data['MTP_context']
2742
-            : '';
2743
-        $context = ucwords(str_replace('_', ' ', $context_slug));
2744
-
2745
-        $item_desc = $messenger_label && $message_type_label
2746
-            ? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2747
-            : '';
2748
-        $item_desc .= 'Message Template';
2749
-        $query_args = array();
2750
-        $edit_array = array();
2751
-        $action_desc = '';
2752
-
2753
-        // if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2754
-        // user to edit.
2755
-        if ($new) {
2756
-            $GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2757
-            if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2758
-                if (empty($edit_array)) {
2759
-                    $success = 0;
2760
-                } else {
2761
-                    $success = 1;
2762
-                    $edit_array = $edit_array[0];
2763
-                    $query_args = array(
2764
-                        'id'      => $edit_array['GRP_ID'],
2765
-                        'context' => $edit_array['MTP_context'],
2766
-                        'action'  => 'edit_message_template',
2767
-                    );
2768
-                }
2769
-            }
2770
-            $action_desc = 'created';
2771
-        } else {
2772
-            $MTPG = EEM_Message_Template_Group::instance();
2773
-            $MTP = EEM_Message_Template::instance();
2774
-
2775
-
2776
-            // run update for each template field in displayed context
2777
-            if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2778
-                EE_Error::add_error(
2779
-                    esc_html__(
2780
-                        'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2781
-                        'event_espresso'
2782
-                    ),
2783
-                    __FILE__,
2784
-                    __FUNCTION__,
2785
-                    __LINE__
2786
-                );
2787
-                $success = 0;
2788
-            } else {
2789
-                // first validate all fields!
2790
-                // this filter allows client code to add its own validation to the template fields as well.
2791
-                // returning an empty array means everything passed validation.
2792
-                // errors in validation should be represented in an array with the following shape:
2793
-                // array(
2794
-                //   'fieldname' => array(
2795
-                //          'msg' => 'error message'
2796
-                //          'value' => 'value for field producing error'
2797
-                // )
2798
-                $custom_validation = (array) apply_filters(
2799
-                    'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2800
-                    array(),
2801
-                    $this->_req_data['MTP_template_fields'],
2802
-                    $context_slug,
2803
-                    $messenger_slug,
2804
-                    $message_type_slug
2805
-                );
2806
-
2807
-                $system_validation = $MTPG->validate(
2808
-                    $this->_req_data['MTP_template_fields'],
2809
-                    $context_slug,
2810
-                    $messenger_slug,
2811
-                    $message_type_slug
2812
-                );
2813
-
2814
-                $system_validation = ! is_array($system_validation) && $system_validation ? array()
2815
-                    : $system_validation;
2816
-                $validates = array_merge($custom_validation, $system_validation);
2817
-
2818
-                // if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2819
-                // appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2820
-                //  WE need to make sure there is no actual error messages in validates.
2821
-                if (is_array($validates) && ! empty($validates)) {
2822
-                    // add the transient so when the form loads we know which fields to highlight
2823
-                    $this->_add_transient('edit_message_template', $validates);
2824
-
2825
-                    $success = 0;
2826
-
2827
-                    // setup notices
2828
-                    foreach ($validates as $field => $error) {
2829
-                        if (isset($error['msg'])) {
2830
-                            EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2831
-                        }
2832
-                    }
2833
-                } else {
2834
-                    $set_column_values = array();
2835
-                    foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2836
-                        $set_column_values = $this->_set_message_template_column_values($template_field);
2837
-
2838
-                        $where_cols_n_values = array(
2839
-                            'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2840
-                        );
2841
-                        // if they aren't allowed to use all JS, restrict them to just posty-y tags
2842
-                        if (! current_user_can('unfiltered_html')) {
2843
-                            if (is_array($set_column_values['MTP_content'])) {
2844
-                                foreach ($set_column_values['MTP_content'] as $key => $value) {
2845
-                                    // remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2846
-                                    // only removes slashes from double-quotes, so attributes using single quotes always
2847
-                                    // appear invalid.) But currently the models expect slashed data, so after wp_kses
2848
-                                    // runs we need to re-slash the data. Sheesh. See
2849
-                                    // https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2850
-                                    $set_column_values['MTP_content'][ $key ] = addslashes(
2851
-                                        wp_kses(
2852
-                                            stripslashes($value),
2853
-                                            wp_kses_allowed_html('post')
2854
-                                        )
2855
-                                    );
2856
-                                }
2857
-                            } else {
2858
-                                $set_column_values['MTP_content'] = wp_kses(
2859
-                                    $set_column_values['MTP_content'],
2860
-                                    wp_kses_allowed_html('post')
2861
-                                );
2862
-                            }
2863
-                        }
2864
-                        $message_template_fields = array(
2865
-                            'GRP_ID'             => $set_column_values['GRP_ID'],
2866
-                            'MTP_template_field' => $set_column_values['MTP_template_field'],
2867
-                            'MTP_context'        => $set_column_values['MTP_context'],
2868
-                            'MTP_content'        => $set_column_values['MTP_content'],
2869
-                        );
2870
-                        if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2871
-                            if ($updated === false) {
2872
-                                EE_Error::add_error(
2873
-                                    sprintf(
2874
-                                        esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2875
-                                        $template_field
2876
-                                    ),
2877
-                                    __FILE__,
2878
-                                    __FUNCTION__,
2879
-                                    __LINE__
2880
-                                );
2881
-                            } else {
2882
-                                $success = 1;
2883
-                            }
2884
-                        } else {
2885
-                            // only do this logic if we don't have a MTP_ID for this field
2886
-                            if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2887
-                                // this has already been through the template field validator and sanitized, so it will be
2888
-                                // safe to insert this field.  Why insert?  This typically happens when we introduce a new
2889
-                                // message template field in a messenger/message type and existing users don't have the
2890
-                                // default setup for it.
2891
-                                // @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2892
-                                $updated = $MTP->insert($message_template_fields);
2893
-                                if (! $updated || is_wp_error($updated)) {
2894
-                                    EE_Error::add_error(
2895
-                                        sprintf(
2896
-                                            esc_html__('%s field could not be updated.', 'event_espresso'),
2897
-                                            $template_field
2898
-                                        ),
2899
-                                        __FILE__,
2900
-                                        __FUNCTION__,
2901
-                                        __LINE__
2902
-                                    );
2903
-                                    $success = 0;
2904
-                                } else {
2905
-                                    $success = 1;
2906
-                                }
2907
-                            }
2908
-                        }
2909
-                        $action_desc = 'updated';
2910
-                    }
2911
-
2912
-                    // we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2913
-                    $mtpg_fields = array(
2914
-                        'MTP_user_id'      => $set_column_values['MTP_user_id'],
2915
-                        'MTP_messenger'    => $set_column_values['MTP_messenger'],
2916
-                        'MTP_message_type' => $set_column_values['MTP_message_type'],
2917
-                        'MTP_is_global'    => $set_column_values['MTP_is_global'],
2918
-                        'MTP_is_override'  => $set_column_values['MTP_is_override'],
2919
-                        'MTP_deleted'      => $set_column_values['MTP_deleted'],
2920
-                        'MTP_is_active'    => $set_column_values['MTP_is_active'],
2921
-                        'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2922
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2923
-                            : '',
2924
-                        'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2925
-                            ? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2926
-                            : '',
2927
-                    );
2928
-
2929
-                    $mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2930
-                    $updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2931
-
2932
-                    if ($updated === false) {
2933
-                        EE_Error::add_error(
2934
-                            sprintf(
2935
-                                esc_html__(
2936
-                                    'The Message Template Group (%d) was NOT updated for some reason',
2937
-                                    'event_espresso'
2938
-                                ),
2939
-                                $set_column_values['GRP_ID']
2940
-                            ),
2941
-                            __FILE__,
2942
-                            __FUNCTION__,
2943
-                            __LINE__
2944
-                        );
2945
-                    } else {
2946
-                        // k now we need to ensure the template_pack and template_variation fields are set.
2947
-                        $template_pack = ! empty($this->_req_data['MTP_template_pack'])
2948
-                            ? $this->_req_data['MTP_template_pack']
2949
-                            : 'default';
2950
-
2951
-                        $template_variation = ! empty($this->_req_data['MTP_template_variation'])
2952
-                            ? $this->_req_data['MTP_template_variation']
2953
-                            : 'default';
2954
-
2955
-                        $mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2956
-                        if ($mtpg_obj instanceof EE_Message_Template_Group) {
2957
-                            $mtpg_obj->set_template_pack_name($template_pack);
2958
-                            $mtpg_obj->set_template_pack_variation($template_variation);
2959
-                        }
2960
-                        $success = 1;
2961
-                    }
2962
-                }
2963
-            }
2964
-        }
2965
-
2966
-        // we return things differently if doing ajax
2967
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2968
-            $this->_template_args['success'] = $success;
2969
-            $this->_template_args['error'] = ! $success ? true : false;
2970
-            $this->_template_args['content'] = '';
2971
-            $this->_template_args['data'] = array(
2972
-                'grpID'        => $edit_array['GRP_ID'],
2973
-                'templateName' => $edit_array['template_name'],
2974
-            );
2975
-            if ($success) {
2976
-                EE_Error::overwrite_success();
2977
-                EE_Error::add_success(
2978
-                    esc_html__(
2979
-                        'The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2980
-                        'event_espresso'
2981
-                    )
2982
-                );
2983
-            }
2984
-
2985
-            $this->_return_json();
2986
-        }
2987
-
2988
-
2989
-        // was a test send triggered?
2990
-        if (isset($this->_req_data['test_button'])) {
2991
-            EE_Error::overwrite_success();
2992
-            $this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2993
-            $override = true;
2994
-        }
2995
-
2996
-        if (empty($query_args)) {
2997
-            $query_args = array(
2998
-                'id'      => $this->_req_data['GRP_ID'],
2999
-                'context' => $context_slug,
3000
-                'action'  => 'edit_message_template',
3001
-            );
3002
-        }
3003
-
3004
-        $this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
3005
-    }
3006
-
3007
-
3008
-    /**
3009
-     * processes a test send request to do an actual messenger delivery test for the given message template being tested
3010
-     *
3011
-     * @param  string $context      what context being tested
3012
-     * @param  string $messenger    messenger being tested
3013
-     * @param  string $message_type message type being tested
3014
-     * @throws EE_Error
3015
-     * @throws InvalidArgumentException
3016
-     * @throws InvalidDataTypeException
3017
-     * @throws InvalidInterfaceException
3018
-     */
3019
-    protected function _do_test_send($context, $messenger, $message_type)
3020
-    {
3021
-        // set things up for preview
3022
-        $this->_req_data['messenger'] = $messenger;
3023
-        $this->_req_data['message_type'] = $message_type;
3024
-        $this->_req_data['context'] = $context;
3025
-        $this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3026
-        $active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3027
-
3028
-        // let's save any existing fields that might be required by the messenger
3029
-        if (isset($this->_req_data['test_settings_fld'])
3030
-            && $active_messenger instanceof EE_messenger
3031
-            && apply_filters(
3032
-                'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3033
-                true,
3034
-                $this->_req_data['test_settings_fld'],
3035
-                $active_messenger
3036
-            )
3037
-        ) {
3038
-            $active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3039
-        }
3040
-
3041
-        /**
3042
-         * Use filter to add additional controls on whether message can send or not
3043
-         */
3044
-        if (apply_filters(
3045
-            'FHEE__Messages_Admin_Page__do_test_send__can_send',
3046
-            true,
3047
-            $context,
3048
-            $this->_req_data,
3049
-            $messenger,
3050
-            $message_type
3051
-        )) {
3052
-            if (EEM_Event::instance()->count() > 0) {
3053
-                $success = $this->_preview_message(true);
3054
-                if ($success) {
3055
-                    EE_Error::add_success(__('Test message sent', 'event_espresso'));
3056
-                } else {
3057
-                    EE_Error::add_error(
3058
-                        esc_html__('The test message was not sent', 'event_espresso'),
3059
-                        __FILE__,
3060
-                        __FUNCTION__,
3061
-                        __LINE__
3062
-                    );
3063
-                }
3064
-            } else {
3065
-                $this->noEventsErrorMessage(true);
3066
-            }
3067
-        }
3068
-    }
3069
-
3070
-
3071
-    /**
3072
-     * _generate_new_templates
3073
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3074
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3075
-     * for the event.
3076
-     *
3077
-     *
3078
-     * @param  string $messenger     the messenger we are generating templates for
3079
-     * @param array   $message_types array of message types that the templates are generated for.
3080
-     * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3081
-     *                               indicate the message_template_group being used as the base.
3082
-     *
3083
-     * @param bool    $global
3084
-     *
3085
-     * @return array|bool array of data required for the redirect to the correct edit page or bool if
3086
-     *                               encountering problems.
3087
-     * @throws EE_Error
3088
-     */
3089
-    protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3090
-    {
3091
-
3092
-        // if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3093
-        // just don't generate any templates.
3094
-        if (empty($message_types)) {
3095
-            return true;
3096
-        }
3097
-
3098
-        return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3099
-    }
3100
-
3101
-
3102
-    /**
3103
-     * [_trash_or_restore_message_template]
3104
-     *
3105
-     * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3106
-     * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3107
-     *                        an individual context (FALSE).
3108
-     * @return void
3109
-     * @throws EE_Error
3110
-     * @throws InvalidArgumentException
3111
-     * @throws InvalidDataTypeException
3112
-     * @throws InvalidInterfaceException
3113
-     */
3114
-    protected function _trash_or_restore_message_template($trash = true, $all = false)
3115
-    {
3116
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3117
-        $MTP = EEM_Message_Template_Group::instance();
3118
-
3119
-        $success = 1;
3120
-
3121
-        // incoming GRP_IDs
3122
-        if ($all) {
3123
-            // Checkboxes
3124
-            if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3125
-                // if array has more than one element then success message should be plural.
3126
-                // todo: what about nonce?
3127
-                $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3128
-
3129
-                // cycle through checkboxes
3130
-                while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3131
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3132
-                    if (! $trashed_or_restored) {
3133
-                        $success = 0;
3134
-                    }
3135
-                }
3136
-            } else {
3137
-                // grab single GRP_ID and handle
3138
-                $GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3139
-                if (! empty($GRP_ID)) {
3140
-                    $trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3141
-                    if (! $trashed_or_restored) {
3142
-                        $success = 0;
3143
-                    }
3144
-                } else {
3145
-                    $success = 0;
3146
-                }
3147
-            }
3148
-        }
3149
-
3150
-        $action_desc = $trash
3151
-            ? esc_html__('moved to the trash', 'event_espresso')
3152
-            : esc_html__('restored', 'event_espresso');
3153
-
3154
-        $action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3155
-
3156
-        $item_desc = $all ? _n(
3157
-            'Message Template Group',
3158
-            'Message Template Groups',
3159
-            $success,
3160
-            'event_espresso'
3161
-        ) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3162
-
3163
-        $item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3164
-            'template',
3165
-            'templates',
3166
-            $success,
3167
-            'event_espresso'
3168
-        ) : $item_desc;
3169
-
3170
-        $this->_redirect_after_action($success, $item_desc, $action_desc, array());
3171
-    }
3172
-
3173
-
3174
-    /**
3175
-     * [_delete_message_template]
3176
-     * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3177
-     *
3178
-     * @return void
3179
-     * @throws EE_Error
3180
-     * @throws InvalidArgumentException
3181
-     * @throws InvalidDataTypeException
3182
-     * @throws InvalidInterfaceException
3183
-     */
3184
-    protected function _delete_message_template()
3185
-    {
3186
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3187
-
3188
-        // checkboxes
3189
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3190
-            // if array has more than one element then success message should be plural
3191
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3192
-
3193
-            // cycle through bulk action checkboxes
3194
-            while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3195
-                $success = $this->_delete_mtp_permanently($GRP_ID);
3196
-            }
3197
-        } else {
3198
-            // grab single grp_id and delete
3199
-            $GRP_ID = absint($this->_req_data['id']);
3200
-            $success = $this->_delete_mtp_permanently($GRP_ID);
3201
-        }
3202
-
3203
-        $this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3204
-    }
3205
-
3206
-
3207
-    /**
3208
-     * helper for permanently deleting a mtP group and all related message_templates
3209
-     *
3210
-     * @param  int  $GRP_ID        The group being deleted
3211
-     * @param  bool $include_group whether to delete the Message Template Group as well.
3212
-     * @return bool boolean to indicate the success of the deletes or not.
3213
-     * @throws EE_Error
3214
-     * @throws InvalidArgumentException
3215
-     * @throws InvalidDataTypeException
3216
-     * @throws InvalidInterfaceException
3217
-     */
3218
-    private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3219
-    {
3220
-        $success = 1;
3221
-        $MTPG = EEM_Message_Template_Group::instance();
3222
-        // first let's GET this group
3223
-        $MTG = $MTPG->get_one_by_ID($GRP_ID);
3224
-        // then delete permanently all the related Message Templates
3225
-        $deleted = $MTG->delete_related_permanently('Message_Template');
3226
-
3227
-        if ($deleted === 0) {
3228
-            $success = 0;
3229
-        }
3230
-
3231
-        // now delete permanently this particular group
3232
-
3233
-        if ($include_group && ! $MTG->delete_permanently()) {
3234
-            $success = 0;
3235
-        }
3236
-
3237
-        return $success;
3238
-    }
3239
-
3240
-
3241
-    /**
3242
-     *    _learn_more_about_message_templates_link
3243
-     *
3244
-     * @access protected
3245
-     * @return string
3246
-     */
3247
-    protected function _learn_more_about_message_templates_link()
3248
-    {
3249
-        return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3250
-               . esc_html__('learn more about how message templates works', 'event_espresso')
3251
-               . '</a>';
3252
-    }
3253
-
3254
-
3255
-    /**
3256
-     * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3257
-     * ajax and other routes.
3258
-     *
3259
-     * @return void
3260
-     * @throws DomainException
3261
-     */
3262
-    protected function _settings()
3263
-    {
3264
-
3265
-
3266
-        $this->_set_m_mt_settings();
3267
-
3268
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3269
-            ? $this->_req_data['selected_messenger']
3270
-            : 'email';
3271
-
3272
-        // let's setup the messenger tabs
3273
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3274
-            $this->_m_mt_settings['messenger_tabs'],
3275
-            'messenger_links',
3276
-            '|',
3277
-            $selected_messenger
3278
-        );
3279
-        $this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3280
-        $this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3281
-
3282
-        $this->display_admin_page_with_sidebar();
3283
-    }
3284
-
3285
-
3286
-    /**
3287
-     * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3288
-     *
3289
-     * @access protected
3290
-     * @return void
3291
-     * @throws DomainException
3292
-     */
3293
-    protected function _set_m_mt_settings()
3294
-    {
3295
-        // first if this is already set then lets get out no need to regenerate data.
3296
-        if (! empty($this->_m_mt_settings)) {
3297
-            return;
3298
-        }
3299
-
3300
-        // get all installed messengers and message_types
3301
-        /** @type EE_messenger[] $messengers */
3302
-        $messengers = $this->_message_resource_manager->installed_messengers();
3303
-        /** @type EE_message_type[] $message_types */
3304
-        $message_types = $this->_message_resource_manager->installed_message_types();
3305
-
3306
-
3307
-        // assemble the array for the _tab_text_links helper
3308
-
3309
-        foreach ($messengers as $messenger) {
3310
-            $this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3311
-                'label' => ucwords($messenger->label['singular']),
3312
-                'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3313
-                    ? 'messenger-active'
3314
-                    : '',
3315
-                'href'  => $messenger->name,
3316
-                'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3317
-                'slug'  => $messenger->name,
3318
-                'obj'   => $messenger,
3319
-            );
3320
-
3321
-
3322
-            $message_types_for_messenger = $messenger->get_valid_message_types();
3323
-
3324
-            foreach ($message_types as $message_type) {
3325
-                // first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3326
-                // it shouldn't show in either the inactive OR active metabox.
3327
-                if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3328
-                    continue;
3329
-                }
3330
-
3331
-                $a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3332
-                    $messenger->name,
3333
-                    $message_type->name
3334
-                )
3335
-                    ? 'active'
3336
-                    : 'inactive';
3337
-
3338
-                $this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3339
-                    'label'    => ucwords($message_type->label['singular']),
3340
-                    'class'    => 'message-type-' . $a_or_i,
3341
-                    'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3342
-                    'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3343
-                    'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3344
-                    'title'    => $a_or_i === 'active'
3345
-                        ? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3346
-                        : esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3347
-                    'content'  => $a_or_i === 'active'
3348
-                        ? $this->_message_type_settings_content($message_type, $messenger, true)
3349
-                        : $this->_message_type_settings_content($message_type, $messenger),
3350
-                    'slug'     => $message_type->name,
3351
-                    'active'   => $a_or_i === 'active',
3352
-                    'obj'      => $message_type,
3353
-                );
3354
-            }
3355
-        }
3356
-    }
3357
-
3358
-
3359
-    /**
3360
-     * This just prepares the content for the message type settings
3361
-     *
3362
-     * @param  EE_message_type $message_type The message type object
3363
-     * @param  EE_messenger    $messenger    The messenger object
3364
-     * @param  boolean         $active       Whether the message type is active or not
3365
-     * @return string html output for the content
3366
-     * @throws DomainException
3367
-     */
3368
-    protected function _message_type_settings_content($message_type, $messenger, $active = false)
3369
-    {
3370
-        // get message type fields
3371
-        $fields = $message_type->get_admin_settings_fields();
3372
-        $settings_template_args['template_form_fields'] = '';
3373
-
3374
-        if (! empty($fields) && $active) {
3375
-            $existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3376
-            foreach ($fields as $fldname => $fldprops) {
3377
-                $field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3378
-                $template_form_field[ $field_id ] = array(
3379
-                    'name'       => 'message_type_settings[' . $fldname . ']',
3380
-                    'label'      => $fldprops['label'],
3381
-                    'input'      => $fldprops['field_type'],
3382
-                    'type'       => $fldprops['value_type'],
3383
-                    'required'   => $fldprops['required'],
3384
-                    'validation' => $fldprops['validation'],
3385
-                    'value'      => isset($existing_settings[ $fldname ])
3386
-                        ? $existing_settings[ $fldname ]
3387
-                        : $fldprops['default'],
3388
-                    'options'    => isset($fldprops['options'])
3389
-                        ? $fldprops['options']
3390
-                        : array(),
3391
-                    'default'    => isset($existing_settings[ $fldname ])
3392
-                        ? $existing_settings[ $fldname ]
3393
-                        : $fldprops['default'],
3394
-                    'css_class'  => 'no-drag',
3395
-                    'format'     => $fldprops['format'],
3396
-                );
3397
-            }
3398
-
3399
-
3400
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3401
-                ? $this->_generate_admin_form_fields(
3402
-                    $template_form_field,
3403
-                    'string',
3404
-                    'ee_mt_activate_form'
3405
-                )
3406
-                : '';
3407
-        }
3408
-
3409
-        $settings_template_args['description'] = $message_type->description;
3410
-        // we also need some hidden fields
3411
-        $settings_template_args['hidden_fields'] = array(
3412
-            'message_type_settings[messenger]'    => array(
3413
-                'type'  => 'hidden',
3414
-                'value' => $messenger->name,
3415
-            ),
3416
-            'message_type_settings[message_type]' => array(
3417
-                'type'  => 'hidden',
3418
-                'value' => $message_type->name,
3419
-            ),
3420
-            'type'                                => array(
3421
-                'type'  => 'hidden',
3422
-                'value' => 'message_type',
3423
-            ),
3424
-        );
3425
-
3426
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3427
-            $settings_template_args['hidden_fields'],
3428
-            'array'
3429
-        );
3430
-        $settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3431
-            ? ' hidden'
3432
-            : '';
3433
-
3434
-
3435
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3436
-        $content = EEH_Template::display_template($template, $settings_template_args, true);
3437
-
3438
-        return $content;
3439
-    }
3440
-
3441
-
3442
-    /**
3443
-     * Generate all the metaboxes for the message types and register them for the messages settings page.
3444
-     *
3445
-     * @access protected
3446
-     * @return void
3447
-     * @throws DomainException
3448
-     */
3449
-    protected function _messages_settings_metaboxes()
3450
-    {
3451
-        $this->_set_m_mt_settings();
3452
-        $m_boxes = $mt_boxes = array();
3453
-        $m_template_args = $mt_template_args = array();
3454
-
3455
-        $selected_messenger = isset($this->_req_data['selected_messenger'])
3456
-            ? $this->_req_data['selected_messenger']
3457
-            : 'email';
3458
-
3459
-        if (isset($this->_m_mt_settings['messenger_tabs'])) {
3460
-            foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3461
-                $hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3462
-                $hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3463
-                // messenger meta boxes
3464
-                $active = $selected_messenger === $messenger;
3465
-                $active_mt_tabs = isset(
3466
-                    $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3467
-                )
3468
-                    ? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3469
-                    : '';
3470
-                $m_boxes[ $messenger . '_a_box' ] = sprintf(
3471
-                    esc_html__('%s Settings', 'event_espresso'),
3472
-                    $tab_array['label']
3473
-                );
3474
-                $m_template_args[ $messenger . '_a_box' ] = array(
3475
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476
-                    'inactive_message_types' => isset(
3477
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
-                    )
3479
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
-                        : '',
3481
-                    'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3482
-                    'hidden'                 => $active ? '' : ' hidden',
3483
-                    'hide_on_message'        => $hide_on_message,
3484
-                    'messenger'              => $messenger,
3485
-                    'active'                 => $active,
3486
-                );
3487
-                // message type meta boxes
3488
-                // (which is really just the inactive container for each messenger
3489
-                // showing inactive message types for that messenger)
3490
-                $mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3491
-                $mt_template_args[ $messenger . '_i_box' ] = array(
3492
-                    'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3493
-                    'inactive_message_types' => isset(
3494
-                        $this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3495
-                    )
3496
-                        ? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3497
-                        : '',
3498
-                    'hidden'                 => $active ? '' : ' hidden',
3499
-                    'hide_on_message'        => $hide_on_message,
3500
-                    'hide_off_message'       => $hide_off_message,
3501
-                    'messenger'              => $messenger,
3502
-                    'active'                 => $active,
3503
-                );
3504
-            }
3505
-        }
3506
-
3507
-
3508
-        // register messenger metaboxes
3509
-        $m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3510
-        foreach ($m_boxes as $box => $label) {
3511
-            $callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3512
-            $msgr = str_replace('_a_box', '', $box);
3513
-            add_meta_box(
3514
-                'espresso_' . $msgr . '_settings',
3515
-                $label,
3516
-                function ($post, $metabox) {
3517
-                    echo EEH_Template::display_template(
3518
-                        $metabox["args"]["template_path"],
3519
-                        $metabox["args"]["template_args"],
3520
-                        true
3521
-                    );
3522
-                },
3523
-                $this->_current_screen->id,
3524
-                'normal',
3525
-                'high',
3526
-                $callback_args
3527
-            );
3528
-        }
3529
-
3530
-        // register message type metaboxes
3531
-        $mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3532
-        foreach ($mt_boxes as $box => $label) {
3533
-            $callback_args = array(
3534
-                'template_path' => $mt_template_path,
3535
-                'template_args' => $mt_template_args[ $box ],
3536
-            );
3537
-            $mt = str_replace('_i_box', '', $box);
3538
-            add_meta_box(
3539
-                'espresso_' . $mt . '_inactive_mts',
3540
-                $label,
3541
-                function ($post, $metabox) {
3542
-                    echo EEH_Template::display_template(
3543
-                        $metabox["args"]["template_path"],
3544
-                        $metabox["args"]["template_args"],
3545
-                        true
3546
-                    );
3547
-                },
3548
-                $this->_current_screen->id,
3549
-                'side',
3550
-                'high',
3551
-                $callback_args
3552
-            );
3553
-        }
3554
-
3555
-        // register metabox for global messages settings but only when on the main site.  On single site installs this
3556
-        // will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3557
-        if (is_main_site()) {
3558
-            add_meta_box(
3559
-                'espresso_global_message_settings',
3560
-                esc_html__('Global Message Settings', 'event_espresso'),
3561
-                array($this, 'global_messages_settings_metabox_content'),
3562
-                $this->_current_screen->id,
3563
-                'normal',
3564
-                'low',
3565
-                array()
3566
-            );
3567
-        }
3568
-    }
3569
-
3570
-
3571
-    /**
3572
-     *  This generates the content for the global messages settings metabox.
3573
-     *
3574
-     * @return string
3575
-     * @throws EE_Error
3576
-     * @throws InvalidArgumentException
3577
-     * @throws ReflectionException
3578
-     * @throws InvalidDataTypeException
3579
-     * @throws InvalidInterfaceException
3580
-     */
3581
-    public function global_messages_settings_metabox_content()
3582
-    {
3583
-        $form = $this->_generate_global_settings_form();
3584
-        echo $form->form_open(
3585
-            $this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3586
-            'POST'
3587
-        )
3588
-             . $form->get_html()
3589
-             . $form->form_close();
3590
-    }
3591
-
3592
-
3593
-    /**
3594
-     * This generates and returns the form object for the global messages settings.
3595
-     *
3596
-     * @return EE_Form_Section_Proper
3597
-     * @throws EE_Error
3598
-     * @throws InvalidArgumentException
3599
-     * @throws ReflectionException
3600
-     * @throws InvalidDataTypeException
3601
-     * @throws InvalidInterfaceException
3602
-     */
3603
-    protected function _generate_global_settings_form()
3604
-    {
3605
-        EE_Registry::instance()->load_helper('HTML');
3606
-        /** @var EE_Network_Core_Config $network_config */
3607
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3608
-
3609
-        return new EE_Form_Section_Proper(
3610
-            array(
3611
-                'name'            => 'global_messages_settings',
3612
-                'html_id'         => 'global_messages_settings',
3613
-                'html_class'      => 'form-table',
3614
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3615
-                'subsections'     => apply_filters(
3616
-                    'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3617
-                    array(
3618
-                        'do_messages_on_same_request' => new EE_Select_Input(
3619
-                            array(
3620
-                                true  => esc_html__("On the same request", "event_espresso"),
3621
-                                false => esc_html__("On a separate request", "event_espresso"),
3622
-                            ),
3623
-                            array(
3624
-                                'default'         => $network_config->do_messages_on_same_request,
3625
-                                'html_label_text' => esc_html__(
3626
-                                    'Generate and send all messages:',
3627
-                                    'event_espresso'
3628
-                                ),
3629
-                                'html_help_text'  => esc_html__(
3630
-                                    'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3631
-                                    'event_espresso'
3632
-                                ),
3633
-                            )
3634
-                        ),
3635
-                        'delete_threshold'            => new EE_Select_Input(
3636
-                            array(
3637
-                                0  => esc_html__('Forever', 'event_espresso'),
3638
-                                3  => esc_html__('3 Months', 'event_espresso'),
3639
-                                6  => esc_html__('6 Months', 'event_espresso'),
3640
-                                9  => esc_html__('9 Months', 'event_espresso'),
3641
-                                12 => esc_html__('12 Months', 'event_espresso'),
3642
-                                24 => esc_html__('24 Months', 'event_espresso'),
3643
-                                36 => esc_html__('36 Months', 'event_espresso'),
3644
-                            ),
3645
-                            array(
3646
-                                'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3647
-                                'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3648
-                                'html_help_text'  => esc_html__(
3649
-                                    'You can control how long a record of processed messages is kept via this option.',
3650
-                                    'event_espresso'
3651
-                                ),
3652
-                            )
3653
-                        ),
3654
-                        'update_settings'             => new EE_Submit_Input(
3655
-                            array(
3656
-                                'default'         => esc_html__('Update', 'event_espresso'),
3657
-                                'html_label_text' => '&nbsp',
3658
-                            )
3659
-                        ),
3660
-                    )
3661
-                ),
3662
-            )
3663
-        );
3664
-    }
3665
-
3666
-
3667
-    /**
3668
-     * This handles updating the global settings set on the admin page.
3669
-     *
3670
-     * @throws EE_Error
3671
-     * @throws InvalidDataTypeException
3672
-     * @throws InvalidInterfaceException
3673
-     * @throws InvalidArgumentException
3674
-     * @throws ReflectionException
3675
-     */
3676
-    protected function _update_global_settings()
3677
-    {
3678
-        /** @var EE_Network_Core_Config $network_config */
3679
-        $network_config = EE_Registry::instance()->NET_CFG->core;
3680
-        $messages_config = EE_Registry::instance()->CFG->messages;
3681
-        $form = $this->_generate_global_settings_form();
3682
-        if ($form->was_submitted()) {
3683
-            $form->receive_form_submission();
3684
-            if ($form->is_valid()) {
3685
-                $valid_data = $form->valid_data();
3686
-                foreach ($valid_data as $property => $value) {
3687
-                    $setter = 'set_' . $property;
3688
-                    if (method_exists($network_config, $setter)) {
3689
-                        $network_config->{$setter}($value);
3690
-                    } elseif (property_exists($network_config, $property)
3691
-                        && $network_config->{$property} !== $value
3692
-                    ) {
3693
-                        $network_config->{$property} = $value;
3694
-                    } elseif (property_exists($messages_config, $property)
3695
-                        && $messages_config->{$property} !== $value
3696
-                    ) {
3697
-                        $messages_config->{$property} = $value;
3698
-                    }
3699
-                }
3700
-                // only update if the form submission was valid!
3701
-                EE_Registry::instance()->NET_CFG->update_config(true, false);
3702
-                EE_Registry::instance()->CFG->update_espresso_config();
3703
-                EE_Error::overwrite_success();
3704
-                EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3705
-            }
3706
-        }
3707
-        $this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3708
-    }
3709
-
3710
-
3711
-    /**
3712
-     * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3713
-     *
3714
-     * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3715
-     * @return string html formatted tabs
3716
-     * @throws DomainException
3717
-     */
3718
-    protected function _get_mt_tabs($tab_array)
3719
-    {
3720
-        $tab_array = (array) $tab_array;
3721
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3722
-        $tabs = '';
3723
-
3724
-        foreach ($tab_array as $tab) {
3725
-            $tabs .= EEH_Template::display_template($template, $tab, true);
3726
-        }
3727
-
3728
-        return $tabs;
3729
-    }
3730
-
3731
-
3732
-    /**
3733
-     * This prepares the content of the messenger meta box admin settings
3734
-     *
3735
-     * @param  EE_messenger $messenger The messenger we're setting up content for
3736
-     * @return string html formatted content
3737
-     * @throws DomainException
3738
-     */
3739
-    protected function _get_messenger_box_content(EE_messenger $messenger)
3740
-    {
3741
-
3742
-        $fields = $messenger->get_admin_settings_fields();
3743
-        $settings_template_args['template_form_fields'] = '';
3744
-
3745
-        // is $messenger active?
3746
-        $settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3747
-
3748
-
3749
-        if (! empty($fields)) {
3750
-            $existing_settings = $messenger->get_existing_admin_settings();
3751
-
3752
-            foreach ($fields as $fldname => $fldprops) {
3753
-                $field_id = $messenger->name . '-' . $fldname;
3754
-                $template_form_field[ $field_id ] = array(
3755
-                    'name'       => 'messenger_settings[' . $field_id . ']',
3756
-                    'label'      => $fldprops['label'],
3757
-                    'input'      => $fldprops['field_type'],
3758
-                    'type'       => $fldprops['value_type'],
3759
-                    'required'   => $fldprops['required'],
3760
-                    'validation' => $fldprops['validation'],
3761
-                    'value'      => isset($existing_settings[ $field_id ])
3762
-                        ? $existing_settings[ $field_id ]
3763
-                        : $fldprops['default'],
3764
-                    'css_class'  => '',
3765
-                    'format'     => $fldprops['format'],
3766
-                );
3767
-            }
3768
-
3769
-
3770
-            $settings_template_args['template_form_fields'] = ! empty($template_form_field)
3771
-                ? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3772
-                : '';
3773
-        }
3774
-
3775
-        // we also need some hidden fields
3776
-        $settings_template_args['hidden_fields'] = array(
3777
-            'messenger_settings[messenger]' => array(
3778
-                'type'  => 'hidden',
3779
-                'value' => $messenger->name,
3780
-            ),
3781
-            'type'                          => array(
3782
-                'type'  => 'hidden',
3783
-                'value' => 'messenger',
3784
-            ),
3785
-        );
3786
-
3787
-        // make sure any active message types that are existing are included in the hidden fields
3788
-        if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3789
-            foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3790
-                $settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3791
-                    'type'  => 'hidden',
3792
-                    'value' => $mt,
3793
-                );
3794
-            }
3795
-        }
3796
-        $settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3797
-            $settings_template_args['hidden_fields'],
3798
-            'array'
3799
-        );
3800
-        $active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3801
-
3802
-        $settings_template_args['messenger'] = $messenger->name;
3803
-        $settings_template_args['description'] = $messenger->description;
3804
-        $settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3805
-
3806
-
3807
-        $settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3808
-            $messenger->name
3809
-        )
3810
-            ? $settings_template_args['show_hide_edit_form']
3811
-            : ' hidden';
3812
-
3813
-        $settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3814
-            ? ' hidden'
3815
-            : $settings_template_args['show_hide_edit_form'];
3816
-
3817
-
3818
-        $settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3819
-        $settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3820
-        $settings_template_args['on_off_status'] = $active ? true : false;
3821
-        $template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3822
-        $content = EEH_Template::display_template(
3823
-            $template,
3824
-            $settings_template_args,
3825
-            true
3826
-        );
3827
-
3828
-        return $content;
3829
-    }
3830
-
3831
-
3832
-    /**
3833
-     * used by ajax on the messages settings page to activate|deactivate the messenger
3834
-     *
3835
-     * @throws DomainException
3836
-     * @throws EE_Error
3837
-     * @throws InvalidDataTypeException
3838
-     * @throws InvalidInterfaceException
3839
-     * @throws InvalidArgumentException
3840
-     * @throws ReflectionException
3841
-     */
3842
-    public function activate_messenger_toggle()
3843
-    {
3844
-        $success = true;
3845
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3846
-        // let's check that we have required data
3847
-        if (! isset($this->_req_data['messenger'])) {
3848
-            EE_Error::add_error(
3849
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3850
-                __FILE__,
3851
-                __FUNCTION__,
3852
-                __LINE__
3853
-            );
3854
-            $success = false;
3855
-        }
3856
-
3857
-        // do a nonce check here since we're not arriving via a normal route
3858
-        $nonce = isset($this->_req_data['activate_nonce'])
3859
-            ? sanitize_text_field($this->_req_data['activate_nonce'])
3860
-            : '';
3861
-        $nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3862
-
3863
-        $this->_verify_nonce($nonce, $nonce_ref);
3864
-
3865
-
3866
-        if (! isset($this->_req_data['status'])) {
3867
-            EE_Error::add_error(
3868
-                esc_html__(
3869
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3870
-                    'event_espresso'
3871
-                ),
3872
-                __FILE__,
3873
-                __FUNCTION__,
3874
-                __LINE__
3875
-            );
3876
-            $success = false;
3877
-        }
3878
-
3879
-        // do check to verify we have a valid status.
3880
-        $status = $this->_req_data['status'];
3881
-
3882
-        if ($status !== 'off' && $status !== 'on') {
3883
-            EE_Error::add_error(
3884
-                sprintf(
3885
-                    esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3886
-                    $this->_req_data['status']
3887
-                ),
3888
-                __FILE__,
3889
-                __FUNCTION__,
3890
-                __LINE__
3891
-            );
3892
-            $success = false;
3893
-        }
3894
-
3895
-        if ($success) {
3896
-            // made it here?  Stop dawdling then!!
3897
-            $success = $status === 'off'
3898
-                ? $this->_deactivate_messenger($this->_req_data['messenger'])
3899
-                : $this->_activate_messenger($this->_req_data['messenger']);
3900
-        }
3901
-
3902
-        $this->_template_args['success'] = $success;
3903
-
3904
-        // no special instructions so let's just do the json return (which should automatically do all the special stuff).
3905
-        $this->_return_json();
3906
-    }
3907
-
3908
-
3909
-    /**
3910
-     * used by ajax from the messages settings page to activate|deactivate a message type
3911
-     *
3912
-     * @throws DomainException
3913
-     * @throws EE_Error
3914
-     * @throws ReflectionException
3915
-     * @throws InvalidDataTypeException
3916
-     * @throws InvalidInterfaceException
3917
-     * @throws InvalidArgumentException
3918
-     */
3919
-    public function activate_mt_toggle()
3920
-    {
3921
-        $success = true;
3922
-        $this->_prep_default_response_for_messenger_or_message_type_toggle();
3923
-
3924
-        // let's make sure we have the necessary data
3925
-        if (! isset($this->_req_data['message_type'])) {
3926
-            EE_Error::add_error(
3927
-                esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3928
-                __FILE__,
3929
-                __FUNCTION__,
3930
-                __LINE__
3931
-            );
3932
-            $success = false;
3933
-        }
3934
-
3935
-        if (! isset($this->_req_data['messenger'])) {
3936
-            EE_Error::add_error(
3937
-                esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3938
-                __FILE__,
3939
-                __FUNCTION__,
3940
-                __LINE__
3941
-            );
3942
-            $success = false;
3943
-        }
3944
-
3945
-        if (! isset($this->_req_data['status'])) {
3946
-            EE_Error::add_error(
3947
-                esc_html__(
3948
-                    'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3949
-                    'event_espresso'
3950
-                ),
3951
-                __FILE__,
3952
-                __FUNCTION__,
3953
-                __LINE__
3954
-            );
3955
-            $success = false;
3956
-        }
3957
-
3958
-
3959
-        // do check to verify we have a valid status.
3960
-        $status = $this->_req_data['status'];
3961
-
3962
-        if ($status !== 'activate' && $status !== 'deactivate') {
3963
-            EE_Error::add_error(
3964
-                sprintf(
3965
-                    esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3966
-                    $this->_req_data['status']
3967
-                ),
3968
-                __FILE__,
3969
-                __FUNCTION__,
3970
-                __LINE__
3971
-            );
3972
-            $success = false;
3973
-        }
3974
-
3975
-
3976
-        // do a nonce check here since we're not arriving via a normal route
3977
-        $nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3978
-        $nonce_ref = $this->_req_data['message_type'] . '_nonce';
3979
-
3980
-        $this->_verify_nonce($nonce, $nonce_ref);
3981
-
3982
-        if ($success) {
3983
-            // made it here? um, what are you waiting for then?
3984
-            $success = $status === 'deactivate'
3985
-                ? $this->_deactivate_message_type_for_messenger(
3986
-                    $this->_req_data['messenger'],
3987
-                    $this->_req_data['message_type']
3988
-                )
3989
-                : $this->_activate_message_type_for_messenger(
3990
-                    $this->_req_data['messenger'],
3991
-                    $this->_req_data['message_type']
3992
-                );
3993
-        }
3994
-
3995
-        $this->_template_args['success'] = $success;
3996
-        $this->_return_json();
3997
-    }
3998
-
3999
-
4000
-    /**
4001
-     * Takes care of processing activating a messenger and preparing the appropriate response.
4002
-     *
4003
-     * @param string $messenger_name The name of the messenger being activated
4004
-     * @return bool
4005
-     * @throws DomainException
4006
-     * @throws EE_Error
4007
-     * @throws InvalidArgumentException
4008
-     * @throws ReflectionException
4009
-     * @throws InvalidDataTypeException
4010
-     * @throws InvalidInterfaceException
4011
-     */
4012
-    protected function _activate_messenger($messenger_name)
4013
-    {
4014
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4015
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4016
-        $message_types_to_activate = $active_messenger instanceof EE_Messenger
4017
-            ? $active_messenger->get_default_message_types()
4018
-            : array();
4019
-
4020
-        // ensure is active
4021
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
4022
-
4023
-        // set response_data for reload
4024
-        foreach ($message_types_to_activate as $message_type_name) {
4025
-            /** @var EE_message_type $message_type */
4026
-            $message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4027
-            if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4028
-                $messenger_name,
4029
-                $message_type_name
4030
-            )
4031
-                && $message_type instanceof EE_message_type
4032
-            ) {
4033
-                $this->_template_args['data']['active_mts'][] = $message_type_name;
4034
-                if ($message_type->get_admin_settings_fields()) {
4035
-                    $this->_template_args['data']['mt_reload'][] = $message_type_name;
4036
-                }
4037
-            }
4038
-        }
4039
-
4040
-        // add success message for activating messenger
4041
-        return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4042
-    }
4043
-
4044
-
4045
-    /**
4046
-     * Takes care of processing deactivating a messenger and preparing the appropriate response.
4047
-     *
4048
-     * @param string $messenger_name The name of the messenger being activated
4049
-     * @return bool
4050
-     * @throws DomainException
4051
-     * @throws EE_Error
4052
-     * @throws InvalidArgumentException
4053
-     * @throws ReflectionException
4054
-     * @throws InvalidDataTypeException
4055
-     * @throws InvalidInterfaceException
4056
-     */
4057
-    protected function _deactivate_messenger($messenger_name)
4058
-    {
4059
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4060
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4061
-        $this->_message_resource_manager->deactivate_messenger($messenger_name);
4062
-
4063
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4064
-    }
4065
-
4066
-
4067
-    /**
4068
-     * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4069
-     *
4070
-     * @param string $messenger_name    The name of the messenger the message type is being activated for.
4071
-     * @param string $message_type_name The name of the message type being activated for the messenger
4072
-     * @return bool
4073
-     * @throws DomainException
4074
-     * @throws EE_Error
4075
-     * @throws InvalidArgumentException
4076
-     * @throws ReflectionException
4077
-     * @throws InvalidDataTypeException
4078
-     * @throws InvalidInterfaceException
4079
-     */
4080
-    protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4081
-    {
4082
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4083
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4084
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4085
-        $message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4086
-
4087
-        // ensure is active
4088
-        $this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4089
-
4090
-        // set response for load
4091
-        if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4092
-            $messenger_name,
4093
-            $message_type_name
4094
-        )
4095
-        ) {
4096
-            $this->_template_args['data']['active_mts'][] = $message_type_name;
4097
-            if ($message_type_to_activate->get_admin_settings_fields()) {
4098
-                $this->_template_args['data']['mt_reload'][] = $message_type_name;
4099
-            }
4100
-        }
4101
-
4102
-        return $this->_setup_response_message_for_activating_messenger_with_message_types(
4103
-            $active_messenger,
4104
-            $message_type_to_activate
4105
-        );
4106
-    }
4107
-
4108
-
4109
-    /**
4110
-     * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4111
-     *
4112
-     * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4113
-     * @param string $message_type_name The name of the message type being deactivated for the messenger
4114
-     * @return bool
4115
-     * @throws DomainException
4116
-     * @throws EE_Error
4117
-     * @throws InvalidArgumentException
4118
-     * @throws ReflectionException
4119
-     * @throws InvalidDataTypeException
4120
-     * @throws InvalidInterfaceException
4121
-     */
4122
-    protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4123
-    {
4124
-        /** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4125
-        $active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4126
-        /** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4127
-        $message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4128
-        $this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4129
-
4130
-        return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4131
-            $active_messenger,
4132
-            $message_type_to_deactivate
4133
-        );
4134
-    }
4135
-
4136
-
4137
-    /**
4138
-     * This just initializes the defaults for activating messenger and message type responses.
4139
-     */
4140
-    protected function _prep_default_response_for_messenger_or_message_type_toggle()
4141
-    {
4142
-        $this->_template_args['data']['active_mts'] = array();
4143
-        $this->_template_args['data']['mt_reload'] = array();
4144
-    }
4145
-
4146
-
4147
-    /**
4148
-     * Setup appropriate response for activating a messenger and/or message types
4149
-     *
4150
-     * @param EE_messenger         $messenger
4151
-     * @param EE_message_type|null $message_type
4152
-     * @return bool
4153
-     * @throws DomainException
4154
-     * @throws EE_Error
4155
-     * @throws InvalidArgumentException
4156
-     * @throws ReflectionException
4157
-     * @throws InvalidDataTypeException
4158
-     * @throws InvalidInterfaceException
4159
-     */
4160
-    protected function _setup_response_message_for_activating_messenger_with_message_types(
4161
-        $messenger,
4162
-        EE_Message_Type $message_type = null
4163
-    ) {
4164
-        // if $messenger isn't a valid messenger object then get out.
4165
-        if (! $messenger instanceof EE_Messenger) {
4166
-            EE_Error::add_error(
4167
-                esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4168
-                __FILE__,
4169
-                __FUNCTION__,
4170
-                __LINE__
4171
-            );
4172
-
4173
-            return false;
4174
-        }
4175
-        // activated
4176
-        if ($this->_template_args['data']['active_mts']) {
4177
-            EE_Error::overwrite_success();
4178
-            // activated a message type with the messenger
4179
-            if ($message_type instanceof EE_message_type) {
4180
-                EE_Error::add_success(
4181
-                    sprintf(
4182
-                        esc_html__(
4183
-                            '%s message type has been successfully activated with the %s messenger',
4184
-                            'event_espresso'
4185
-                        ),
4186
-                        ucwords($message_type->label['singular']),
4187
-                        ucwords($messenger->label['singular'])
4188
-                    )
4189
-                );
4190
-
4191
-                // if message type was invoice then let's make sure we activate the invoice payment method.
4192
-                if ($message_type->name === 'invoice') {
4193
-                    EE_Registry::instance()->load_lib('Payment_Method_Manager');
4194
-                    $pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4195
-                    if ($pm instanceof EE_Payment_Method) {
4196
-                        EE_Error::add_attention(
4197
-                            esc_html__(
4198
-                                'Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
4199
-                                'event_espresso'
4200
-                            )
4201
-                        );
4202
-                    }
4203
-                }
4204
-                // just toggles the entire messenger
4205
-            } else {
4206
-                EE_Error::add_success(
4207
-                    sprintf(
4208
-                        esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4209
-                        ucwords($messenger->label['singular'])
4210
-                    )
4211
-                );
4212
-            }
4213
-
4214
-            return true;
4215
-
4216
-            // possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4217
-            // message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4218
-            // in which case we just give a success message for the messenger being successfully activated.
4219
-        } else {
4220
-            if (! $messenger->get_default_message_types()) {
4221
-                // messenger doesn't have any default message types so still a success.
4222
-                EE_Error::add_success(
4223
-                    sprintf(
4224
-                        esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4225
-                        ucwords($messenger->label['singular'])
4226
-                    )
4227
-                );
4228
-
4229
-                return true;
4230
-            } else {
4231
-                EE_Error::add_error(
4232
-                    $message_type instanceof EE_message_type
4233
-                        ? sprintf(
4234
-                            esc_html__(
4235
-                                '%s message type was not successfully activated with the %s messenger',
4236
-                                'event_espresso'
4237
-                            ),
4238
-                            ucwords($message_type->label['singular']),
4239
-                            ucwords($messenger->label['singular'])
4240
-                        )
4241
-                        : sprintf(
4242
-                            esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4243
-                            ucwords($messenger->label['singular'])
4244
-                        ),
4245
-                    __FILE__,
4246
-                    __FUNCTION__,
4247
-                    __LINE__
4248
-                );
4249
-
4250
-                return false;
4251
-            }
4252
-        }
4253
-    }
4254
-
4255
-
4256
-    /**
4257
-     * This sets up the appropriate response for deactivating a messenger and/or message type.
4258
-     *
4259
-     * @param EE_messenger         $messenger
4260
-     * @param EE_message_type|null $message_type
4261
-     * @return bool
4262
-     * @throws DomainException
4263
-     * @throws EE_Error
4264
-     * @throws InvalidArgumentException
4265
-     * @throws ReflectionException
4266
-     * @throws InvalidDataTypeException
4267
-     * @throws InvalidInterfaceException
4268
-     */
4269
-    protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4270
-        $messenger,
4271
-        EE_message_type $message_type = null
4272
-    ) {
4273
-        EE_Error::overwrite_success();
4274
-
4275
-        // if $messenger isn't a valid messenger object then get out.
4276
-        if (! $messenger instanceof EE_Messenger) {
4277
-            EE_Error::add_error(
4278
-                esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4279
-                __FILE__,
4280
-                __FUNCTION__,
4281
-                __LINE__
4282
-            );
4283
-
4284
-            return false;
4285
-        }
4286
-
4287
-        if ($message_type instanceof EE_message_type) {
4288
-            $message_type_name = $message_type->name;
4289
-            EE_Error::add_success(
4290
-                sprintf(
4291
-                    esc_html__(
4292
-                        '%s message type has been successfully deactivated for the %s messenger.',
4293
-                        'event_espresso'
4294
-                    ),
4295
-                    ucwords($message_type->label['singular']),
4296
-                    ucwords($messenger->label['singular'])
4297
-                )
4298
-            );
4299
-        } else {
4300
-            $message_type_name = '';
4301
-            EE_Error::add_success(
4302
-                sprintf(
4303
-                    esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4304
-                    ucwords($messenger->label['singular'])
4305
-                )
4306
-            );
4307
-        }
4308
-
4309
-        // if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4310
-        if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4311
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
4312
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4313
-            if ($count_updated > 0) {
4314
-                $msg = $message_type_name === 'invoice'
4315
-                    ? esc_html__(
4316
-                        'Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
4317
-                        'event_espresso'
4318
-                    )
4319
-                    : esc_html__(
4320
-                        'Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
4321
-                        'event_espresso'
4322
-                    );
4323
-                EE_Error::add_attention($msg);
4324
-            }
4325
-        }
4326
-
4327
-        return true;
4328
-    }
4329
-
4330
-
4331
-    /**
4332
-     * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4333
-     *
4334
-     * @throws DomainException
4335
-     */
4336
-    public function update_mt_form()
4337
-    {
4338
-        if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4339
-            EE_Error::add_error(
4340
-                esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4341
-                __FILE__,
4342
-                __FUNCTION__,
4343
-                __LINE__
4344
-            );
4345
-            $this->_return_json();
4346
-        }
4347
-
4348
-        $message_types = $this->get_installed_message_types();
4349
-
4350
-        $message_type = $message_types[ $this->_req_data['message_type'] ];
4351
-        $messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4352
-
4353
-        $content = $this->_message_type_settings_content(
4354
-            $message_type,
4355
-            $messenger,
4356
-            true
4357
-        );
4358
-        $this->_template_args['success'] = true;
4359
-        $this->_template_args['content'] = $content;
4360
-        $this->_return_json();
4361
-    }
4362
-
4363
-
4364
-    /**
4365
-     * this handles saving the settings for a messenger or message type
4366
-     *
4367
-     */
4368
-    public function save_settings()
4369
-    {
4370
-        if (! isset($this->_req_data['type'])) {
4371
-            EE_Error::add_error(
4372
-                esc_html__(
4373
-                    'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4374
-                    'event_espresso'
4375
-                ),
4376
-                __FILE__,
4377
-                __FUNCTION__,
4378
-                __LINE__
4379
-            );
4380
-            $this->_template_args['error'] = true;
4381
-            $this->_return_json();
4382
-        }
4383
-
4384
-
4385
-        if ($this->_req_data['type'] === 'messenger') {
4386
-            // this should be an array.
4387
-            $settings = $this->_req_data['messenger_settings'];
4388
-            $messenger = $settings['messenger'];
4389
-            // let's setup the settings data
4390
-            foreach ($settings as $key => $value) {
4391
-                switch ($key) {
4392
-                    case 'messenger':
4393
-                        unset($settings['messenger']);
4394
-                        break;
4395
-                    case 'message_types':
4396
-                        unset($settings['message_types']);
4397
-                        break;
4398
-                    default:
4399
-                        $settings[ $key ] = $value;
4400
-                        break;
4401
-                }
4402
-            }
4403
-            $this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4404
-        } elseif ($this->_req_data['type'] === 'message_type') {
4405
-            $settings = $this->_req_data['message_type_settings'];
4406
-            $messenger = $settings['messenger'];
4407
-            $message_type = $settings['message_type'];
4408
-
4409
-            foreach ($settings as $key => $value) {
4410
-                switch ($key) {
4411
-                    case 'messenger':
4412
-                        unset($settings['messenger']);
4413
-                        break;
4414
-                    case 'message_type':
4415
-                        unset($settings['message_type']);
4416
-                        break;
4417
-                    default:
4418
-                        $settings[ $key ] = $value;
4419
-                        break;
4420
-                }
4421
-            }
4422
-
4423
-            $this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4424
-        }
4425
-
4426
-        // okay we should have the data all setup.  Now we just update!
4427
-        $success = $this->_message_resource_manager->update_active_messengers_option();
4428
-
4429
-        if ($success) {
4430
-            EE_Error::add_success(__('Settings updated', 'event_espresso'));
4431
-        } else {
4432
-            EE_Error::add_error(
4433
-                esc_html__(
4434
-                    'Settings did not get updated',
4435
-                    'event_espresso'
4436
-                ),
4437
-                __FILE__,
4438
-                __FUNCTION__,
4439
-                __LINE__
4440
-            );
4441
-        }
4442
-
4443
-        $this->_template_args['success'] = $success;
4444
-        $this->_return_json();
4445
-    }
4446
-
4447
-
4448
-
4449
-
4450
-    /**  EE MESSAGE PROCESSING ACTIONS **/
4451
-
4452
-
4453
-    /**
4454
-     * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4455
-     * However, this does not send immediately, it just queues for sending.
4456
-     *
4457
-     * @since 4.9.0
4458
-     * @throws EE_Error
4459
-     * @throws InvalidDataTypeException
4460
-     * @throws InvalidInterfaceException
4461
-     * @throws InvalidArgumentException
4462
-     * @throws ReflectionException
4463
-     */
4464
-    protected function _generate_now()
4465
-    {
4466
-        EED_Messages::generate_now($this->_get_msg_ids_from_request());
4467
-        $this->_redirect_after_action(false, '', '', array(), true);
4468
-    }
4469
-
4470
-
4471
-    /**
4472
-     * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4473
-     * are EEM_Message::status_resend or EEM_Message::status_idle
4474
-     *
4475
-     * @since 4.9.0
4476
-     * @throws EE_Error
4477
-     * @throws InvalidDataTypeException
4478
-     * @throws InvalidInterfaceException
4479
-     * @throws InvalidArgumentException
4480
-     * @throws ReflectionException
4481
-     */
4482
-    protected function _generate_and_send_now()
4483
-    {
4484
-        EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4485
-        $this->_redirect_after_action(false, '', '', array(), true);
4486
-    }
4487
-
4488
-
4489
-    /**
4490
-     * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4491
-     *
4492
-     * @since 4.9.0
4493
-     * @throws EE_Error
4494
-     * @throws InvalidDataTypeException
4495
-     * @throws InvalidInterfaceException
4496
-     * @throws InvalidArgumentException
4497
-     * @throws ReflectionException
4498
-     */
4499
-    protected function _queue_for_resending()
4500
-    {
4501
-        EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4502
-        $this->_redirect_after_action(false, '', '', array(), true);
4503
-    }
4504
-
4505
-
4506
-    /**
4507
-     *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4508
-     *
4509
-     * @since 4.9.0
4510
-     * @throws EE_Error
4511
-     * @throws InvalidDataTypeException
4512
-     * @throws InvalidInterfaceException
4513
-     * @throws InvalidArgumentException
4514
-     * @throws ReflectionException
4515
-     */
4516
-    protected function _send_now()
4517
-    {
4518
-        EED_Messages::send_now($this->_get_msg_ids_from_request());
4519
-        $this->_redirect_after_action(false, '', '', array(), true);
4520
-    }
4521
-
4522
-
4523
-    /**
4524
-     * Deletes EE_messages for IDs in the request.
4525
-     *
4526
-     * @since 4.9.0
4527
-     * @throws EE_Error
4528
-     * @throws InvalidDataTypeException
4529
-     * @throws InvalidInterfaceException
4530
-     * @throws InvalidArgumentException
4531
-     */
4532
-    protected function _delete_ee_messages()
4533
-    {
4534
-        $msg_ids = $this->_get_msg_ids_from_request();
4535
-        $deleted_count = 0;
4536
-        foreach ($msg_ids as $msg_id) {
4537
-            if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4538
-                $deleted_count++;
4539
-            }
4540
-        }
4541
-        if ($deleted_count) {
4542
-            EE_Error::add_success(
4543
-                esc_html(
4544
-                    _n(
4545
-                        'Message successfully deleted',
4546
-                        'Messages successfully deleted',
4547
-                        $deleted_count,
4548
-                        'event_espresso'
4549
-                    )
4550
-                )
4551
-            );
4552
-            $this->_redirect_after_action(
4553
-                false,
4554
-                '',
4555
-                '',
4556
-                array(),
4557
-                true
4558
-            );
4559
-        } else {
4560
-            EE_Error::add_error(
4561
-                _n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4562
-                __FILE__,
4563
-                __FUNCTION__,
4564
-                __LINE__
4565
-            );
4566
-            $this->_redirect_after_action(false, '', '', array(), true);
4567
-        }
4568
-    }
4569
-
4570
-
4571
-    /**
4572
-     *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4573
-     *
4574
-     * @since 4.9.0
4575
-     * @return array
4576
-     */
4577
-    protected function _get_msg_ids_from_request()
4578
-    {
4579
-        if (! isset($this->_req_data['MSG_ID'])) {
4580
-            return array();
4581
-        }
4582
-
4583
-        return is_array($this->_req_data['MSG_ID'])
4584
-            ? array_keys($this->_req_data['MSG_ID'])
4585
-            : array($this->_req_data['MSG_ID']);
4586
-    }
2666
+		$output = ob_get_contents();
2667
+		ob_clean();
2668
+		$this->_context_switcher = $output;
2669
+	}
2670
+
2671
+
2672
+	/**
2673
+	 * utility for sanitizing new values coming in.
2674
+	 * Note: this is only used when updating a context.
2675
+	 *
2676
+	 * @access protected
2677
+	 *
2678
+	 * @param int $index This helps us know which template field to select from the request array.
2679
+	 *
2680
+	 * @return array
2681
+	 */
2682
+	protected function _set_message_template_column_values($index)
2683
+	{
2684
+		if (is_array($this->_req_data['MTP_template_fields'][ $index ]['content'])) {
2685
+			foreach ($this->_req_data['MTP_template_fields'][ $index ]['content'] as $field => $value) {
2686
+				$this->_req_data['MTP_template_fields'][ $index ]['content'][ $field ] = $value;
2687
+			}
2688
+		}
2689
+
2690
+
2691
+		$set_column_values = array(
2692
+			'MTP_ID'             => absint($this->_req_data['MTP_template_fields'][ $index ]['MTP_ID']),
2693
+			'GRP_ID'             => absint($this->_req_data['GRP_ID']),
2694
+			'MTP_user_id'        => absint($this->_req_data['MTP_user_id']),
2695
+			'MTP_messenger'      => strtolower($this->_req_data['MTP_messenger']),
2696
+			'MTP_message_type'   => strtolower($this->_req_data['MTP_message_type']),
2697
+			'MTP_template_field' => strtolower($this->_req_data['MTP_template_fields'][ $index ]['name']),
2698
+			'MTP_context'        => strtolower($this->_req_data['MTP_context']),
2699
+			'MTP_content'        => $this->_req_data['MTP_template_fields'][ $index ]['content'],
2700
+			'MTP_is_global'      => isset($this->_req_data['MTP_is_global'])
2701
+				? absint($this->_req_data['MTP_is_global'])
2702
+				: 0,
2703
+			'MTP_is_override'    => isset($this->_req_data['MTP_is_override'])
2704
+				? absint($this->_req_data['MTP_is_override'])
2705
+				: 0,
2706
+			'MTP_deleted'        => absint($this->_req_data['MTP_deleted']),
2707
+			'MTP_is_active'      => absint($this->_req_data['MTP_is_active']),
2708
+		);
2709
+
2710
+
2711
+		return $set_column_values;
2712
+	}
2713
+
2714
+
2715
+	protected function _insert_or_update_message_template($new = false)
2716
+	{
2717
+
2718
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2719
+		$success = 0;
2720
+		$override = false;
2721
+
2722
+		// setup notices description
2723
+		$messenger_slug = ! empty($this->_req_data['MTP_messenger']) ? $this->_req_data['MTP_messenger'] : '';
2724
+
2725
+		// need the message type and messenger objects to be able to use the labels for the notices
2726
+		$messenger_object = $this->_message_resource_manager->get_messenger($messenger_slug);
2727
+		$messenger_label = $messenger_object instanceof EE_messenger
2728
+			? ucwords($messenger_object->label['singular'])
2729
+			: '';
2730
+
2731
+		$message_type_slug = ! empty($this->_req_data['MTP_message_type'])
2732
+			? $this->_req_data['MTP_message_type']
2733
+			: '';
2734
+		$message_type_object = $this->_message_resource_manager->get_message_type($message_type_slug);
2735
+
2736
+		$message_type_label = $message_type_object instanceof EE_message_type
2737
+			? ucwords($message_type_object->label['singular'])
2738
+			: '';
2739
+
2740
+		$context_slug = ! empty($this->_req_data['MTP_context'])
2741
+			? $this->_req_data['MTP_context']
2742
+			: '';
2743
+		$context = ucwords(str_replace('_', ' ', $context_slug));
2744
+
2745
+		$item_desc = $messenger_label && $message_type_label
2746
+			? $messenger_label . ' ' . $message_type_label . ' ' . $context . ' '
2747
+			: '';
2748
+		$item_desc .= 'Message Template';
2749
+		$query_args = array();
2750
+		$edit_array = array();
2751
+		$action_desc = '';
2752
+
2753
+		// if this is "new" then we need to generate the default contexts for the selected messenger/message_type for
2754
+		// user to edit.
2755
+		if ($new) {
2756
+			$GRP_ID = ! empty($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : 0;
2757
+			if ($edit_array = $this->_generate_new_templates($messenger_slug, $message_type_slug, $GRP_ID)) {
2758
+				if (empty($edit_array)) {
2759
+					$success = 0;
2760
+				} else {
2761
+					$success = 1;
2762
+					$edit_array = $edit_array[0];
2763
+					$query_args = array(
2764
+						'id'      => $edit_array['GRP_ID'],
2765
+						'context' => $edit_array['MTP_context'],
2766
+						'action'  => 'edit_message_template',
2767
+					);
2768
+				}
2769
+			}
2770
+			$action_desc = 'created';
2771
+		} else {
2772
+			$MTPG = EEM_Message_Template_Group::instance();
2773
+			$MTP = EEM_Message_Template::instance();
2774
+
2775
+
2776
+			// run update for each template field in displayed context
2777
+			if (! isset($this->_req_data['MTP_template_fields']) && empty($this->_req_data['MTP_template_fields'])) {
2778
+				EE_Error::add_error(
2779
+					esc_html__(
2780
+						'There was a problem saving the template fields from the form because I didn\'t receive any actual template field data.',
2781
+						'event_espresso'
2782
+					),
2783
+					__FILE__,
2784
+					__FUNCTION__,
2785
+					__LINE__
2786
+				);
2787
+				$success = 0;
2788
+			} else {
2789
+				// first validate all fields!
2790
+				// this filter allows client code to add its own validation to the template fields as well.
2791
+				// returning an empty array means everything passed validation.
2792
+				// errors in validation should be represented in an array with the following shape:
2793
+				// array(
2794
+				//   'fieldname' => array(
2795
+				//          'msg' => 'error message'
2796
+				//          'value' => 'value for field producing error'
2797
+				// )
2798
+				$custom_validation = (array) apply_filters(
2799
+					'FHEE__Messages_Admin_Page___insert_or_update_message_template__validates',
2800
+					array(),
2801
+					$this->_req_data['MTP_template_fields'],
2802
+					$context_slug,
2803
+					$messenger_slug,
2804
+					$message_type_slug
2805
+				);
2806
+
2807
+				$system_validation = $MTPG->validate(
2808
+					$this->_req_data['MTP_template_fields'],
2809
+					$context_slug,
2810
+					$messenger_slug,
2811
+					$message_type_slug
2812
+				);
2813
+
2814
+				$system_validation = ! is_array($system_validation) && $system_validation ? array()
2815
+					: $system_validation;
2816
+				$validates = array_merge($custom_validation, $system_validation);
2817
+
2818
+				// if $validate returned error messages (i.e. is_array()) then we need to process them and setup an
2819
+				// appropriate response. HMM, dang this isn't correct, $validates will ALWAYS be an array.
2820
+				//  WE need to make sure there is no actual error messages in validates.
2821
+				if (is_array($validates) && ! empty($validates)) {
2822
+					// add the transient so when the form loads we know which fields to highlight
2823
+					$this->_add_transient('edit_message_template', $validates);
2824
+
2825
+					$success = 0;
2826
+
2827
+					// setup notices
2828
+					foreach ($validates as $field => $error) {
2829
+						if (isset($error['msg'])) {
2830
+							EE_Error::add_error($error['msg'], __FILE__, __FUNCTION__, __LINE__);
2831
+						}
2832
+					}
2833
+				} else {
2834
+					$set_column_values = array();
2835
+					foreach ($this->_req_data['MTP_template_fields'] as $template_field => $content) {
2836
+						$set_column_values = $this->_set_message_template_column_values($template_field);
2837
+
2838
+						$where_cols_n_values = array(
2839
+							'MTP_ID' => $this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'],
2840
+						);
2841
+						// if they aren't allowed to use all JS, restrict them to just posty-y tags
2842
+						if (! current_user_can('unfiltered_html')) {
2843
+							if (is_array($set_column_values['MTP_content'])) {
2844
+								foreach ($set_column_values['MTP_content'] as $key => $value) {
2845
+									// remove slashes so wp_kses works properly (its wp_kses_stripslashes() function
2846
+									// only removes slashes from double-quotes, so attributes using single quotes always
2847
+									// appear invalid.) But currently the models expect slashed data, so after wp_kses
2848
+									// runs we need to re-slash the data. Sheesh. See
2849
+									// https://events.codebasehq.com/projects/event-espresso/tickets/11211#update-47321587
2850
+									$set_column_values['MTP_content'][ $key ] = addslashes(
2851
+										wp_kses(
2852
+											stripslashes($value),
2853
+											wp_kses_allowed_html('post')
2854
+										)
2855
+									);
2856
+								}
2857
+							} else {
2858
+								$set_column_values['MTP_content'] = wp_kses(
2859
+									$set_column_values['MTP_content'],
2860
+									wp_kses_allowed_html('post')
2861
+								);
2862
+							}
2863
+						}
2864
+						$message_template_fields = array(
2865
+							'GRP_ID'             => $set_column_values['GRP_ID'],
2866
+							'MTP_template_field' => $set_column_values['MTP_template_field'],
2867
+							'MTP_context'        => $set_column_values['MTP_context'],
2868
+							'MTP_content'        => $set_column_values['MTP_content'],
2869
+						);
2870
+						if ($updated = $MTP->update($message_template_fields, array($where_cols_n_values))) {
2871
+							if ($updated === false) {
2872
+								EE_Error::add_error(
2873
+									sprintf(
2874
+										esc_html__('%s field was NOT updated for some reason', 'event_espresso'),
2875
+										$template_field
2876
+									),
2877
+									__FILE__,
2878
+									__FUNCTION__,
2879
+									__LINE__
2880
+								);
2881
+							} else {
2882
+								$success = 1;
2883
+							}
2884
+						} else {
2885
+							// only do this logic if we don't have a MTP_ID for this field
2886
+							if (empty($this->_req_data['MTP_template_fields'][ $template_field ]['MTP_ID'])) {
2887
+								// this has already been through the template field validator and sanitized, so it will be
2888
+								// safe to insert this field.  Why insert?  This typically happens when we introduce a new
2889
+								// message template field in a messenger/message type and existing users don't have the
2890
+								// default setup for it.
2891
+								// @link https://events.codebasehq.com/projects/event-espresso/tickets/9465
2892
+								$updated = $MTP->insert($message_template_fields);
2893
+								if (! $updated || is_wp_error($updated)) {
2894
+									EE_Error::add_error(
2895
+										sprintf(
2896
+											esc_html__('%s field could not be updated.', 'event_espresso'),
2897
+											$template_field
2898
+										),
2899
+										__FILE__,
2900
+										__FUNCTION__,
2901
+										__LINE__
2902
+									);
2903
+									$success = 0;
2904
+								} else {
2905
+									$success = 1;
2906
+								}
2907
+							}
2908
+						}
2909
+						$action_desc = 'updated';
2910
+					}
2911
+
2912
+					// we can use the last set_column_values for the MTPG update (because its the same for all of these specific MTPs)
2913
+					$mtpg_fields = array(
2914
+						'MTP_user_id'      => $set_column_values['MTP_user_id'],
2915
+						'MTP_messenger'    => $set_column_values['MTP_messenger'],
2916
+						'MTP_message_type' => $set_column_values['MTP_message_type'],
2917
+						'MTP_is_global'    => $set_column_values['MTP_is_global'],
2918
+						'MTP_is_override'  => $set_column_values['MTP_is_override'],
2919
+						'MTP_deleted'      => $set_column_values['MTP_deleted'],
2920
+						'MTP_is_active'    => $set_column_values['MTP_is_active'],
2921
+						'MTP_name'         => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_name'])
2922
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_name']
2923
+							: '',
2924
+						'MTP_description'  => ! empty($this->_req_data['ee_msg_non_global_fields']['MTP_description'])
2925
+							? $this->_req_data['ee_msg_non_global_fields']['MTP_description']
2926
+							: '',
2927
+					);
2928
+
2929
+					$mtpg_where = array('GRP_ID' => $set_column_values['GRP_ID']);
2930
+					$updated = $MTPG->update($mtpg_fields, array($mtpg_where));
2931
+
2932
+					if ($updated === false) {
2933
+						EE_Error::add_error(
2934
+							sprintf(
2935
+								esc_html__(
2936
+									'The Message Template Group (%d) was NOT updated for some reason',
2937
+									'event_espresso'
2938
+								),
2939
+								$set_column_values['GRP_ID']
2940
+							),
2941
+							__FILE__,
2942
+							__FUNCTION__,
2943
+							__LINE__
2944
+						);
2945
+					} else {
2946
+						// k now we need to ensure the template_pack and template_variation fields are set.
2947
+						$template_pack = ! empty($this->_req_data['MTP_template_pack'])
2948
+							? $this->_req_data['MTP_template_pack']
2949
+							: 'default';
2950
+
2951
+						$template_variation = ! empty($this->_req_data['MTP_template_variation'])
2952
+							? $this->_req_data['MTP_template_variation']
2953
+							: 'default';
2954
+
2955
+						$mtpg_obj = $MTPG->get_one_by_ID($set_column_values['GRP_ID']);
2956
+						if ($mtpg_obj instanceof EE_Message_Template_Group) {
2957
+							$mtpg_obj->set_template_pack_name($template_pack);
2958
+							$mtpg_obj->set_template_pack_variation($template_variation);
2959
+						}
2960
+						$success = 1;
2961
+					}
2962
+				}
2963
+			}
2964
+		}
2965
+
2966
+		// we return things differently if doing ajax
2967
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2968
+			$this->_template_args['success'] = $success;
2969
+			$this->_template_args['error'] = ! $success ? true : false;
2970
+			$this->_template_args['content'] = '';
2971
+			$this->_template_args['data'] = array(
2972
+				'grpID'        => $edit_array['GRP_ID'],
2973
+				'templateName' => $edit_array['template_name'],
2974
+			);
2975
+			if ($success) {
2976
+				EE_Error::overwrite_success();
2977
+				EE_Error::add_success(
2978
+					esc_html__(
2979
+						'The new template has been created and automatically selected for this event.  You can edit the new template by clicking the edit button.  Note before this template is assigned to this event, the event must be saved.',
2980
+						'event_espresso'
2981
+					)
2982
+				);
2983
+			}
2984
+
2985
+			$this->_return_json();
2986
+		}
2987
+
2988
+
2989
+		// was a test send triggered?
2990
+		if (isset($this->_req_data['test_button'])) {
2991
+			EE_Error::overwrite_success();
2992
+			$this->_do_test_send($context_slug, $messenger_slug, $message_type_slug);
2993
+			$override = true;
2994
+		}
2995
+
2996
+		if (empty($query_args)) {
2997
+			$query_args = array(
2998
+				'id'      => $this->_req_data['GRP_ID'],
2999
+				'context' => $context_slug,
3000
+				'action'  => 'edit_message_template',
3001
+			);
3002
+		}
3003
+
3004
+		$this->_redirect_after_action($success, $item_desc, $action_desc, $query_args, $override);
3005
+	}
3006
+
3007
+
3008
+	/**
3009
+	 * processes a test send request to do an actual messenger delivery test for the given message template being tested
3010
+	 *
3011
+	 * @param  string $context      what context being tested
3012
+	 * @param  string $messenger    messenger being tested
3013
+	 * @param  string $message_type message type being tested
3014
+	 * @throws EE_Error
3015
+	 * @throws InvalidArgumentException
3016
+	 * @throws InvalidDataTypeException
3017
+	 * @throws InvalidInterfaceException
3018
+	 */
3019
+	protected function _do_test_send($context, $messenger, $message_type)
3020
+	{
3021
+		// set things up for preview
3022
+		$this->_req_data['messenger'] = $messenger;
3023
+		$this->_req_data['message_type'] = $message_type;
3024
+		$this->_req_data['context'] = $context;
3025
+		$this->_req_data['GRP_ID'] = isset($this->_req_data['GRP_ID']) ? $this->_req_data['GRP_ID'] : '';
3026
+		$active_messenger = $this->_message_resource_manager->get_active_messenger($messenger);
3027
+
3028
+		// let's save any existing fields that might be required by the messenger
3029
+		if (isset($this->_req_data['test_settings_fld'])
3030
+			&& $active_messenger instanceof EE_messenger
3031
+			&& apply_filters(
3032
+				'FHEE__Messages_Admin_Page__do_test_send__set_existing_test_settings',
3033
+				true,
3034
+				$this->_req_data['test_settings_fld'],
3035
+				$active_messenger
3036
+			)
3037
+		) {
3038
+			$active_messenger->set_existing_test_settings($this->_req_data['test_settings_fld']);
3039
+		}
3040
+
3041
+		/**
3042
+		 * Use filter to add additional controls on whether message can send or not
3043
+		 */
3044
+		if (apply_filters(
3045
+			'FHEE__Messages_Admin_Page__do_test_send__can_send',
3046
+			true,
3047
+			$context,
3048
+			$this->_req_data,
3049
+			$messenger,
3050
+			$message_type
3051
+		)) {
3052
+			if (EEM_Event::instance()->count() > 0) {
3053
+				$success = $this->_preview_message(true);
3054
+				if ($success) {
3055
+					EE_Error::add_success(__('Test message sent', 'event_espresso'));
3056
+				} else {
3057
+					EE_Error::add_error(
3058
+						esc_html__('The test message was not sent', 'event_espresso'),
3059
+						__FILE__,
3060
+						__FUNCTION__,
3061
+						__LINE__
3062
+					);
3063
+				}
3064
+			} else {
3065
+				$this->noEventsErrorMessage(true);
3066
+			}
3067
+		}
3068
+	}
3069
+
3070
+
3071
+	/**
3072
+	 * _generate_new_templates
3073
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
3074
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
3075
+	 * for the event.
3076
+	 *
3077
+	 *
3078
+	 * @param  string $messenger     the messenger we are generating templates for
3079
+	 * @param array   $message_types array of message types that the templates are generated for.
3080
+	 * @param int     $GRP_ID        If this is a custom template being generated then a GRP_ID needs to be included to
3081
+	 *                               indicate the message_template_group being used as the base.
3082
+	 *
3083
+	 * @param bool    $global
3084
+	 *
3085
+	 * @return array|bool array of data required for the redirect to the correct edit page or bool if
3086
+	 *                               encountering problems.
3087
+	 * @throws EE_Error
3088
+	 */
3089
+	protected function _generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
3090
+	{
3091
+
3092
+		// if no $message_types are given then that's okay... this may be a messenger that just adds shortcodes, so we
3093
+		// just don't generate any templates.
3094
+		if (empty($message_types)) {
3095
+			return true;
3096
+		}
3097
+
3098
+		return EEH_MSG_Template::generate_new_templates($messenger, $message_types, $GRP_ID, $global);
3099
+	}
3100
+
3101
+
3102
+	/**
3103
+	 * [_trash_or_restore_message_template]
3104
+	 *
3105
+	 * @param  boolean $trash whether to move an item to trash/restore (TRUE) or restore it (FALSE)
3106
+	 * @param boolean  $all   whether this is going to trash/restore all contexts within a template group (TRUE) OR just
3107
+	 *                        an individual context (FALSE).
3108
+	 * @return void
3109
+	 * @throws EE_Error
3110
+	 * @throws InvalidArgumentException
3111
+	 * @throws InvalidDataTypeException
3112
+	 * @throws InvalidInterfaceException
3113
+	 */
3114
+	protected function _trash_or_restore_message_template($trash = true, $all = false)
3115
+	{
3116
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3117
+		$MTP = EEM_Message_Template_Group::instance();
3118
+
3119
+		$success = 1;
3120
+
3121
+		// incoming GRP_IDs
3122
+		if ($all) {
3123
+			// Checkboxes
3124
+			if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3125
+				// if array has more than one element then success message should be plural.
3126
+				// todo: what about nonce?
3127
+				$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3128
+
3129
+				// cycle through checkboxes
3130
+				while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3131
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3132
+					if (! $trashed_or_restored) {
3133
+						$success = 0;
3134
+					}
3135
+				}
3136
+			} else {
3137
+				// grab single GRP_ID and handle
3138
+				$GRP_ID = isset($this->_req_data['id']) ? absint($this->_req_data['id']) : 0;
3139
+				if (! empty($GRP_ID)) {
3140
+					$trashed_or_restored = $trash ? $MTP->delete_by_ID($GRP_ID) : $MTP->restore_by_ID($GRP_ID);
3141
+					if (! $trashed_or_restored) {
3142
+						$success = 0;
3143
+					}
3144
+				} else {
3145
+					$success = 0;
3146
+				}
3147
+			}
3148
+		}
3149
+
3150
+		$action_desc = $trash
3151
+			? esc_html__('moved to the trash', 'event_espresso')
3152
+			: esc_html__('restored', 'event_espresso');
3153
+
3154
+		$action_desc = ! empty($this->_req_data['template_switch']) ? esc_html__('switched', 'event_espresso') : $action_desc;
3155
+
3156
+		$item_desc = $all ? _n(
3157
+			'Message Template Group',
3158
+			'Message Template Groups',
3159
+			$success,
3160
+			'event_espresso'
3161
+		) : _n('Message Template Context', 'Message Template Contexts', $success, 'event_espresso');
3162
+
3163
+		$item_desc = ! empty($this->_req_data['template_switch']) ? _n(
3164
+			'template',
3165
+			'templates',
3166
+			$success,
3167
+			'event_espresso'
3168
+		) : $item_desc;
3169
+
3170
+		$this->_redirect_after_action($success, $item_desc, $action_desc, array());
3171
+	}
3172
+
3173
+
3174
+	/**
3175
+	 * [_delete_message_template]
3176
+	 * NOTE: this handles not only the deletion of the groups but also all the templates belonging to that group.
3177
+	 *
3178
+	 * @return void
3179
+	 * @throws EE_Error
3180
+	 * @throws InvalidArgumentException
3181
+	 * @throws InvalidDataTypeException
3182
+	 * @throws InvalidInterfaceException
3183
+	 */
3184
+	protected function _delete_message_template()
3185
+	{
3186
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3187
+
3188
+		// checkboxes
3189
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
3190
+			// if array has more than one element then success message should be plural
3191
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
3192
+
3193
+			// cycle through bulk action checkboxes
3194
+			while (list($GRP_ID, $value) = each($this->_req_data['checkbox'])) {
3195
+				$success = $this->_delete_mtp_permanently($GRP_ID);
3196
+			}
3197
+		} else {
3198
+			// grab single grp_id and delete
3199
+			$GRP_ID = absint($this->_req_data['id']);
3200
+			$success = $this->_delete_mtp_permanently($GRP_ID);
3201
+		}
3202
+
3203
+		$this->_redirect_after_action($success, 'Message Templates', 'deleted', array());
3204
+	}
3205
+
3206
+
3207
+	/**
3208
+	 * helper for permanently deleting a mtP group and all related message_templates
3209
+	 *
3210
+	 * @param  int  $GRP_ID        The group being deleted
3211
+	 * @param  bool $include_group whether to delete the Message Template Group as well.
3212
+	 * @return bool boolean to indicate the success of the deletes or not.
3213
+	 * @throws EE_Error
3214
+	 * @throws InvalidArgumentException
3215
+	 * @throws InvalidDataTypeException
3216
+	 * @throws InvalidInterfaceException
3217
+	 */
3218
+	private function _delete_mtp_permanently($GRP_ID, $include_group = true)
3219
+	{
3220
+		$success = 1;
3221
+		$MTPG = EEM_Message_Template_Group::instance();
3222
+		// first let's GET this group
3223
+		$MTG = $MTPG->get_one_by_ID($GRP_ID);
3224
+		// then delete permanently all the related Message Templates
3225
+		$deleted = $MTG->delete_related_permanently('Message_Template');
3226
+
3227
+		if ($deleted === 0) {
3228
+			$success = 0;
3229
+		}
3230
+
3231
+		// now delete permanently this particular group
3232
+
3233
+		if ($include_group && ! $MTG->delete_permanently()) {
3234
+			$success = 0;
3235
+		}
3236
+
3237
+		return $success;
3238
+	}
3239
+
3240
+
3241
+	/**
3242
+	 *    _learn_more_about_message_templates_link
3243
+	 *
3244
+	 * @access protected
3245
+	 * @return string
3246
+	 */
3247
+	protected function _learn_more_about_message_templates_link()
3248
+	{
3249
+		return '<a class="hidden" style="margin:0 20px; cursor:pointer; font-size:12px;" >'
3250
+			   . esc_html__('learn more about how message templates works', 'event_espresso')
3251
+			   . '</a>';
3252
+	}
3253
+
3254
+
3255
+	/**
3256
+	 * Used for setting up messenger/message type activation.  This loads up the initial view.  The rest is handled by
3257
+	 * ajax and other routes.
3258
+	 *
3259
+	 * @return void
3260
+	 * @throws DomainException
3261
+	 */
3262
+	protected function _settings()
3263
+	{
3264
+
3265
+
3266
+		$this->_set_m_mt_settings();
3267
+
3268
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3269
+			? $this->_req_data['selected_messenger']
3270
+			: 'email';
3271
+
3272
+		// let's setup the messenger tabs
3273
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
3274
+			$this->_m_mt_settings['messenger_tabs'],
3275
+			'messenger_links',
3276
+			'|',
3277
+			$selected_messenger
3278
+		);
3279
+		$this->_template_args['before_admin_page_content'] = '<div class="ui-widget ui-helper-clearfix">';
3280
+		$this->_template_args['after_admin_page_content'] = '</div><!-- end .ui-widget -->';
3281
+
3282
+		$this->display_admin_page_with_sidebar();
3283
+	}
3284
+
3285
+
3286
+	/**
3287
+	 * This sets the $_m_mt_settings property for when needed (used on the Messages settings page)
3288
+	 *
3289
+	 * @access protected
3290
+	 * @return void
3291
+	 * @throws DomainException
3292
+	 */
3293
+	protected function _set_m_mt_settings()
3294
+	{
3295
+		// first if this is already set then lets get out no need to regenerate data.
3296
+		if (! empty($this->_m_mt_settings)) {
3297
+			return;
3298
+		}
3299
+
3300
+		// get all installed messengers and message_types
3301
+		/** @type EE_messenger[] $messengers */
3302
+		$messengers = $this->_message_resource_manager->installed_messengers();
3303
+		/** @type EE_message_type[] $message_types */
3304
+		$message_types = $this->_message_resource_manager->installed_message_types();
3305
+
3306
+
3307
+		// assemble the array for the _tab_text_links helper
3308
+
3309
+		foreach ($messengers as $messenger) {
3310
+			$this->_m_mt_settings['messenger_tabs'][ $messenger->name ] = array(
3311
+				'label' => ucwords($messenger->label['singular']),
3312
+				'class' => $this->_message_resource_manager->is_messenger_active($messenger->name)
3313
+					? 'messenger-active'
3314
+					: '',
3315
+				'href'  => $messenger->name,
3316
+				'title' => esc_html__('Modify this Messenger', 'event_espresso'),
3317
+				'slug'  => $messenger->name,
3318
+				'obj'   => $messenger,
3319
+			);
3320
+
3321
+
3322
+			$message_types_for_messenger = $messenger->get_valid_message_types();
3323
+
3324
+			foreach ($message_types as $message_type) {
3325
+				// first we need to verify that this message type is valid with this messenger. Cause if it isn't then
3326
+				// it shouldn't show in either the inactive OR active metabox.
3327
+				if (! in_array($message_type->name, $message_types_for_messenger, true)) {
3328
+					continue;
3329
+				}
3330
+
3331
+				$a_or_i = $this->_message_resource_manager->is_message_type_active_for_messenger(
3332
+					$messenger->name,
3333
+					$message_type->name
3334
+				)
3335
+					? 'active'
3336
+					: 'inactive';
3337
+
3338
+				$this->_m_mt_settings['message_type_tabs'][ $messenger->name ][ $a_or_i ][ $message_type->name ] = array(
3339
+					'label'    => ucwords($message_type->label['singular']),
3340
+					'class'    => 'message-type-' . $a_or_i,
3341
+					'slug_id'  => $message_type->name . '-messagetype-' . $messenger->name,
3342
+					'mt_nonce' => wp_create_nonce($message_type->name . '_nonce'),
3343
+					'href'     => 'espresso_' . $message_type->name . '_message_type_settings',
3344
+					'title'    => $a_or_i === 'active'
3345
+						? esc_html__('Drag this message type to the Inactive window to deactivate', 'event_espresso')
3346
+						: esc_html__('Drag this message type to the messenger to activate', 'event_espresso'),
3347
+					'content'  => $a_or_i === 'active'
3348
+						? $this->_message_type_settings_content($message_type, $messenger, true)
3349
+						: $this->_message_type_settings_content($message_type, $messenger),
3350
+					'slug'     => $message_type->name,
3351
+					'active'   => $a_or_i === 'active',
3352
+					'obj'      => $message_type,
3353
+				);
3354
+			}
3355
+		}
3356
+	}
3357
+
3358
+
3359
+	/**
3360
+	 * This just prepares the content for the message type settings
3361
+	 *
3362
+	 * @param  EE_message_type $message_type The message type object
3363
+	 * @param  EE_messenger    $messenger    The messenger object
3364
+	 * @param  boolean         $active       Whether the message type is active or not
3365
+	 * @return string html output for the content
3366
+	 * @throws DomainException
3367
+	 */
3368
+	protected function _message_type_settings_content($message_type, $messenger, $active = false)
3369
+	{
3370
+		// get message type fields
3371
+		$fields = $message_type->get_admin_settings_fields();
3372
+		$settings_template_args['template_form_fields'] = '';
3373
+
3374
+		if (! empty($fields) && $active) {
3375
+			$existing_settings = $message_type->get_existing_admin_settings($messenger->name);
3376
+			foreach ($fields as $fldname => $fldprops) {
3377
+				$field_id = $messenger->name . '-' . $message_type->name . '-' . $fldname;
3378
+				$template_form_field[ $field_id ] = array(
3379
+					'name'       => 'message_type_settings[' . $fldname . ']',
3380
+					'label'      => $fldprops['label'],
3381
+					'input'      => $fldprops['field_type'],
3382
+					'type'       => $fldprops['value_type'],
3383
+					'required'   => $fldprops['required'],
3384
+					'validation' => $fldprops['validation'],
3385
+					'value'      => isset($existing_settings[ $fldname ])
3386
+						? $existing_settings[ $fldname ]
3387
+						: $fldprops['default'],
3388
+					'options'    => isset($fldprops['options'])
3389
+						? $fldprops['options']
3390
+						: array(),
3391
+					'default'    => isset($existing_settings[ $fldname ])
3392
+						? $existing_settings[ $fldname ]
3393
+						: $fldprops['default'],
3394
+					'css_class'  => 'no-drag',
3395
+					'format'     => $fldprops['format'],
3396
+				);
3397
+			}
3398
+
3399
+
3400
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3401
+				? $this->_generate_admin_form_fields(
3402
+					$template_form_field,
3403
+					'string',
3404
+					'ee_mt_activate_form'
3405
+				)
3406
+				: '';
3407
+		}
3408
+
3409
+		$settings_template_args['description'] = $message_type->description;
3410
+		// we also need some hidden fields
3411
+		$settings_template_args['hidden_fields'] = array(
3412
+			'message_type_settings[messenger]'    => array(
3413
+				'type'  => 'hidden',
3414
+				'value' => $messenger->name,
3415
+			),
3416
+			'message_type_settings[message_type]' => array(
3417
+				'type'  => 'hidden',
3418
+				'value' => $message_type->name,
3419
+			),
3420
+			'type'                                => array(
3421
+				'type'  => 'hidden',
3422
+				'value' => 'message_type',
3423
+			),
3424
+		);
3425
+
3426
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3427
+			$settings_template_args['hidden_fields'],
3428
+			'array'
3429
+		);
3430
+		$settings_template_args['show_form'] = empty($settings_template_args['template_form_fields'])
3431
+			? ' hidden'
3432
+			: '';
3433
+
3434
+
3435
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_mt_settings_content.template.php';
3436
+		$content = EEH_Template::display_template($template, $settings_template_args, true);
3437
+
3438
+		return $content;
3439
+	}
3440
+
3441
+
3442
+	/**
3443
+	 * Generate all the metaboxes for the message types and register them for the messages settings page.
3444
+	 *
3445
+	 * @access protected
3446
+	 * @return void
3447
+	 * @throws DomainException
3448
+	 */
3449
+	protected function _messages_settings_metaboxes()
3450
+	{
3451
+		$this->_set_m_mt_settings();
3452
+		$m_boxes = $mt_boxes = array();
3453
+		$m_template_args = $mt_template_args = array();
3454
+
3455
+		$selected_messenger = isset($this->_req_data['selected_messenger'])
3456
+			? $this->_req_data['selected_messenger']
3457
+			: 'email';
3458
+
3459
+		if (isset($this->_m_mt_settings['messenger_tabs'])) {
3460
+			foreach ($this->_m_mt_settings['messenger_tabs'] as $messenger => $tab_array) {
3461
+				$hide_on_message = $this->_message_resource_manager->is_messenger_active($messenger) ? '' : 'hidden';
3462
+				$hide_off_message = $this->_message_resource_manager->is_messenger_active($messenger) ? 'hidden' : '';
3463
+				// messenger meta boxes
3464
+				$active = $selected_messenger === $messenger;
3465
+				$active_mt_tabs = isset(
3466
+					$this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3467
+				)
3468
+					? $this->_m_mt_settings['message_type_tabs'][ $messenger ]['active']
3469
+					: '';
3470
+				$m_boxes[ $messenger . '_a_box' ] = sprintf(
3471
+					esc_html__('%s Settings', 'event_espresso'),
3472
+					$tab_array['label']
3473
+				);
3474
+				$m_template_args[ $messenger . '_a_box' ] = array(
3475
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3476
+					'inactive_message_types' => isset(
3477
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3478
+					)
3479
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3480
+						: '',
3481
+					'content'                => $this->_get_messenger_box_content($tab_array['obj']),
3482
+					'hidden'                 => $active ? '' : ' hidden',
3483
+					'hide_on_message'        => $hide_on_message,
3484
+					'messenger'              => $messenger,
3485
+					'active'                 => $active,
3486
+				);
3487
+				// message type meta boxes
3488
+				// (which is really just the inactive container for each messenger
3489
+				// showing inactive message types for that messenger)
3490
+				$mt_boxes[ $messenger . '_i_box' ] = esc_html__('Inactive Message Types', 'event_espresso');
3491
+				$mt_template_args[ $messenger . '_i_box' ] = array(
3492
+					'active_message_types'   => ! empty($active_mt_tabs) ? $this->_get_mt_tabs($active_mt_tabs) : '',
3493
+					'inactive_message_types' => isset(
3494
+						$this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive']
3495
+					)
3496
+						? $this->_get_mt_tabs($this->_m_mt_settings['message_type_tabs'][ $messenger ]['inactive'])
3497
+						: '',
3498
+					'hidden'                 => $active ? '' : ' hidden',
3499
+					'hide_on_message'        => $hide_on_message,
3500
+					'hide_off_message'       => $hide_off_message,
3501
+					'messenger'              => $messenger,
3502
+					'active'                 => $active,
3503
+				);
3504
+			}
3505
+		}
3506
+
3507
+
3508
+		// register messenger metaboxes
3509
+		$m_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_mt_meta_box.template.php';
3510
+		foreach ($m_boxes as $box => $label) {
3511
+			$callback_args = array('template_path' => $m_template_path, 'template_args' => $m_template_args[ $box ]);
3512
+			$msgr = str_replace('_a_box', '', $box);
3513
+			add_meta_box(
3514
+				'espresso_' . $msgr . '_settings',
3515
+				$label,
3516
+				function ($post, $metabox) {
3517
+					echo EEH_Template::display_template(
3518
+						$metabox["args"]["template_path"],
3519
+						$metabox["args"]["template_args"],
3520
+						true
3521
+					);
3522
+				},
3523
+				$this->_current_screen->id,
3524
+				'normal',
3525
+				'high',
3526
+				$callback_args
3527
+			);
3528
+		}
3529
+
3530
+		// register message type metaboxes
3531
+		$mt_template_path = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_messenger_meta_box.template.php';
3532
+		foreach ($mt_boxes as $box => $label) {
3533
+			$callback_args = array(
3534
+				'template_path' => $mt_template_path,
3535
+				'template_args' => $mt_template_args[ $box ],
3536
+			);
3537
+			$mt = str_replace('_i_box', '', $box);
3538
+			add_meta_box(
3539
+				'espresso_' . $mt . '_inactive_mts',
3540
+				$label,
3541
+				function ($post, $metabox) {
3542
+					echo EEH_Template::display_template(
3543
+						$metabox["args"]["template_path"],
3544
+						$metabox["args"]["template_args"],
3545
+						true
3546
+					);
3547
+				},
3548
+				$this->_current_screen->id,
3549
+				'side',
3550
+				'high',
3551
+				$callback_args
3552
+			);
3553
+		}
3554
+
3555
+		// register metabox for global messages settings but only when on the main site.  On single site installs this
3556
+		// will always result in the metabox showing, on multisite installs the metabox will only show on the main site.
3557
+		if (is_main_site()) {
3558
+			add_meta_box(
3559
+				'espresso_global_message_settings',
3560
+				esc_html__('Global Message Settings', 'event_espresso'),
3561
+				array($this, 'global_messages_settings_metabox_content'),
3562
+				$this->_current_screen->id,
3563
+				'normal',
3564
+				'low',
3565
+				array()
3566
+			);
3567
+		}
3568
+	}
3569
+
3570
+
3571
+	/**
3572
+	 *  This generates the content for the global messages settings metabox.
3573
+	 *
3574
+	 * @return string
3575
+	 * @throws EE_Error
3576
+	 * @throws InvalidArgumentException
3577
+	 * @throws ReflectionException
3578
+	 * @throws InvalidDataTypeException
3579
+	 * @throws InvalidInterfaceException
3580
+	 */
3581
+	public function global_messages_settings_metabox_content()
3582
+	{
3583
+		$form = $this->_generate_global_settings_form();
3584
+		echo $form->form_open(
3585
+			$this->add_query_args_and_nonce(array('action' => 'update_global_settings'), EE_MSG_ADMIN_URL),
3586
+			'POST'
3587
+		)
3588
+			 . $form->get_html()
3589
+			 . $form->form_close();
3590
+	}
3591
+
3592
+
3593
+	/**
3594
+	 * This generates and returns the form object for the global messages settings.
3595
+	 *
3596
+	 * @return EE_Form_Section_Proper
3597
+	 * @throws EE_Error
3598
+	 * @throws InvalidArgumentException
3599
+	 * @throws ReflectionException
3600
+	 * @throws InvalidDataTypeException
3601
+	 * @throws InvalidInterfaceException
3602
+	 */
3603
+	protected function _generate_global_settings_form()
3604
+	{
3605
+		EE_Registry::instance()->load_helper('HTML');
3606
+		/** @var EE_Network_Core_Config $network_config */
3607
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3608
+
3609
+		return new EE_Form_Section_Proper(
3610
+			array(
3611
+				'name'            => 'global_messages_settings',
3612
+				'html_id'         => 'global_messages_settings',
3613
+				'html_class'      => 'form-table',
3614
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
3615
+				'subsections'     => apply_filters(
3616
+					'FHEE__Messages_Admin_Page__global_messages_settings_metabox_content__form_subsections',
3617
+					array(
3618
+						'do_messages_on_same_request' => new EE_Select_Input(
3619
+							array(
3620
+								true  => esc_html__("On the same request", "event_espresso"),
3621
+								false => esc_html__("On a separate request", "event_espresso"),
3622
+							),
3623
+							array(
3624
+								'default'         => $network_config->do_messages_on_same_request,
3625
+								'html_label_text' => esc_html__(
3626
+									'Generate and send all messages:',
3627
+									'event_espresso'
3628
+								),
3629
+								'html_help_text'  => esc_html__(
3630
+									'By default the messages system uses a more efficient means of processing messages on separate requests and utilizes the wp-cron scheduling system.  This makes things execute faster for people registering for your events.  However, if the wp-cron system is disabled on your site and there is no alternative in place, then you can change this so messages are always executed on the same request.',
3631
+									'event_espresso'
3632
+								),
3633
+							)
3634
+						),
3635
+						'delete_threshold'            => new EE_Select_Input(
3636
+							array(
3637
+								0  => esc_html__('Forever', 'event_espresso'),
3638
+								3  => esc_html__('3 Months', 'event_espresso'),
3639
+								6  => esc_html__('6 Months', 'event_espresso'),
3640
+								9  => esc_html__('9 Months', 'event_espresso'),
3641
+								12 => esc_html__('12 Months', 'event_espresso'),
3642
+								24 => esc_html__('24 Months', 'event_espresso'),
3643
+								36 => esc_html__('36 Months', 'event_espresso'),
3644
+							),
3645
+							array(
3646
+								'default'         => EE_Registry::instance()->CFG->messages->delete_threshold,
3647
+								'html_label_text' => esc_html__('Cleanup of old messages:', 'event_espresso'),
3648
+								'html_help_text'  => esc_html__(
3649
+									'You can control how long a record of processed messages is kept via this option.',
3650
+									'event_espresso'
3651
+								),
3652
+							)
3653
+						),
3654
+						'update_settings'             => new EE_Submit_Input(
3655
+							array(
3656
+								'default'         => esc_html__('Update', 'event_espresso'),
3657
+								'html_label_text' => '&nbsp',
3658
+							)
3659
+						),
3660
+					)
3661
+				),
3662
+			)
3663
+		);
3664
+	}
3665
+
3666
+
3667
+	/**
3668
+	 * This handles updating the global settings set on the admin page.
3669
+	 *
3670
+	 * @throws EE_Error
3671
+	 * @throws InvalidDataTypeException
3672
+	 * @throws InvalidInterfaceException
3673
+	 * @throws InvalidArgumentException
3674
+	 * @throws ReflectionException
3675
+	 */
3676
+	protected function _update_global_settings()
3677
+	{
3678
+		/** @var EE_Network_Core_Config $network_config */
3679
+		$network_config = EE_Registry::instance()->NET_CFG->core;
3680
+		$messages_config = EE_Registry::instance()->CFG->messages;
3681
+		$form = $this->_generate_global_settings_form();
3682
+		if ($form->was_submitted()) {
3683
+			$form->receive_form_submission();
3684
+			if ($form->is_valid()) {
3685
+				$valid_data = $form->valid_data();
3686
+				foreach ($valid_data as $property => $value) {
3687
+					$setter = 'set_' . $property;
3688
+					if (method_exists($network_config, $setter)) {
3689
+						$network_config->{$setter}($value);
3690
+					} elseif (property_exists($network_config, $property)
3691
+						&& $network_config->{$property} !== $value
3692
+					) {
3693
+						$network_config->{$property} = $value;
3694
+					} elseif (property_exists($messages_config, $property)
3695
+						&& $messages_config->{$property} !== $value
3696
+					) {
3697
+						$messages_config->{$property} = $value;
3698
+					}
3699
+				}
3700
+				// only update if the form submission was valid!
3701
+				EE_Registry::instance()->NET_CFG->update_config(true, false);
3702
+				EE_Registry::instance()->CFG->update_espresso_config();
3703
+				EE_Error::overwrite_success();
3704
+				EE_Error::add_success(__('Global message settings were updated', 'event_espresso'));
3705
+			}
3706
+		}
3707
+		$this->_redirect_after_action(0, '', '', array('action' => 'settings'), true);
3708
+	}
3709
+
3710
+
3711
+	/**
3712
+	 * this prepares the messenger tabs that can be dragged in and out of messenger boxes to activate/deactivate
3713
+	 *
3714
+	 * @param  array $tab_array This is an array of message type tab details used to generate the tabs
3715
+	 * @return string html formatted tabs
3716
+	 * @throws DomainException
3717
+	 */
3718
+	protected function _get_mt_tabs($tab_array)
3719
+	{
3720
+		$tab_array = (array) $tab_array;
3721
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_details_mt_settings_tab_item.template.php';
3722
+		$tabs = '';
3723
+
3724
+		foreach ($tab_array as $tab) {
3725
+			$tabs .= EEH_Template::display_template($template, $tab, true);
3726
+		}
3727
+
3728
+		return $tabs;
3729
+	}
3730
+
3731
+
3732
+	/**
3733
+	 * This prepares the content of the messenger meta box admin settings
3734
+	 *
3735
+	 * @param  EE_messenger $messenger The messenger we're setting up content for
3736
+	 * @return string html formatted content
3737
+	 * @throws DomainException
3738
+	 */
3739
+	protected function _get_messenger_box_content(EE_messenger $messenger)
3740
+	{
3741
+
3742
+		$fields = $messenger->get_admin_settings_fields();
3743
+		$settings_template_args['template_form_fields'] = '';
3744
+
3745
+		// is $messenger active?
3746
+		$settings_template_args['active'] = $this->_message_resource_manager->is_messenger_active($messenger->name);
3747
+
3748
+
3749
+		if (! empty($fields)) {
3750
+			$existing_settings = $messenger->get_existing_admin_settings();
3751
+
3752
+			foreach ($fields as $fldname => $fldprops) {
3753
+				$field_id = $messenger->name . '-' . $fldname;
3754
+				$template_form_field[ $field_id ] = array(
3755
+					'name'       => 'messenger_settings[' . $field_id . ']',
3756
+					'label'      => $fldprops['label'],
3757
+					'input'      => $fldprops['field_type'],
3758
+					'type'       => $fldprops['value_type'],
3759
+					'required'   => $fldprops['required'],
3760
+					'validation' => $fldprops['validation'],
3761
+					'value'      => isset($existing_settings[ $field_id ])
3762
+						? $existing_settings[ $field_id ]
3763
+						: $fldprops['default'],
3764
+					'css_class'  => '',
3765
+					'format'     => $fldprops['format'],
3766
+				);
3767
+			}
3768
+
3769
+
3770
+			$settings_template_args['template_form_fields'] = ! empty($template_form_field)
3771
+				? $this->_generate_admin_form_fields($template_form_field, 'string', 'ee_m_activate_form')
3772
+				: '';
3773
+		}
3774
+
3775
+		// we also need some hidden fields
3776
+		$settings_template_args['hidden_fields'] = array(
3777
+			'messenger_settings[messenger]' => array(
3778
+				'type'  => 'hidden',
3779
+				'value' => $messenger->name,
3780
+			),
3781
+			'type'                          => array(
3782
+				'type'  => 'hidden',
3783
+				'value' => 'messenger',
3784
+			),
3785
+		);
3786
+
3787
+		// make sure any active message types that are existing are included in the hidden fields
3788
+		if (isset($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'])) {
3789
+			foreach ($this->_m_mt_settings['message_type_tabs'][ $messenger->name ]['active'] as $mt => $values) {
3790
+				$settings_template_args['hidden_fields'][ 'messenger_settings[message_types][' . $mt . ']' ] = array(
3791
+					'type'  => 'hidden',
3792
+					'value' => $mt,
3793
+				);
3794
+			}
3795
+		}
3796
+		$settings_template_args['hidden_fields'] = $this->_generate_admin_form_fields(
3797
+			$settings_template_args['hidden_fields'],
3798
+			'array'
3799
+		);
3800
+		$active = $this->_message_resource_manager->is_messenger_active($messenger->name);
3801
+
3802
+		$settings_template_args['messenger'] = $messenger->name;
3803
+		$settings_template_args['description'] = $messenger->description;
3804
+		$settings_template_args['show_hide_edit_form'] = $active ? '' : ' hidden';
3805
+
3806
+
3807
+		$settings_template_args['show_hide_edit_form'] = $this->_message_resource_manager->is_messenger_active(
3808
+			$messenger->name
3809
+		)
3810
+			? $settings_template_args['show_hide_edit_form']
3811
+			: ' hidden';
3812
+
3813
+		$settings_template_args['show_hide_edit_form'] = empty($settings_template_args['template_form_fields'])
3814
+			? ' hidden'
3815
+			: $settings_template_args['show_hide_edit_form'];
3816
+
3817
+
3818
+		$settings_template_args['on_off_action'] = $active ? 'messenger-off' : 'messenger-on';
3819
+		$settings_template_args['nonce'] = wp_create_nonce('activate_' . $messenger->name . '_toggle_nonce');
3820
+		$settings_template_args['on_off_status'] = $active ? true : false;
3821
+		$template = EE_MSG_TEMPLATE_PATH . 'ee_msg_m_settings_content.template.php';
3822
+		$content = EEH_Template::display_template(
3823
+			$template,
3824
+			$settings_template_args,
3825
+			true
3826
+		);
3827
+
3828
+		return $content;
3829
+	}
3830
+
3831
+
3832
+	/**
3833
+	 * used by ajax on the messages settings page to activate|deactivate the messenger
3834
+	 *
3835
+	 * @throws DomainException
3836
+	 * @throws EE_Error
3837
+	 * @throws InvalidDataTypeException
3838
+	 * @throws InvalidInterfaceException
3839
+	 * @throws InvalidArgumentException
3840
+	 * @throws ReflectionException
3841
+	 */
3842
+	public function activate_messenger_toggle()
3843
+	{
3844
+		$success = true;
3845
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3846
+		// let's check that we have required data
3847
+		if (! isset($this->_req_data['messenger'])) {
3848
+			EE_Error::add_error(
3849
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3850
+				__FILE__,
3851
+				__FUNCTION__,
3852
+				__LINE__
3853
+			);
3854
+			$success = false;
3855
+		}
3856
+
3857
+		// do a nonce check here since we're not arriving via a normal route
3858
+		$nonce = isset($this->_req_data['activate_nonce'])
3859
+			? sanitize_text_field($this->_req_data['activate_nonce'])
3860
+			: '';
3861
+		$nonce_ref = 'activate_' . $this->_req_data['messenger'] . '_toggle_nonce';
3862
+
3863
+		$this->_verify_nonce($nonce, $nonce_ref);
3864
+
3865
+
3866
+		if (! isset($this->_req_data['status'])) {
3867
+			EE_Error::add_error(
3868
+				esc_html__(
3869
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3870
+					'event_espresso'
3871
+				),
3872
+				__FILE__,
3873
+				__FUNCTION__,
3874
+				__LINE__
3875
+			);
3876
+			$success = false;
3877
+		}
3878
+
3879
+		// do check to verify we have a valid status.
3880
+		$status = $this->_req_data['status'];
3881
+
3882
+		if ($status !== 'off' && $status !== 'on') {
3883
+			EE_Error::add_error(
3884
+				sprintf(
3885
+					esc_html__('The given status (%s) is not valid. Must be "off" or "on"', 'event_espresso'),
3886
+					$this->_req_data['status']
3887
+				),
3888
+				__FILE__,
3889
+				__FUNCTION__,
3890
+				__LINE__
3891
+			);
3892
+			$success = false;
3893
+		}
3894
+
3895
+		if ($success) {
3896
+			// made it here?  Stop dawdling then!!
3897
+			$success = $status === 'off'
3898
+				? $this->_deactivate_messenger($this->_req_data['messenger'])
3899
+				: $this->_activate_messenger($this->_req_data['messenger']);
3900
+		}
3901
+
3902
+		$this->_template_args['success'] = $success;
3903
+
3904
+		// no special instructions so let's just do the json return (which should automatically do all the special stuff).
3905
+		$this->_return_json();
3906
+	}
3907
+
3908
+
3909
+	/**
3910
+	 * used by ajax from the messages settings page to activate|deactivate a message type
3911
+	 *
3912
+	 * @throws DomainException
3913
+	 * @throws EE_Error
3914
+	 * @throws ReflectionException
3915
+	 * @throws InvalidDataTypeException
3916
+	 * @throws InvalidInterfaceException
3917
+	 * @throws InvalidArgumentException
3918
+	 */
3919
+	public function activate_mt_toggle()
3920
+	{
3921
+		$success = true;
3922
+		$this->_prep_default_response_for_messenger_or_message_type_toggle();
3923
+
3924
+		// let's make sure we have the necessary data
3925
+		if (! isset($this->_req_data['message_type'])) {
3926
+			EE_Error::add_error(
3927
+				esc_html__('Message Type name needed to toggle activation. None given', 'event_espresso'),
3928
+				__FILE__,
3929
+				__FUNCTION__,
3930
+				__LINE__
3931
+			);
3932
+			$success = false;
3933
+		}
3934
+
3935
+		if (! isset($this->_req_data['messenger'])) {
3936
+			EE_Error::add_error(
3937
+				esc_html__('Messenger name needed to toggle activation. None given', 'event_espresso'),
3938
+				__FILE__,
3939
+				__FUNCTION__,
3940
+				__LINE__
3941
+			);
3942
+			$success = false;
3943
+		}
3944
+
3945
+		if (! isset($this->_req_data['status'])) {
3946
+			EE_Error::add_error(
3947
+				esc_html__(
3948
+					'Messenger status needed to know whether activation or deactivation is happening. No status is given',
3949
+					'event_espresso'
3950
+				),
3951
+				__FILE__,
3952
+				__FUNCTION__,
3953
+				__LINE__
3954
+			);
3955
+			$success = false;
3956
+		}
3957
+
3958
+
3959
+		// do check to verify we have a valid status.
3960
+		$status = $this->_req_data['status'];
3961
+
3962
+		if ($status !== 'activate' && $status !== 'deactivate') {
3963
+			EE_Error::add_error(
3964
+				sprintf(
3965
+					esc_html__('The given status (%s) is not valid. Must be "active" or "inactive"', 'event_espresso'),
3966
+					$this->_req_data['status']
3967
+				),
3968
+				__FILE__,
3969
+				__FUNCTION__,
3970
+				__LINE__
3971
+			);
3972
+			$success = false;
3973
+		}
3974
+
3975
+
3976
+		// do a nonce check here since we're not arriving via a normal route
3977
+		$nonce = isset($this->_req_data['mt_nonce']) ? sanitize_text_field($this->_req_data['mt_nonce']) : '';
3978
+		$nonce_ref = $this->_req_data['message_type'] . '_nonce';
3979
+
3980
+		$this->_verify_nonce($nonce, $nonce_ref);
3981
+
3982
+		if ($success) {
3983
+			// made it here? um, what are you waiting for then?
3984
+			$success = $status === 'deactivate'
3985
+				? $this->_deactivate_message_type_for_messenger(
3986
+					$this->_req_data['messenger'],
3987
+					$this->_req_data['message_type']
3988
+				)
3989
+				: $this->_activate_message_type_for_messenger(
3990
+					$this->_req_data['messenger'],
3991
+					$this->_req_data['message_type']
3992
+				);
3993
+		}
3994
+
3995
+		$this->_template_args['success'] = $success;
3996
+		$this->_return_json();
3997
+	}
3998
+
3999
+
4000
+	/**
4001
+	 * Takes care of processing activating a messenger and preparing the appropriate response.
4002
+	 *
4003
+	 * @param string $messenger_name The name of the messenger being activated
4004
+	 * @return bool
4005
+	 * @throws DomainException
4006
+	 * @throws EE_Error
4007
+	 * @throws InvalidArgumentException
4008
+	 * @throws ReflectionException
4009
+	 * @throws InvalidDataTypeException
4010
+	 * @throws InvalidInterfaceException
4011
+	 */
4012
+	protected function _activate_messenger($messenger_name)
4013
+	{
4014
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4015
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4016
+		$message_types_to_activate = $active_messenger instanceof EE_Messenger
4017
+			? $active_messenger->get_default_message_types()
4018
+			: array();
4019
+
4020
+		// ensure is active
4021
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_types_to_activate);
4022
+
4023
+		// set response_data for reload
4024
+		foreach ($message_types_to_activate as $message_type_name) {
4025
+			/** @var EE_message_type $message_type */
4026
+			$message_type = $this->_message_resource_manager->get_message_type($message_type_name);
4027
+			if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4028
+				$messenger_name,
4029
+				$message_type_name
4030
+			)
4031
+				&& $message_type instanceof EE_message_type
4032
+			) {
4033
+				$this->_template_args['data']['active_mts'][] = $message_type_name;
4034
+				if ($message_type->get_admin_settings_fields()) {
4035
+					$this->_template_args['data']['mt_reload'][] = $message_type_name;
4036
+				}
4037
+			}
4038
+		}
4039
+
4040
+		// add success message for activating messenger
4041
+		return $this->_setup_response_message_for_activating_messenger_with_message_types($active_messenger);
4042
+	}
4043
+
4044
+
4045
+	/**
4046
+	 * Takes care of processing deactivating a messenger and preparing the appropriate response.
4047
+	 *
4048
+	 * @param string $messenger_name The name of the messenger being activated
4049
+	 * @return bool
4050
+	 * @throws DomainException
4051
+	 * @throws EE_Error
4052
+	 * @throws InvalidArgumentException
4053
+	 * @throws ReflectionException
4054
+	 * @throws InvalidDataTypeException
4055
+	 * @throws InvalidInterfaceException
4056
+	 */
4057
+	protected function _deactivate_messenger($messenger_name)
4058
+	{
4059
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4060
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4061
+		$this->_message_resource_manager->deactivate_messenger($messenger_name);
4062
+
4063
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types($active_messenger);
4064
+	}
4065
+
4066
+
4067
+	/**
4068
+	 * Takes care of processing activating a message type for a messenger and preparing the appropriate response.
4069
+	 *
4070
+	 * @param string $messenger_name    The name of the messenger the message type is being activated for.
4071
+	 * @param string $message_type_name The name of the message type being activated for the messenger
4072
+	 * @return bool
4073
+	 * @throws DomainException
4074
+	 * @throws EE_Error
4075
+	 * @throws InvalidArgumentException
4076
+	 * @throws ReflectionException
4077
+	 * @throws InvalidDataTypeException
4078
+	 * @throws InvalidInterfaceException
4079
+	 */
4080
+	protected function _activate_message_type_for_messenger($messenger_name, $message_type_name)
4081
+	{
4082
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4083
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4084
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4085
+		$message_type_to_activate = $this->_message_resource_manager->get_message_type($message_type_name);
4086
+
4087
+		// ensure is active
4088
+		$this->_message_resource_manager->activate_messenger($active_messenger, $message_type_name);
4089
+
4090
+		// set response for load
4091
+		if ($this->_message_resource_manager->is_message_type_active_for_messenger(
4092
+			$messenger_name,
4093
+			$message_type_name
4094
+		)
4095
+		) {
4096
+			$this->_template_args['data']['active_mts'][] = $message_type_name;
4097
+			if ($message_type_to_activate->get_admin_settings_fields()) {
4098
+				$this->_template_args['data']['mt_reload'][] = $message_type_name;
4099
+			}
4100
+		}
4101
+
4102
+		return $this->_setup_response_message_for_activating_messenger_with_message_types(
4103
+			$active_messenger,
4104
+			$message_type_to_activate
4105
+		);
4106
+	}
4107
+
4108
+
4109
+	/**
4110
+	 * Takes care of processing deactivating a message type for a messenger and preparing the appropriate response.
4111
+	 *
4112
+	 * @param string $messenger_name    The name of the messenger the message type is being deactivated for.
4113
+	 * @param string $message_type_name The name of the message type being deactivated for the messenger
4114
+	 * @return bool
4115
+	 * @throws DomainException
4116
+	 * @throws EE_Error
4117
+	 * @throws InvalidArgumentException
4118
+	 * @throws ReflectionException
4119
+	 * @throws InvalidDataTypeException
4120
+	 * @throws InvalidInterfaceException
4121
+	 */
4122
+	protected function _deactivate_message_type_for_messenger($messenger_name, $message_type_name)
4123
+	{
4124
+		/** @var EE_messenger $active_messenger This will be present because it can't be toggled if it isn't */
4125
+		$active_messenger = $this->_message_resource_manager->get_messenger($messenger_name);
4126
+		/** @var EE_message_type $message_type_to_activate This will be present because it can't be toggled if it isn't */
4127
+		$message_type_to_deactivate = $this->_message_resource_manager->get_message_type($message_type_name);
4128
+		$this->_message_resource_manager->deactivate_message_type_for_messenger($message_type_name, $messenger_name);
4129
+
4130
+		return $this->_setup_response_message_for_deactivating_messenger_with_message_types(
4131
+			$active_messenger,
4132
+			$message_type_to_deactivate
4133
+		);
4134
+	}
4135
+
4136
+
4137
+	/**
4138
+	 * This just initializes the defaults for activating messenger and message type responses.
4139
+	 */
4140
+	protected function _prep_default_response_for_messenger_or_message_type_toggle()
4141
+	{
4142
+		$this->_template_args['data']['active_mts'] = array();
4143
+		$this->_template_args['data']['mt_reload'] = array();
4144
+	}
4145
+
4146
+
4147
+	/**
4148
+	 * Setup appropriate response for activating a messenger and/or message types
4149
+	 *
4150
+	 * @param EE_messenger         $messenger
4151
+	 * @param EE_message_type|null $message_type
4152
+	 * @return bool
4153
+	 * @throws DomainException
4154
+	 * @throws EE_Error
4155
+	 * @throws InvalidArgumentException
4156
+	 * @throws ReflectionException
4157
+	 * @throws InvalidDataTypeException
4158
+	 * @throws InvalidInterfaceException
4159
+	 */
4160
+	protected function _setup_response_message_for_activating_messenger_with_message_types(
4161
+		$messenger,
4162
+		EE_Message_Type $message_type = null
4163
+	) {
4164
+		// if $messenger isn't a valid messenger object then get out.
4165
+		if (! $messenger instanceof EE_Messenger) {
4166
+			EE_Error::add_error(
4167
+				esc_html__('The messenger being activated is not a valid messenger', 'event_espresso'),
4168
+				__FILE__,
4169
+				__FUNCTION__,
4170
+				__LINE__
4171
+			);
4172
+
4173
+			return false;
4174
+		}
4175
+		// activated
4176
+		if ($this->_template_args['data']['active_mts']) {
4177
+			EE_Error::overwrite_success();
4178
+			// activated a message type with the messenger
4179
+			if ($message_type instanceof EE_message_type) {
4180
+				EE_Error::add_success(
4181
+					sprintf(
4182
+						esc_html__(
4183
+							'%s message type has been successfully activated with the %s messenger',
4184
+							'event_espresso'
4185
+						),
4186
+						ucwords($message_type->label['singular']),
4187
+						ucwords($messenger->label['singular'])
4188
+					)
4189
+				);
4190
+
4191
+				// if message type was invoice then let's make sure we activate the invoice payment method.
4192
+				if ($message_type->name === 'invoice') {
4193
+					EE_Registry::instance()->load_lib('Payment_Method_Manager');
4194
+					$pm = EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
4195
+					if ($pm instanceof EE_Payment_Method) {
4196
+						EE_Error::add_attention(
4197
+							esc_html__(
4198
+								'Activating the invoice message type also automatically activates the invoice payment method.  If you do not wish the invoice payment method to be active, or to change its settings, visit the payment method admin page.',
4199
+								'event_espresso'
4200
+							)
4201
+						);
4202
+					}
4203
+				}
4204
+				// just toggles the entire messenger
4205
+			} else {
4206
+				EE_Error::add_success(
4207
+					sprintf(
4208
+						esc_html__('%s messenger has been successfully activated', 'event_espresso'),
4209
+						ucwords($messenger->label['singular'])
4210
+					)
4211
+				);
4212
+			}
4213
+
4214
+			return true;
4215
+
4216
+			// possible error condition. This will happen when our active_mts data is empty because it is validated for actual active
4217
+			// message types after the activation process.  However its possible some messengers don't HAVE any default_message_types
4218
+			// in which case we just give a success message for the messenger being successfully activated.
4219
+		} else {
4220
+			if (! $messenger->get_default_message_types()) {
4221
+				// messenger doesn't have any default message types so still a success.
4222
+				EE_Error::add_success(
4223
+					sprintf(
4224
+						esc_html__('%s messenger was successfully activated.', 'event_espresso'),
4225
+						ucwords($messenger->label['singular'])
4226
+					)
4227
+				);
4228
+
4229
+				return true;
4230
+			} else {
4231
+				EE_Error::add_error(
4232
+					$message_type instanceof EE_message_type
4233
+						? sprintf(
4234
+							esc_html__(
4235
+								'%s message type was not successfully activated with the %s messenger',
4236
+								'event_espresso'
4237
+							),
4238
+							ucwords($message_type->label['singular']),
4239
+							ucwords($messenger->label['singular'])
4240
+						)
4241
+						: sprintf(
4242
+							esc_html__('%s messenger was not successfully activated', 'event_espresso'),
4243
+							ucwords($messenger->label['singular'])
4244
+						),
4245
+					__FILE__,
4246
+					__FUNCTION__,
4247
+					__LINE__
4248
+				);
4249
+
4250
+				return false;
4251
+			}
4252
+		}
4253
+	}
4254
+
4255
+
4256
+	/**
4257
+	 * This sets up the appropriate response for deactivating a messenger and/or message type.
4258
+	 *
4259
+	 * @param EE_messenger         $messenger
4260
+	 * @param EE_message_type|null $message_type
4261
+	 * @return bool
4262
+	 * @throws DomainException
4263
+	 * @throws EE_Error
4264
+	 * @throws InvalidArgumentException
4265
+	 * @throws ReflectionException
4266
+	 * @throws InvalidDataTypeException
4267
+	 * @throws InvalidInterfaceException
4268
+	 */
4269
+	protected function _setup_response_message_for_deactivating_messenger_with_message_types(
4270
+		$messenger,
4271
+		EE_message_type $message_type = null
4272
+	) {
4273
+		EE_Error::overwrite_success();
4274
+
4275
+		// if $messenger isn't a valid messenger object then get out.
4276
+		if (! $messenger instanceof EE_Messenger) {
4277
+			EE_Error::add_error(
4278
+				esc_html__('The messenger being deactivated is not a valid messenger', 'event_espresso'),
4279
+				__FILE__,
4280
+				__FUNCTION__,
4281
+				__LINE__
4282
+			);
4283
+
4284
+			return false;
4285
+		}
4286
+
4287
+		if ($message_type instanceof EE_message_type) {
4288
+			$message_type_name = $message_type->name;
4289
+			EE_Error::add_success(
4290
+				sprintf(
4291
+					esc_html__(
4292
+						'%s message type has been successfully deactivated for the %s messenger.',
4293
+						'event_espresso'
4294
+					),
4295
+					ucwords($message_type->label['singular']),
4296
+					ucwords($messenger->label['singular'])
4297
+				)
4298
+			);
4299
+		} else {
4300
+			$message_type_name = '';
4301
+			EE_Error::add_success(
4302
+				sprintf(
4303
+					esc_html__('%s messenger has been successfully deactivated.', 'event_espresso'),
4304
+					ucwords($messenger->label['singular'])
4305
+				)
4306
+			);
4307
+		}
4308
+
4309
+		// if messenger was html or message type was invoice then let's make sure we deactivate invoice payment method.
4310
+		if ($messenger->name === 'html' || $message_type_name === 'invoice') {
4311
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
4312
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method('invoice');
4313
+			if ($count_updated > 0) {
4314
+				$msg = $message_type_name === 'invoice'
4315
+					? esc_html__(
4316
+						'Deactivating the invoice message type also automatically deactivates the invoice payment method. In order for invoices to be generated the invoice message type must be active. If you completed this action by mistake, simply reactivate the invoice message type and then visit the payment methods admin page to reactivate the invoice payment method.',
4317
+						'event_espresso'
4318
+					)
4319
+					: esc_html__(
4320
+						'Deactivating the html messenger also automatically deactivates the invoice payment method.  In order for invoices to be generated the html messenger must be be active.  If you completed this action by mistake, simply reactivate the html messenger, then visit the payment methods admin page to reactivate the invoice payment method.',
4321
+						'event_espresso'
4322
+					);
4323
+				EE_Error::add_attention($msg);
4324
+			}
4325
+		}
4326
+
4327
+		return true;
4328
+	}
4329
+
4330
+
4331
+	/**
4332
+	 * handles updating a message type form on messenger activation IF the message type has settings fields. (via ajax)
4333
+	 *
4334
+	 * @throws DomainException
4335
+	 */
4336
+	public function update_mt_form()
4337
+	{
4338
+		if (! isset($this->_req_data['messenger']) || ! isset($this->_req_data['message_type'])) {
4339
+			EE_Error::add_error(
4340
+				esc_html__('Require message type or messenger to send an updated form', 'event_espresso'),
4341
+				__FILE__,
4342
+				__FUNCTION__,
4343
+				__LINE__
4344
+			);
4345
+			$this->_return_json();
4346
+		}
4347
+
4348
+		$message_types = $this->get_installed_message_types();
4349
+
4350
+		$message_type = $message_types[ $this->_req_data['message_type'] ];
4351
+		$messenger = $this->_message_resource_manager->get_active_messenger($this->_req_data['messenger']);
4352
+
4353
+		$content = $this->_message_type_settings_content(
4354
+			$message_type,
4355
+			$messenger,
4356
+			true
4357
+		);
4358
+		$this->_template_args['success'] = true;
4359
+		$this->_template_args['content'] = $content;
4360
+		$this->_return_json();
4361
+	}
4362
+
4363
+
4364
+	/**
4365
+	 * this handles saving the settings for a messenger or message type
4366
+	 *
4367
+	 */
4368
+	public function save_settings()
4369
+	{
4370
+		if (! isset($this->_req_data['type'])) {
4371
+			EE_Error::add_error(
4372
+				esc_html__(
4373
+					'Cannot save settings because type is unknown (messenger settings or messsage type settings?)',
4374
+					'event_espresso'
4375
+				),
4376
+				__FILE__,
4377
+				__FUNCTION__,
4378
+				__LINE__
4379
+			);
4380
+			$this->_template_args['error'] = true;
4381
+			$this->_return_json();
4382
+		}
4383
+
4384
+
4385
+		if ($this->_req_data['type'] === 'messenger') {
4386
+			// this should be an array.
4387
+			$settings = $this->_req_data['messenger_settings'];
4388
+			$messenger = $settings['messenger'];
4389
+			// let's setup the settings data
4390
+			foreach ($settings as $key => $value) {
4391
+				switch ($key) {
4392
+					case 'messenger':
4393
+						unset($settings['messenger']);
4394
+						break;
4395
+					case 'message_types':
4396
+						unset($settings['message_types']);
4397
+						break;
4398
+					default:
4399
+						$settings[ $key ] = $value;
4400
+						break;
4401
+				}
4402
+			}
4403
+			$this->_message_resource_manager->add_settings_for_messenger($messenger, $settings);
4404
+		} elseif ($this->_req_data['type'] === 'message_type') {
4405
+			$settings = $this->_req_data['message_type_settings'];
4406
+			$messenger = $settings['messenger'];
4407
+			$message_type = $settings['message_type'];
4408
+
4409
+			foreach ($settings as $key => $value) {
4410
+				switch ($key) {
4411
+					case 'messenger':
4412
+						unset($settings['messenger']);
4413
+						break;
4414
+					case 'message_type':
4415
+						unset($settings['message_type']);
4416
+						break;
4417
+					default:
4418
+						$settings[ $key ] = $value;
4419
+						break;
4420
+				}
4421
+			}
4422
+
4423
+			$this->_message_resource_manager->add_settings_for_message_type($messenger, $message_type, $settings);
4424
+		}
4425
+
4426
+		// okay we should have the data all setup.  Now we just update!
4427
+		$success = $this->_message_resource_manager->update_active_messengers_option();
4428
+
4429
+		if ($success) {
4430
+			EE_Error::add_success(__('Settings updated', 'event_espresso'));
4431
+		} else {
4432
+			EE_Error::add_error(
4433
+				esc_html__(
4434
+					'Settings did not get updated',
4435
+					'event_espresso'
4436
+				),
4437
+				__FILE__,
4438
+				__FUNCTION__,
4439
+				__LINE__
4440
+			);
4441
+		}
4442
+
4443
+		$this->_template_args['success'] = $success;
4444
+		$this->_return_json();
4445
+	}
4446
+
4447
+
4448
+
4449
+
4450
+	/**  EE MESSAGE PROCESSING ACTIONS **/
4451
+
4452
+
4453
+	/**
4454
+	 * This immediately generates any EE_Message ID's that are selected that are EEM_Message::status_incomplete
4455
+	 * However, this does not send immediately, it just queues for sending.
4456
+	 *
4457
+	 * @since 4.9.0
4458
+	 * @throws EE_Error
4459
+	 * @throws InvalidDataTypeException
4460
+	 * @throws InvalidInterfaceException
4461
+	 * @throws InvalidArgumentException
4462
+	 * @throws ReflectionException
4463
+	 */
4464
+	protected function _generate_now()
4465
+	{
4466
+		EED_Messages::generate_now($this->_get_msg_ids_from_request());
4467
+		$this->_redirect_after_action(false, '', '', array(), true);
4468
+	}
4469
+
4470
+
4471
+	/**
4472
+	 * This immediately generates AND sends any EE_Message's selected that are EEM_Message::status_incomplete or that
4473
+	 * are EEM_Message::status_resend or EEM_Message::status_idle
4474
+	 *
4475
+	 * @since 4.9.0
4476
+	 * @throws EE_Error
4477
+	 * @throws InvalidDataTypeException
4478
+	 * @throws InvalidInterfaceException
4479
+	 * @throws InvalidArgumentException
4480
+	 * @throws ReflectionException
4481
+	 */
4482
+	protected function _generate_and_send_now()
4483
+	{
4484
+		EED_Messages::generate_and_send_now($this->_get_msg_ids_from_request());
4485
+		$this->_redirect_after_action(false, '', '', array(), true);
4486
+	}
4487
+
4488
+
4489
+	/**
4490
+	 * This queues any EEM_Message::status_sent EE_Message ids in the request for resending.
4491
+	 *
4492
+	 * @since 4.9.0
4493
+	 * @throws EE_Error
4494
+	 * @throws InvalidDataTypeException
4495
+	 * @throws InvalidInterfaceException
4496
+	 * @throws InvalidArgumentException
4497
+	 * @throws ReflectionException
4498
+	 */
4499
+	protected function _queue_for_resending()
4500
+	{
4501
+		EED_Messages::queue_for_resending($this->_get_msg_ids_from_request());
4502
+		$this->_redirect_after_action(false, '', '', array(), true);
4503
+	}
4504
+
4505
+
4506
+	/**
4507
+	 *  This sends immediately any EEM_Message::status_idle or EEM_Message::status_resend messages in the queue
4508
+	 *
4509
+	 * @since 4.9.0
4510
+	 * @throws EE_Error
4511
+	 * @throws InvalidDataTypeException
4512
+	 * @throws InvalidInterfaceException
4513
+	 * @throws InvalidArgumentException
4514
+	 * @throws ReflectionException
4515
+	 */
4516
+	protected function _send_now()
4517
+	{
4518
+		EED_Messages::send_now($this->_get_msg_ids_from_request());
4519
+		$this->_redirect_after_action(false, '', '', array(), true);
4520
+	}
4521
+
4522
+
4523
+	/**
4524
+	 * Deletes EE_messages for IDs in the request.
4525
+	 *
4526
+	 * @since 4.9.0
4527
+	 * @throws EE_Error
4528
+	 * @throws InvalidDataTypeException
4529
+	 * @throws InvalidInterfaceException
4530
+	 * @throws InvalidArgumentException
4531
+	 */
4532
+	protected function _delete_ee_messages()
4533
+	{
4534
+		$msg_ids = $this->_get_msg_ids_from_request();
4535
+		$deleted_count = 0;
4536
+		foreach ($msg_ids as $msg_id) {
4537
+			if (EEM_Message::instance()->delete_by_ID($msg_id)) {
4538
+				$deleted_count++;
4539
+			}
4540
+		}
4541
+		if ($deleted_count) {
4542
+			EE_Error::add_success(
4543
+				esc_html(
4544
+					_n(
4545
+						'Message successfully deleted',
4546
+						'Messages successfully deleted',
4547
+						$deleted_count,
4548
+						'event_espresso'
4549
+					)
4550
+				)
4551
+			);
4552
+			$this->_redirect_after_action(
4553
+				false,
4554
+				'',
4555
+				'',
4556
+				array(),
4557
+				true
4558
+			);
4559
+		} else {
4560
+			EE_Error::add_error(
4561
+				_n('The message was not deleted.', 'The messages were not deleted', count($msg_ids), 'event_espresso'),
4562
+				__FILE__,
4563
+				__FUNCTION__,
4564
+				__LINE__
4565
+			);
4566
+			$this->_redirect_after_action(false, '', '', array(), true);
4567
+		}
4568
+	}
4569
+
4570
+
4571
+	/**
4572
+	 *  This looks for 'MSG_ID' key in the request and returns an array of MSG_ID's if present.
4573
+	 *
4574
+	 * @since 4.9.0
4575
+	 * @return array
4576
+	 */
4577
+	protected function _get_msg_ids_from_request()
4578
+	{
4579
+		if (! isset($this->_req_data['MSG_ID'])) {
4580
+			return array();
4581
+		}
4582
+
4583
+		return is_array($this->_req_data['MSG_ID'])
4584
+			? array_keys($this->_req_data['MSG_ID'])
4585
+			: array($this->_req_data['MSG_ID']);
4586
+	}
4587 4587
 }
Please login to merge, or discard this patch.